ilml-plugin-linkedin 1.15.0 → 1.16.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.
@@ -242,14 +242,14 @@ function findEntryContainer(root) {
242
242
  `),process.exit(1));var ft=ln({token:dt});function un(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 dn({scriptName:e,mode:t,status:n,error:o,duration:r}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),c=r?` ${un(r)}`:"",s=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${s} \u2014 ${l}${c}`}async function pt({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let s=`**${dn({scriptName:e,mode:t,status:n,error:r,duration:i})}**
243
243
 
244
244
  ${o.join(`
245
- `)}`;try{await ft.addMessage(l,s)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var pn=fn(import.meta.url),mn=oe.dirname(oe.dirname(pn)),Ne=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(mn,"collected-profiles"),Fe=oe.join(Ne,"run-log.json");function hn(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 l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function mt(){try{if(!J.existsSync(Fe))return{runs:[]};let e=JSON.parse(J.readFileSync(Fe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ht(e){J.existsSync(Ne)||J.mkdirSync(Ne,{recursive:!0});try{hn(Fe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function gt(e,t="default"){let n=mt();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.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(l=>new Date(l.timestamp).getTime()>i),ht(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Me(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=mt(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let s=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}ht(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";pt({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Ie();Ie();import{getPluginConfig as gn}from"@ilivemylife/graph-sdk";var yn=await gn();for(let[e,t]of Object.entries(yn))process.env[e]===void 0&&(process.env[e]=t);var ar=process.env.LINKEDIN_NAME,ae=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),cr=Object.freeze(new Set([ae.DRAFT,ae.CONFIRMED,ae.NEEDS_REVIEW])),ur=Object.freeze(new Set([ae.DRAFT,ae.CONFIRMED,ae.REJECTED,ae.NEEDS_REVIEW]));import"dotenv/config";import*as R from"fs";import*as L from"path";import{fileURLToPath as wn}from"url";var Sn=wn(import.meta.url),bn=L.dirname(L.dirname(Sn)),X=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"collected-profiles"):L.join(bn,"collected-profiles"),Le=L.join(X,"people.json"),hr=L.join(X,"jobs.json"),St=L.join(X,"quota.json"),gr=L.join(X,"conversations.json"),yr=L.join(X,"sync-state.json"),wr=L.join(X,"application-questions.json"),Pe=L.join(X,"profile-history"),bt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ye=bt(process.env.CONNECT_MAX_DAILY,20),we=bt(process.env.CONNECT_MAX_WEEKLY,100),pe=null,kn=null,Q=null,vn=null,$n=null,Cn=null;function kt(){pe=null,kn=null,Q=null,vn=null,$n=null,Cn=null}function _e(){R.existsSync(X)||R.mkdirSync(X,{recursive:!0})}function qe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";R.writeFileSync(o,n);for(let r=0;r<3;r++)try{R.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Be(e,t){if(!R.existsSync(e))return null;try{let n=JSON.parse(R.readFileSync(e,"utf-8"));try{R.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${L.resolve(e)}`);let o=e+".backup";if(R.existsSync(o))try{let r=JSON.parse(R.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{R.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{R.copyFileSync(e,e+".corrupted")}catch{}return null}}function Se(){return new Date().toISOString().split("T")[0]}var xn=["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"],En=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Ue(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function An(){R.existsSync(Pe)||R.mkdirSync(Pe,{recursive:!0})}function vt(e){let t=Ue(e);return t?L.join(Pe,`${t}.json`):null}function In(e){let t=vt(e);return t?Be(t,`profile-history/${Ue(e)}.json`)||[]:[]}function Dn(e,t){let n=vt(e);if(!n)return;An();let o=In(e);o.unshift(t);try{qe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${Ue(e)}: ${r.message}`)}}function yt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function wt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function _n(e,t){if(!e)return[];let n=[];for(let o of En){let r=e[o],i=t[o];yt(r)||yt(i)||wt(r)!==wt(i)&&n.push(o)}return n}function Rn(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 re(){return pe||(_e(),pe=Be(Le,"people.json")||{},pe)}function Je(e){_e(),pe=e;try{qe(Le,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${L.resolve(Le)}`)}}function De(e,t={}){if(!e)return null;let n=re(),o=Se(),r=new Date().toISOString(),i=n[e];if(i){let l=_n(i,t);l.length>0&&(Dn(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:Rn(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 c of xn)if(t[c]!=null){if(Array.isArray(t[c])&&t[c].length===0&&Array.isArray(i[c])&&i[c].length>0)continue;i[c]=t[c]}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,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Je(n),n[e]}function $t(e,t){if(!e||!t)return;let n=re(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Se(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Je(n))}function Ct(e){return e&&re()[e]?.connectionStatus||null}function xt(e,t,n={}){if(!e)return;n.profileInfo?De(e,n.profileInfo):re()[e]||De(e,{});let o=re(),r=o[e];if(!r)return;let i=Se();r.connectionStatus=t,t==="connected"?r.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(r.requestedConnectionAt||(r.requestedConnectionAt=i)),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),Je(o)}function Et(){return Q||(_e(),Q=Be(St,"quota.json"),(!Q||!Q.connections)&&(Q={connections:[]}),Q)}function Tn(e){_e(),Q=e;try{qe(St,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function At(e,t="unknown"){let n=Et(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Tn(n)}function It(){let e=Et(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ve(){let e=It(),t=Se(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=ye,i=o>=we,l=!r&&!i,c={allowed:l,daily:{sent:n,max:ye},weekly:{sent:o,max:we}};return l||(c.reason=r?`Daily limit reached (${n}/${ye})`:`Weekly limit reached (${o}/${we})`),c}function He(){let e=It(),t=Se(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:ye,remaining:ye-n},weekly:{sent:o,max:we,remaining:we-o}}}async function Tt(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 y(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Rt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Pn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:c=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),await le(e)&&(console.log(" Dismissed Premium overlay"),await y(1500),await Tt(e,t));let a=0;for(let b=0;b<2;b++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(D=>window.scrollTo(0,D),C*T/6),await y(900);let I=await e.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await y(800);let d=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),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"]),I=v=>{let x=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(x)},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:[]},D=document.querySelector("main");if(!D)return T;let B=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],k=Array.from(D.querySelectorAll("h2")),F=B.find(v=>{let x=v.textContent&&v.textContent.trim(),E=(x||"").replace(/\s*\(\d+\)$/,"").trim();return x&&x.length>1&&x.length<100&&!b.has(E)&&!C.has(E)}),z=F?F.textContent.trim():null,M=F?F.parentElement:null;for(;M&&M!==D&&!Array.from(M.children).filter(x=>x.tagName==="P").some(x=>{let E=x.textContent&&x.textContent.trim();return E&&E.length>5&&!I(E)});)M=M.parentElement;let ie=null,te=null,me=null,fe=null;if(M&&M!==D){let v=Array.from(M.children).filter(E=>E.tagName==="P").filter(E=>{let ne=E.textContent&&E.textContent.trim();return ne&&ne.length>5&&!I(ne)});if(v[0]&&(ie=v[0].textContent.trim()),v[1]){let E=v[1].textContent.trim().split(/\s*[·•]\s*/);te=E[0]||null,E.length>1&&(me=E.slice(1).join(" \xB7 "))}let x=Array.from(M.children).filter(E=>E.tagName==="DIV");for(let E=x.length-1;E>=0;E--){let ne=x[E].textContent&&x[E].textContent.trim();if(ne&&!(z&&ne.startsWith(z))&&(fe=ne.split(/[·•]/)[0].trim(),fe))break}}let Ee=null;if(M){let v=M.querySelectorAll("p, span, div");for(let x of v){let E=(x.textContent||"").trim().replace(/^[·•]\s*/,"");if(E==="1st"||E==="2nd"||E==="3rd"){Ee=E;break}}}let Oe=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),_=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),O=_&&_.src||null,j=D.textContent||"",N=null,G=j.match(/(\d+\+?)\s+connections\b/i);G&&(N=G[1]+" connections");let Ae=null,ot=j.match(/(\d+)\s+mutual connection/i),rt=j.match(/and\s+(\d+)\s+other mutual/i),en=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ot?Ae=parseInt(ot[1],10):rt?Ae=2+parseInt(rt[1],10):en&&(Ae=2);let st=null,it=null,lt=k.find(v=>v.textContent&&v.textContent.trim()==="About");if(lt){let v=lt.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").trim();x=x.replace(/^About\s*/,"").trim();let E=x.match(/Top skills\s*(.+?)$/i);if(E){let je=E[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(rn=>rn.trim()).filter(Boolean);je.length>0&&je.length<10&&(it=je)}x=x.split(/\n?…\s*more/i)[0].trim(),x=x.split(/\n?\.\.\.\s*more/i)[0].trim(),x=x.split(/\bTop skills\b/i)[0].trim(),x=x.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),st=x||null}}let at=null,ct=k.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(ct){let v=ct.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);x&&(at=parseInt(x[1].replace(/,/g,""),10))}}let tn=[...new Set(k.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==z).filter(v=>b.has(v)))],he=document.body.textContent||"",nn=/#OpenToWork\b/i.test(he)||/\bOpen to work\b/.test(he),on=/#Hiring\b/i.test(he)||/\bI'?m hiring\b/i.test(he)||/\bWe are hiring\b/i.test(he);return{name:z,title:ie,location:fe,currentCompany:te,currentSchool:me,connectionDegree:Ee,hasVerifiedBadge:Oe,photoUrl:O,connectionsLevel:N,mutualConnectionsCount:Ae,followers:at,openToWork:nn,hiring:on,about:st,topSkills:it,availableSections:tn}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,f=null,h=null,m=null,S=null,w=null;if(o||r||i||l||c||s){let b=await Promise.resolve().then(()=>(_t(),Dt));o&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(f=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${f.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),c&&(S=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),s&&(w=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...d,profileUrl:t,...p!==null&&{experience:p},...f!==null&&{featured:f},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...S!==null&&{recommendations:S},...w!==null&&{certifications:w}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function $e(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=u=>u&&!u.closest(n),r=u=>Array.from(document.querySelectorAll(u)).filter(o),i=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,s={pendingCount:i.length,pendingLabels:i.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return i.length>0?{status:"pending",debug:s}:l&&!c?{status:"connected",debug:s}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:s}:{status:"not_connected",debug:s}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function We(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(s=u.textContent?.trim(),s&&!s.includes("notification")))return s;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.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 a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).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(a=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=a.toLowerCase().split(" ")[0],f='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(f))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),f=document.querySelectorAll("button[aria-label]");return Array.from(f).filter(m=>{let S=m.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&p.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&f.test(m))return h}return null},s);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,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(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(u)&&(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 u=await e.evaluate((a,d)=>{let p=a.className.includes("muted"),f=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(a.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),w=d?m.includes(d):!0;return{isMuted:p,isStickyHeader:f,inRecommendations:h,hasInvite:S,matchesName:w,ariaLabel:m}},s,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.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 l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let s of c){let u=await e.evaluate(a=>{let d=a.getBoundingClientRect(),p=d.width>0&&d.height>0,f=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:f,top:d.top}},s);if(u.isVisible&&!u.isInStickyHeader){l=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of c)s!==l&&await s.dispose().catch(()=>{});if(!l&&c.length>0&&(l=c[c.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let s=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(p=>{let f=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",m=p.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:f==="Follow"||f==="Message"||f==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let d=a.parentElement;for(let p=0;p<8&&d;p++){for(let f of d.querySelectorAll("button"))if(f.innerText?.trim()==="More"&&f!==a)return f;d=d.parentElement}return null});l=s?.asElement?.()||null,l||await s?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await y(500),await e.evaluate(a=>a.click(),l),await y(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let a=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let p of d){let f=p.querySelector('a[href*="custom-invite"]');if(f)return f;for(let h of p.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=a?.asElement?.()||null,u||await a?.dispose?.().catch(()=>{})}if(!u){let a=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let f of d)for(let h of f.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&p.push(m)}return[...new Set(p)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,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(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(u)&&(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 qn(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await y(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",l=(n.ariaLabel||"").toLowerCase();if(l.includes("invite")){let a=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(a&&!l.includes(a))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${a})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await y(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await y(2e3),"premium_redirect"}else i?(await e.evaluate(a=>a.click(),t),await y(3e3)):(await e.evaluate(a=>a.click(),t),await y(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Bn(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 y(1500);let n=await We(e);if(n){await e.evaluate(r=>r.click(),n),await y(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 y(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Un(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=Ve();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let l=await Jn(e,t,n);return l.connectionSent&&!i&&At(t,o),l}async function Jn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
- --- Connecting: ${u} ---`),c.length>0){let w=re()[t]?.location;if(Rt(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),s.reason="excluded_location",s.profileInfo={location:w},s}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(5e3),await le(e)&&(console.log(" Dismissed Premium overlay"),await y(2e3),await Tt(e,t),await y(2e3)),s.profileInfo=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),$=_=>{let O=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},b={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 b;let I=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],T=Array.from(C.querySelectorAll("h2")),D=I.find(_=>{let O=_.textContent&&_.textContent.trim();return O&&O.length>1&&O.length<100&&!w.has(O)&&O!=="0 notifications"}),B=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==C&&!Array.from(k.children).filter(j=>j.tagName==="P").some(j=>{let N=j.textContent&&j.textContent.trim();return N&&N.length>5&&!$(N)});)k=k.parentElement;let F=null,z=null,M=null;if(k&&k!==C){let _=Array.from(k.children),O=_.filter(N=>N.tagName==="P").filter(N=>{let G=N.textContent&&N.textContent.trim();return G&&G.length>5&&!$(G)});O[0]&&(F=O[0].textContent.trim()),O[1]&&(z=O[1].textContent.trim());let j=_.filter(N=>N.tagName==="DIV");for(let N=j.length-1;N>=0;N--){let G=j[N].textContent&&j[N].textContent.trim();if(G&&!(B&&G.startsWith(B))&&(M=G.split(/[·•]/)[0].trim(),M))break}}let ie=null;if(k){let _=k.querySelectorAll("p, span, div");for(let O of _){let j=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){ie=j;break}}}let te=null,me=T.find(_=>_.textContent&&_.textContent.trim()==="About");if(me){let _=me.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;_&&(te=(_.textContent||"").trim().replace(/^About\s*/,"").trim()||null,te&&(te=te.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let fe=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ee=fe&&fe.src||null,Oe=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:B,title:F,location:M,about:te,company:z,connectionDegree:ie,connectionsCount:null,mutualConnections:null,photoUrl:Ee,hasVerifiedBadge:Oe}}),c.length>0){let w=s.profileInfo?.location,$=re()[t]?.location,b=w||$;if(Rt(b,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${b}`),s.reason="excluded_location",s;!w&&$==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await $e(e);if(s.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await le(e);let p=await We(e);if(!p&&(await le(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await y(2e3),p=await We(e)),!p))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=p.method;let f=await qn(e,p.button);if(f==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(f==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(4e3);let w=await $e(e);if(w==="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: ${w} \u2014 trying More dropdown...`),await le(e),await y(1e3);let $=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if($)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),$),await y(500),await $.click().catch(()=>e.evaluate(C=>C.click(),$)),await y(2e3);let b=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(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),b),await y(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 y(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 y(500),s.reason="premium_required",s}catch(b){return console.log(" More dropdown failed:",b.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 w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await y(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let w=await e.evaluate(()=>{let $=document.querySelector("#interop-outlet")?.shadowRoot;if(!$)return{addNote:!1,sendWithout:!1};let b=$.querySelector('button[aria-label="Add a note"]'),C=$.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!C}});if(w.addNote){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=$?.asElement?.()||null,m||await $.dispose().catch(()=>{})}if(w.sendWithout){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=$?.asElement?.()||null,S||await $.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await y(1500),await e.$("div.modal-upsell")){let b=await Bn(e);return s.success=b,s.connectionSent=b,s.reason=b?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let $=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if($){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",b);await $.type(C,{delay:20}),await y(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I){try{await I.evaluate(T=>T.click())}catch{console.log(" Click timeout, likely still sent")}return await y(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(S){console.log(" Sending without note...");try{await S.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await y(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(m&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(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 w=S;if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(p.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 y(4e3)),await le(e),await y(500);let $=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let C of $){let I=await e.evaluate(T=>{let D=T.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!T.closest('.sticky-header, [class*="sticky"]')}},C);if(I.visible&&!I.inSticky){b=C;break}}!b&&$.length>0&&(b=$[$.length-1]);for(let C of $)C!==b&&await C.dispose().catch(()=>{});if(b)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),b),await y(500),await b.click().catch(()=>e.evaluate(I=>I.click(),b)),await y(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(B=>B.click(),C),await y(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(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 D=await e.$('button[aria-label="Send without a note"]');if(D){console.log(" Modal appeared via More dropdown, sending without note...");try{await D.evaluate(B=>B.click())}catch{}return await y(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(u){console.error(` \u2717 Error: ${u.message}`),s.reason="error",s.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{s.fatal=!0}return s}}async function Ot(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:s=null,excludeLocations:u=[],source:a="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
245
+ `)}`;try{await ft.addMessage(l,s)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var pn=fn(import.meta.url),mn=oe.dirname(oe.dirname(pn)),Ne=process.env.DATA_DIR?oe.resolve(process.env.DATA_DIR,"collected-profiles"):oe.join(mn,"collected-profiles"),Fe=oe.join(Ne,"run-log.json");function hn(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 l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function mt(){try{if(!J.existsSync(Fe))return{runs:[]};let e=JSON.parse(J.readFileSync(Fe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ht(e){J.existsSync(Ne)||J.mkdirSync(Ne,{recursive:!0});try{hn(Fe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function gt(e,t="default"){let n=mt();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.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(l=>new Date(l.timestamp).getTime()>i),ht(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Me(e,t,n=null,o=null){if(!e)return;let r=null;try{let l=mt(),c=l.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,r=c.duration;else{let s=l.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());s&&(s.status=t,s.result=t,s.duration=Date.now()-e.startTime,s.stats=n,s.error=o,r=s.duration)}ht(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";pt({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:o,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}Ie();Ie();import{getPluginConfig as gn}from"@ilivemylife/graph-sdk";var yn=await gn();for(let[e,t]of Object.entries(yn))process.env[e]===void 0&&(process.env[e]=t);var ar=process.env.LINKEDIN_NAME,ae=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),cr=Object.freeze(new Set([ae.DRAFT,ae.CONFIRMED,ae.NEEDS_REVIEW])),ur=Object.freeze(new Set([ae.DRAFT,ae.CONFIRMED,ae.REJECTED,ae.NEEDS_REVIEW]));import"dotenv/config";import*as R from"fs";import*as L from"path";import{fileURLToPath as wn}from"url";var Sn=wn(import.meta.url),bn=L.dirname(L.dirname(Sn)),X=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"collected-profiles"):L.join(bn,"collected-profiles"),Le=L.join(X,"people.json"),hr=L.join(X,"jobs.json"),St=L.join(X,"quota.json"),gr=L.join(X,"conversations.json"),yr=L.join(X,"sync-state.json"),wr=L.join(X,"application-questions.json"),Pe=L.join(X,"profile-history"),bt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ye=bt(process.env.CONNECT_MAX_DAILY,20),we=bt(process.env.CONNECT_MAX_WEEKLY,100),pe=null,kn=null,Q=null,vn=null,$n=null,Cn=null;function kt(){pe=null,kn=null,Q=null,vn=null,$n=null,Cn=null}function _e(){R.existsSync(X)||R.mkdirSync(X,{recursive:!0})}function qe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";R.writeFileSync(o,n);for(let r=0;r<3;r++)try{R.renameSync(o,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Be(e,t){if(!R.existsSync(e))return null;try{let n=JSON.parse(R.readFileSync(e,"utf-8"));try{R.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${L.resolve(e)}`);let o=e+".backup";if(R.existsSync(o))try{let r=JSON.parse(R.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{R.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{R.copyFileSync(e,e+".corrupted")}catch{}return null}}function Se(){return new Date().toISOString().split("T")[0]}var xn=["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"],An=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Ue(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function En(){R.existsSync(Pe)||R.mkdirSync(Pe,{recursive:!0})}function vt(e){let t=Ue(e);return t?L.join(Pe,`${t}.json`):null}function In(e){let t=vt(e);return t?Be(t,`profile-history/${Ue(e)}.json`)||[]:[]}function Dn(e,t){let n=vt(e);if(!n)return;En();let o=In(e);o.unshift(t);try{qe(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${Ue(e)}: ${r.message}`)}}function yt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function wt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function _n(e,t){if(!e)return[];let n=[];for(let o of An){let r=e[o],i=t[o];yt(r)||yt(i)||wt(r)!==wt(i)&&n.push(o)}return n}function Rn(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 re(){return pe||(_e(),pe=Be(Le,"people.json")||{},pe)}function Je(e){_e(),pe=e;try{qe(Le,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${L.resolve(Le)}`)}}function De(e,t={}){if(!e)return null;let n=re(),o=Se(),r=new Date().toISOString(),i=n[e];if(i){let l=_n(i,t);l.length>0&&(Dn(e,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:l,snapshot:Rn(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 c of xn)if(t[c]!=null){if(Array.isArray(t[c])&&t[c].length===0&&Array.isArray(i[c])&&i[c].length>0)continue;i[c]=t[c]}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,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Je(n),n[e]}function $t(e,t){if(!e||!t)return;let n=re(),o=n[e];if(!o)return;o.encounters||(o.encounters=[]);let i={date:Se(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!o.encounters.some(c=>c.date===i.date&&c.source===i.source&&c.action===i.action&&(c.jobId||"")===(i.jobId||""))&&(o.encounters.push(i),o.lastUpdated=new Date().toISOString(),Je(n))}function Ct(e){return e&&re()[e]?.connectionStatus||null}function xt(e,t,n={}){if(!e)return;n.profileInfo?De(e,n.profileInfo):re()[e]||De(e,{});let o=re(),r=o[e];if(!r)return;let i=Se();r.connectionStatus=t,t==="connected"?r.connectionDate=i:(t==="pending"||t==="sent_without_note"||t==="sent_with_note"||t==="sent_without_note_upsell")&&(r.requestedConnectionAt||(r.requestedConnectionAt=i)),r.connectionMethod=n.method||r.connectionMethod,r.messageSent=n.messageSent||r.messageSent,r.lastUpdated=new Date().toISOString(),Je(o)}function At(){return Q||(_e(),Q=Be(St,"quota.json"),(!Q||!Q.connections)&&(Q={connections:[]}),Q)}function Tn(e){_e(),Q=e;try{qe(St,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function Et(e,t="unknown"){let n=At(),o=new Date;n.connections.push({date:o.toISOString().split("T")[0],time:o.toTimeString().split(" ")[0],profileUrl:e,source:t}),Tn(n)}function It(){let e=At(),t=new Date;t.setDate(t.getDate()-7);let n=t.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=n)}function Ve(){let e=It(),t=Se(),n=e.filter(s=>s.date===t).length,o=e.length,r=n>=ye,i=o>=we,l=!r&&!i,c={allowed:l,daily:{sent:n,max:ye},weekly:{sent:o,max:we}};return l||(c.reason=r?`Daily limit reached (${n}/${ye})`:`Weekly limit reached (${o}/${we})`),c}function He(){let e=It(),t=Se(),n=e.filter(r=>r.date===t).length,o=e.length;return{daily:{sent:n,max:ye,remaining:ye-n},weekly:{sent:o,max:we,remaining:we-o}}}async function Tt(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 y(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function Rt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Pn(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:i=!1,extractSkills:l=!1,extractRecommendations:c=!1,extractCertifications:s=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(3e3),await le(e)&&(console.log(" Dismissed Premium overlay"),await y(1500),await Tt(e,t));let a=0;for(let b=0;b<2;b++){let C=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(D=>window.scrollTo(0,D),C*T/6),await y(900);let I=await e.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await y(800);let d=await e.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),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"]),I=v=>{let x=(v||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(x)},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:[]},D=document.querySelector("main");if(!D)return T;let B=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],k=Array.from(D.querySelectorAll("h2")),F=B.find(v=>{let x=v.textContent&&v.textContent.trim(),A=(x||"").replace(/\s*\(\d+\)$/,"").trim();return x&&x.length>1&&x.length<100&&!b.has(A)&&!C.has(A)}),z=F?F.textContent.trim():null,M=F?F.parentElement:null;for(;M&&M!==D&&!Array.from(M.children).filter(x=>x.tagName==="P").some(x=>{let A=x.textContent&&x.textContent.trim();return A&&A.length>5&&!I(A)});)M=M.parentElement;let ie=null,te=null,me=null,fe=null;if(M&&M!==D){let v=Array.from(M.children).filter(A=>A.tagName==="P").filter(A=>{let ne=A.textContent&&A.textContent.trim();return ne&&ne.length>5&&!I(ne)});if(v[0]&&(ie=v[0].textContent.trim()),v[1]){let A=v[1].textContent.trim().split(/\s*[·•]\s*/);te=A[0]||null,A.length>1&&(me=A.slice(1).join(" \xB7 "))}let x=Array.from(M.children).filter(A=>A.tagName==="DIV");for(let A=x.length-1;A>=0;A--){let ne=x[A].textContent&&x[A].textContent.trim();if(ne&&!(z&&ne.startsWith(z))&&(fe=ne.split(/[·•]/)[0].trim(),fe))break}}let Ae=null;if(M){let v=M.querySelectorAll("p, span, div");for(let x of v){let A=(x.textContent||"").trim().replace(/^[·•]\s*/,"");if(A==="1st"||A==="2nd"||A==="3rd"){Ae=A;break}}}let Oe=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),_=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),O=_&&_.src||null,j=D.textContent||"",N=null,G=j.match(/(\d+\+?)\s+connections\b/i);G&&(N=G[1]+" connections");let Ee=null,ot=j.match(/(\d+)\s+mutual connection/i),rt=j.match(/and\s+(\d+)\s+other mutual/i),en=j.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ot?Ee=parseInt(ot[1],10):rt?Ee=2+parseInt(rt[1],10):en&&(Ee=2);let st=null,it=null,lt=k.find(v=>v.textContent&&v.textContent.trim()==="About");if(lt){let v=lt.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").trim();x=x.replace(/^About\s*/,"").trim();let A=x.match(/Top skills\s*(.+?)$/i);if(A){let je=A[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(rn=>rn.trim()).filter(Boolean);je.length>0&&je.length<10&&(it=je)}x=x.split(/\n?…\s*more/i)[0].trim(),x=x.split(/\n?\.\.\.\s*more/i)[0].trim(),x=x.split(/\bTop skills\b/i)[0].trim(),x=x.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),st=x||null}}let at=null,ct=k.find(v=>v.textContent&&v.textContent.trim()==="Activity");if(ct){let v=ct.parentElement;for(;v&&v.tagName!=="SECTION";)v=v.parentElement;if(v){let x=(v.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);x&&(at=parseInt(x[1].replace(/,/g,""),10))}}let tn=[...new Set(k.map(v=>(v.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(v=>v&&v.length>1&&v.length<60&&v!==z).filter(v=>b.has(v)))],he=document.body.textContent||"",nn=/#OpenToWork\b/i.test(he)||/\bOpen to work\b/.test(he),on=/#Hiring\b/i.test(he)||/\bI'?m hiring\b/i.test(he)||/\bWe are hiring\b/i.test(he);return{name:z,title:ie,location:fe,currentCompany:te,currentSchool:me,connectionDegree:Ae,hasVerifiedBadge:Oe,photoUrl:O,connectionsLevel:N,mutualConnectionsCount:Ee,followers:at,openToWork:nn,hiring:on,about:st,topSkills:it,availableSections:tn}});console.log(`Viewed: ${d.name} - ${d.title}`);let p=null,f=null,h=null,m=null,S=null,w=null;if(o||r||i||l||c||s){let b=await Promise.resolve().then(()=>(_t(),Dt));o&&(p=await b.extractExperienceFromDetails(e,t),console.log(` + Experience: ${p.length} entries`)),r&&(f=await b.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${f.length} entries`)),i&&(h=await b.extractEducationFromDetails(e,t),console.log(` + Education: ${h.length} entries`)),l&&(m=await b.extractSkillsFromDetails(e,t),console.log(` + Skills: ${m.length} entries`)),c&&(S=await b.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),s&&(w=await b.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...d,profileUrl:t,...p!==null&&{experience:p},...f!==null&&{featured:f},...h!==null&&{education:h},...m!==null&&{skillsFull:m},...S!==null&&{recommendations:S},...w!==null&&{certifications:w}}}catch(u){console.error(`Error viewing profile ${t}:`,u.message);try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function $e(e){let t=await e.evaluate(()=>{let n='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside',o=u=>u&&!u.closest(n),r=u=>Array.from(document.querySelectorAll(u)).filter(o),i=r('button[aria-label*="Pending"], a[aria-label*="Pending"]'),l=r('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,c=r('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,s={pendingCount:i.length,pendingLabels:i.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!l,hasConnectBtn:!!c};return i.length>0?{status:"pending",debug:s}:l&&!c?{status:"connected",debug:s}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:s}:{status:"not_connected",debug:s}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function We(e){let t=null,n=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim();if(s&&!s.includes("notification"))return s;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(s=u.textContent?.trim(),s&&!s.includes("notification")))return s;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.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 a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).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(a=>{let d=document.querySelectorAll('a[href*="custom-invite"]'),p=a.toLowerCase().split(" ")[0],f='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let h of d){let m=h.getBoundingClientRect();if(m.width===0||m.height===0||h.closest(f))continue;if((h.getAttribute("aria-label")||"").toLowerCase().includes(p))return h}return null},n);let u=t?.asElement?.()||null;if(u||await t?.dispose?.().catch(()=>{}),u)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:u,method:"connect_link"}}if(n){let s=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${s}"`);let u=await e.evaluate(d=>{let p=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),f=document.querySelectorAll("button[aria-label]");return Array.from(f).filter(m=>{let S=m.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&p.test(S)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},s);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(d=>{let p=document.querySelectorAll("button[aria-label]"),f=new RegExp("\\b"+d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of p){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&f.test(m))return h}return null},s);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,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(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(u)&&(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 u=await e.evaluate((a,d)=>{let p=a.className.includes("muted"),f=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(a.getAttribute("aria-label")||"").toLowerCase(),S=m.includes("invite"),w=d?m.includes(d):!0;return{isMuted:p,isStickyHeader:f,inRecommendations:h,hasInvite:S,matchesName:w,ariaLabel:m}},s,r);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.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 l=null,c=await e.$$('button[id*="profile-overflow-action"]');for(let s of c){let u=await e.evaluate(a=>{let d=a.getBoundingClientRect(),p=d.width>0&&d.height>0,f=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:p,isInStickyHeader:f,top:d.top}},s);if(u.isVisible&&!u.isInStickyHeader){l=s,console.log(" Found More button by ID pattern (main)");break}}for(let s of c)s!==l&&await s.dispose().catch(()=>{});if(!l&&c.length>0&&(l=c[c.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let s=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(p=>{let f=p.innerText?.trim(),h=p.getAttribute("aria-label")||"",m=p.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:f==="Follow"||f==="Message"||f==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let d=a.parentElement;for(let p=0;p<8&&d;p++){for(let f of d.querySelectorAll("button"))if(f.innerText?.trim()==="More"&&f!==a)return f;d=d.parentElement}return null});l=s?.asElement?.()||null,l||await s?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await y(500),await e.evaluate(a=>a.click(),l),await y(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let u=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(u||(u=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),u||(u=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),u||(u=await e.$('div[role="button"][aria-label*="Invite"]')),u||(u=await e.$('div[role="button"][aria-label*="connect"]')),!u){let a=await e.evaluateHandle(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let p of d){let f=p.querySelector('a[href*="custom-invite"]');if(f)return f;for(let h of p.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});u=a?.asElement?.()||null,u||await a?.dispose?.().catch(()=>{})}if(!u){let a=await e.evaluate(()=>{let d=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),p=[];for(let f of d)for(let h of f.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&p.push(m)}return[...new Set(p)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,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(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();s.includes("invite")&&!s.includes(u)&&(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 qn(e,t){await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),t),await y(500);let n=await e.evaluate(a=>({tag:a.tagName,ariaLabel:a.getAttribute("aria-label"),href:a.getAttribute("href")}),t),r=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),i=n.tag==="DIV",l=(n.ariaLabel||"").toLowerCase();if(l.includes("invite")){let a=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(a&&!l.includes(a))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${a})`),"wrong_target"}if(r){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(d=>d.click(),t)]),await y(2e3);let a=e.url();if(a.includes("premium")||a.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await y(2e3),"premium_redirect"}else i?(await e.evaluate(a=>a.click(),t),await y(3e3)):(await e.evaluate(a=>a.click(),t),await y(3e3));let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let s=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(s?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Bn(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 y(1500);let n=await We(e);if(n){await e.evaluate(r=>r.click(),n),await y(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 y(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function Un(e,t,n={}){let{source:o="unknown",skipQuotaGate:r=!1,skipQuotaRecord:i=!1}=n;if(!r){let c=Ve();if(!c.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${c.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:c.reason,profileInfo:null}}let l=await Jn(e,t,n);return l.connectionSent&&!i&&Et(t,o),l}async function Jn(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:c=[]}=n,s={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null,resolvedUrl:null};try{let u=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
246
+ --- Connecting: ${u} ---`),c.length>0){let w=re()[t]?.location;if(Rt(w,c))return console.log(` \u26A0 Excluded location (stored): ${w}`),s.reason="excluded_location",s.profileInfo={location:w},s}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(5e3),await le(e)&&(console.log(" Dismissed Premium overlay"),await y(2e3),await Tt(e,t),await y(2e3)),s.profileInfo=await e.evaluate(()=>{let w=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Courses","Test scores","Organizations","More profiles for you","Explore Premium profiles","Suggested for you","Promoted","Ad Options","Don\u2019t want to see this"]),$=_=>{let O=(_||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(O)},b={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 b;let I=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],T=Array.from(C.querySelectorAll("h2")),D=I.find(_=>{let O=_.textContent&&_.textContent.trim();return O&&O.length>1&&O.length<100&&!w.has(O)&&O!=="0 notifications"}),B=D?D.textContent.trim():null,k=D?D.parentElement:null;for(;k&&k!==C&&!Array.from(k.children).filter(j=>j.tagName==="P").some(j=>{let N=j.textContent&&j.textContent.trim();return N&&N.length>5&&!$(N)});)k=k.parentElement;let F=null,z=null,M=null;if(k&&k!==C){let _=Array.from(k.children),O=_.filter(N=>N.tagName==="P").filter(N=>{let G=N.textContent&&N.textContent.trim();return G&&G.length>5&&!$(G)});O[0]&&(F=O[0].textContent.trim()),O[1]&&(z=O[1].textContent.trim());let j=_.filter(N=>N.tagName==="DIV");for(let N=j.length-1;N>=0;N--){let G=j[N].textContent&&j[N].textContent.trim();if(G&&!(B&&G.startsWith(B))&&(M=G.split(/[·•]/)[0].trim(),M))break}}let ie=null;if(k){let _=k.querySelectorAll("p, span, div");for(let O of _){let j=(O.textContent||"").trim().replace(/^[·•]\s*/,"");if(j==="1st"||j==="2nd"||j==="3rd"){ie=j;break}}}let te=null,me=T.find(_=>_.textContent&&_.textContent.trim()==="About");if(me){let _=me.parentElement;for(;_&&_.tagName!=="SECTION";)_=_.parentElement;_&&(te=(_.textContent||"").trim().replace(/^About\s*/,"").trim()||null,te&&(te=te.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let fe=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ae=fe&&fe.src||null,Oe=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:B,title:F,location:M,about:te,company:z,connectionDegree:ie,connectionsCount:null,mutualConnections:null,photoUrl:Ae,hasVerifiedBadge:Oe}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(s.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(c.length>0){let w=s.profileInfo?.location,$=re()[t]?.location,b=w||$;if(Rt(b,c))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${b}`),s.reason="excluded_location",s;!w&&$==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let d=await $e(e);if(s.profileInfo?.connectionDegree==="1st"&&d!=="pending"&&(d!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),d="connected"),d==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),s.reason="pending",s;if(d==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),s.reason="connected",s;await le(e);let p=await We(e);if(!p&&(await le(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await y(2e3),p=await We(e)),!p))return console.log(" \u2717 Connect not found"),s.reason="button_not_found",s;s.method=p.method;let f=await qn(e,p.button);if(f==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),s.reason="wrong_target",s;if(f==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(4e3);let w=await $e(e);if(w==="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: ${w} \u2014 trying More dropdown...`),await le(e),await y(1e3);let $=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if($)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),$),await y(500),await $.click().catch(()=>e.evaluate(C=>C.click(),$)),await y(2e3);let b=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(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(T=>T.click(),b),await y(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 y(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 y(500),s.reason="premium_required",s}catch(b){return console.log(" More dropdown failed:",b.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 w=await e.$('button[aria-label="Dismiss"]');return w&&await w.click(),await y(500),s.reason="email_required",s}let m=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!m&&!S){let w=await e.evaluate(()=>{let $=document.querySelector("#interop-outlet")?.shadowRoot;if(!$)return{addNote:!1,sendWithout:!1};let b=$.querySelector('button[aria-label="Add a note"]'),C=$.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!C}});if(w.addNote){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=$?.asElement?.()||null,m||await $.dispose().catch(()=>{})}if(w.sendWithout){let $=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=$?.asElement?.()||null,S||await $.dispose().catch(()=>{})}}if(r){if(m&&o){if(console.log(" Adding personalized note..."),await m.click(),await y(1500),await e.$("div.modal-upsell")){let b=await Bn(e);return s.success=b,s.connectionSent=b,s.reason=b?"sent_without_note_upsell":"upsell_failed",s.withCustomMessage=!1,s}let $=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if($){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=o.replace("{name}",b);await $.type(C,{delay:20}),await y(500);let I=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(I){try{await I.evaluate(T=>T.click())}catch{console.log(" Click timeout, likely still sent")}return await y(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(S){console.log(" Sending without note...");try{await S.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await y(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(m&&!o){console.log(" No message provided, sending without note...");let w=await e.$('button[aria-label="Send without a note"]');if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(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 w=S;if(w){try{await w.evaluate($=>$.click())}catch{console.log(" Click timeout, likely still sent")}return await y(3e3),console.log(" \u2713 Connection sent (without note)"),s.success=!0,s.connectionSent=!0,s.reason="sent_without_note",s.withCustomMessage=!1,s}}if(p.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 y(4e3)),await le(e),await y(500);let $=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let C of $){let I=await e.evaluate(T=>{let D=T.getBoundingClientRect();return{visible:D.width>0&&D.height>0,inSticky:!!T.closest('.sticky-header, [class*="sticky"]')}},C);if(I.visible&&!I.inSticky){b=C;break}}!b&&$.length>0&&(b=$[$.length-1]);for(let C of $)C!==b&&await C.dispose().catch(()=>{});if(b)try{await e.evaluate(I=>I.scrollIntoView({behavior:"smooth",block:"center"}),b),await y(500),await b.click().catch(()=>e.evaluate(I=>I.click(),b)),await y(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(B=>B.click(),C),await y(3e3);let I=e.url();if(I.includes("/premium/")||I.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await y(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 D=await e.$('button[aria-label="Send without a note"]');if(D){console.log(" Modal appeared via More dropdown, sending without note...");try{await D.evaluate(B=>B.click())}catch{}return await y(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(u){console.error(` \u2717 Error: ${u.message}`),s.reason="error",s.error=u.message;let a=u.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return s.fatal=!0,s;try{await e.goto("about:blank",{timeout:1e4}),await y(1e3)}catch{s.fatal=!0}return s}}async function Ot(e,t,n={}){let{message:o=null,useCustomMessage:r=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:c=3e3,onProfileProcessed:s=null,excludeLocations:u=[],source:a="unknown"}=n,d={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
247
247
  === Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${r?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!l){let f=He();console.log(`Quota: today ${f.daily.sent}/${f.daily.max} | week ${f.weekly.sent}/${f.weekly.max}`)}console.log("");let p=0;for(let f=0;f<t.length;f++){let h=t[f];try{if(e.isClosed()){console.log(`
248
248
  \u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
249
249
  \u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${f+1}/${t.length}] Skipping - no URL`);continue}let m=Ct(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,s&&await s(h,d,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${f+1}/${t.length}] ${h.name||h.profileUrl}`);let S=null;if(l){let w=await Pn(e,h.profileUrl);w?(De(h.profileUrl,{...w,source:a}),d.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(d.errors++,S={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=Ve();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(S=await Un(e,h.profileUrl,{message:o,useCustomMessage:r,excludeLocations:u,source:a,skipQuotaGate:!0}),S.success)d.connectionsSent++;else switch(S.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(S?.fatal){console.log(`
250
250
  \u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(S?.reason==="error"){if(p++,p>=3){console.log(`
251
251
  \u26A0 ${p} consecutive errors \u2014 aborting funnel`);break}}else p=0;if(S&&S.reason&&(xt(h.profileUrl,S.reason,{method:S.method,messageSent:S.messageSent,profileInfo:S.profileInfo}),$t(h.profileUrl,{source:a||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:S.reason})),s&&await s(h,d,S),f<t.length-1){let w=c+Math.random()*2e3;await y(w)}}if(console.log(`
252
- === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let f=He();console.log(` Connection quota left: today ${f.daily.remaining} of ${f.daily.max} | week ${f.weekly.remaining} of ${f.weekly.max}`)}return d}import"dotenv/config";import*as P from"fs";import*as Z from"path";import{fileURLToPath as Vn}from"url";var Hn=Vn(import.meta.url),Wn=Z.dirname(Z.dirname(Hn)),Ce=process.env.DATA_DIR?Z.resolve(process.env.DATA_DIR,"collected-profiles"):Z.join(Wn,"collected-profiles");function Ye(){P.existsSync(Ce)||P.mkdirSync(Ce,{recursive:!0})}function Yn(){return new Date().toISOString().split("T")[0]}function jt(e,t=null){let n=t||Yn();return Z.join(Ce,`${e}-${n}.json`)}function Nt(e,t=null){Ye();let n=jt(e,t);try{if(P.existsSync(n)){let o=P.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function Ft(e,t=null){return Nt(e,t).filter(o=>!o.processed)}function Mt(e,t,n,o=null){Ye();let r=jt(e,o);try{if(!P.existsSync(r))return;let i=JSON.parse(P.readFileSync(r,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(l.name=c.name),c.title&&(l.title=c.title),c.location&&(l.location=c.location),c.company&&(l.company=c.company),c.connectionDegree&&(l.connectionDegree=c.connectionDegree),c.connectionsCount&&(l.connectionsCount=c.connectionsCount),c.mutualConnections&&(l.mutualConnections=c.mutualConnections),c.photoUrl&&(l.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=c.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),P.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Lt(e){let t=Nt(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function Pt(){Ye();try{return P.readdirSync(Ce).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(P.readFileSync(Z.join(Ce,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as g from"fs";import*as tt from"os";import*as A from"path";import{fileURLToPath as Eo}from"url";var ze={};ge(ze,{NAME:()=>Kn,VERSION:()=>Gn,up:()=>Xn});import*as V from"fs";import*as Re from"path";var Gn=1,Kn="normalize-jobs-and-questions",zn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Qn=50;function Ge(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function Ke(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(r){try{V.unlinkSync(o)}catch{}throw r}try{V.renameSync(o,e)}catch(r){try{V.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let 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 Xn(e,t){let n=Re.join(e,"jobs.json"),o=Re.join(t,"scouted-jobs.json"),r=Re.join(e,"application-questions.json"),i=Ge(n)||{},l=Ge(o)||{},c=0,s=[];for(let a of Object.keys(i)){if(!l[a])continue;let d=l[a],p=i[a];for(let f of zn)d[f]!=null&&p[f]==null&&(p[f]=d[f]);s.push(a),c++}c>0?(Ke(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ge(r);if(u&&Array.isArray(u.applications)){let a={},d=0;for(let p of u.applications){let f=p.jobId||"unknown";a[f]||(a[f]={applications:[]});let h=(p.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Qn?S.options=m.options:(S.optionsOmitted=!0,d++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});a[f].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||h.length,questions:h})}Ke(r,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(s.length>0){for(let a of s)delete l[a];Ke(o,l),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Qe={};ge(Qe,{NAME:()=>eo,VERSION:()=>Zn,up:()=>oo});import*as H from"fs";import*as qt from"path";var Zn=2,eo="reset-unread-flags";function to(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function no(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let 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 oo(e){let t=qt.join(e,"conversations.json"),n=to(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}no(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Xe={};ge(Xe,{NAME:()=>so,VERSION:()=>ro,up:()=>uo});import*as W from"fs";import*as Bt from"path";var ro=3,so="recompute-last-message-by",io=new Set(["draft","confirmed","rejected","needs_review"]);function lo(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function ao(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let 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 co(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!io.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,l)=>l.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function uo(e){let t=Bt.join(e,"conversations.json"),n=lo(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,l=0;for(let c of Object.keys(n)){let s=n[c];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let u=Array.isArray(s.messages)?s.messages:[],a=co(u,o),d=a==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==a&&l++,s.lastMessageBy=a,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}ao(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ze={};ge(Ze,{NAME:()=>po,VERSION:()=>fo,up:()=>yo});import*as Y from"fs";import*as Ut from"path";var fo=4,po="split-connection-timestamps",mo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ho(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function go(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 yo(e){let t=Ut.join(e,"people.json"),n=ho(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let l=n[i];!l||typeof l!="object"||(r++,mo.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}go(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as U from"path";import{fileURLToPath as wo}from"url";var So=wo(import.meta.url),bo=U.dirname(U.dirname(So)),xe=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(bo,"market-research"),Dr=U.join(xe,"scouted-jobs.json"),_r=U.join(xe,"discovered-people.json"),Rr=U.join(xe,"visit-log.json"),Tr=U.join(xe,"companies.json"),Or=U.join(xe,"job-decisions.json");function Jt(){ko=null,vo=null,$o=null,Co=null,xo=null}var ko=null;var vo=null;var $o=null;var Co=null;var xo=null;var Ao=Eo(import.meta.url),Io=A.dirname(Ao),Do=A.dirname(A.dirname(Io));function _o(e){return e&&(e==="~"?tt.homedir():e.startsWith("~/")||e.startsWith("~\\")?A.join(tt.homedir(),e.slice(2)):e)}var K=process.env.DATA_DIR?A.resolve(_o(process.env.DATA_DIR)):Do,ue=A.join(K,"collected-profiles"),de=A.join(K,"market-research"),q=A.join(K,".schema-version"),Vt=[A.join(ue,".schema-version"),A.join(de,".schema-version")],se=4,ee=[{version:1,module:ze},{version:2,module:Qe},{version:3,module:Xe},{version:4,module:Ze}];(function(){ee.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ee){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=ee.length?ee[ee.length-1].version:0;if(n!==se)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${se}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ee.length;o++){let r=o+1;if(ee[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ee[o].version}`)}})();function Gt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
252
+ === Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!l){let f=He();console.log(` Connection quota left: today ${f.daily.remaining} of ${f.daily.max} | week ${f.weekly.remaining} of ${f.weekly.max}`)}return d}import"dotenv/config";import*as P from"fs";import*as Z from"path";import{fileURLToPath as Vn}from"url";var Hn=Vn(import.meta.url),Wn=Z.dirname(Z.dirname(Hn)),Ce=process.env.DATA_DIR?Z.resolve(process.env.DATA_DIR,"collected-profiles"):Z.join(Wn,"collected-profiles");function Ye(){P.existsSync(Ce)||P.mkdirSync(Ce,{recursive:!0})}function Yn(){return new Date().toISOString().split("T")[0]}function jt(e,t=null){let n=t||Yn();return Z.join(Ce,`${e}-${n}.json`)}function Nt(e,t=null){Ye();let n=jt(e,t);try{if(P.existsSync(n)){let o=P.readFileSync(n,"utf-8"),r=JSON.parse(o);return console.log(`\u{1F4C2} Loaded ${r.profiles.length} profiles from ${n}`),r.profiles}}catch(o){console.error(`Error loading profiles from ${n}:`,o.message)}return[]}function Ft(e,t=null){return Nt(e,t).filter(o=>!o.processed)}function Mt(e,t,n,o=null){Ye();let r=jt(e,o);try{if(!P.existsSync(r))return;let i=JSON.parse(P.readFileSync(r,"utf-8")),l=i.profiles.find(c=>c.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof n=="string")l.status=n;else if(typeof n=="object"){if(l.status=n.status,n.profileInfo){let c=n.profileInfo;c.name&&(l.name=c.name),c.title&&(l.title=c.title),c.location&&(l.location=c.location),c.company&&(l.company=c.company),c.connectionDegree&&(l.connectionDegree=c.connectionDegree),c.connectionsCount&&(l.connectionsCount=c.connectionsCount),c.mutualConnections&&(l.mutualConnections=c.mutualConnections),c.photoUrl&&(l.photoUrl=c.photoUrl),c.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=c.hasVerifiedBadge)}l.funnelResult={connectionSent:n.connectionSent||!1,withCustomMessage:n.withCustomMessage||!1,message:n.message||null,method:n.method||null,reason:n.reason||null,error:n.error||null}}i.lastUpdated=new Date().toISOString(),P.writeFileSync(r,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function Lt(e){let t=Nt(e),n=t.filter(r=>r.processed),o=t.filter(r=>!r.processed);return{total:t.length,processed:n.length,unprocessed:o.length,statuses:n.reduce((r,i)=>(r[i.status]=(r[i.status]||0)+1,r),{})}}function Pt(){Ye();try{return P.readdirSync(Ce).filter(t=>t.endsWith(".json")).map(t=>{let[n,o]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let r=JSON.parse(P.readFileSync(Z.join(Ce,t),"utf-8"));return{file:t,source:n,date:o,count:r.profiles?.length||0,unprocessed:r.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:n,date:o,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as g from"fs";import*as tt from"os";import*as E from"path";import{fileURLToPath as Ao}from"url";var ze={};ge(ze,{NAME:()=>Kn,VERSION:()=>Gn,up:()=>Xn});import*as V from"fs";import*as Re from"path";var Gn=1,Kn="normalize-jobs-and-questions",zn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Qn=50;function Ge(e){return V.existsSync(e)?JSON.parse(V.readFileSync(e,"utf-8")):null}function Ke(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{V.writeFileSync(o,n)}catch(r){try{V.unlinkSync(o)}catch{}throw r}try{V.renameSync(o,e)}catch(r){try{V.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let 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 Xn(e,t){let n=Re.join(e,"jobs.json"),o=Re.join(t,"scouted-jobs.json"),r=Re.join(e,"application-questions.json"),i=Ge(n)||{},l=Ge(o)||{},c=0,s=[];for(let a of Object.keys(i)){if(!l[a])continue;let d=l[a],p=i[a];for(let f of zn)d[f]!=null&&p[f]==null&&(p[f]=d[f]);s.push(a),c++}c>0?(Ke(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Ge(r);if(u&&Array.isArray(u.applications)){let a={},d=0;for(let p of u.applications){let f=p.jobId||"unknown";a[f]||(a[f]={applications:[]});let h=(p.questions||[]).map(m=>{let S={type:m.type||"input",question:m.question||"",answer:m.answer||""};return m.options&&(m.options.length<=Qn?S.options=m.options:(S.optionsOmitted=!0,d++)),m.page&&(S.page=m.page),m.wasPreFilled&&(S.wasPreFilled=!0),m.wasRetry&&(S.wasRetry=!0),S});a[f].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||h.length,questions:h})}Ke(r,a),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(a).length} unique jobs)`),d>0&&console.log(` Phase 2: Stripped bloated options from ${d} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(s.length>0){for(let a of s)delete l[a];Ke(o,l),console.log(` Phase 3: Removed ${s.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Qe={};ge(Qe,{NAME:()=>eo,VERSION:()=>Zn,up:()=>oo});import*as H from"fs";import*as qt from"path";var Zn=2,eo="reset-unread-flags";function to(e){return H.existsSync(e)?JSON.parse(H.readFileSync(e,"utf-8")):null}function no(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,n)}catch(r){try{H.unlinkSync(o)}catch{}throw r}try{H.renameSync(o,e)}catch(r){try{H.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let 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 oo(e){let t=qt.join(e,"conversations.json"),n=to(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}no(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Xe={};ge(Xe,{NAME:()=>so,VERSION:()=>ro,up:()=>uo});import*as W from"fs";import*as Bt from"path";var ro=3,so="recompute-last-message-by",io=new Set(["draft","confirmed","rejected","needs_review"]);function lo(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function ao(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,n)}catch(r){try{W.unlinkSync(o)}catch{}throw r}try{W.renameSync(o,e)}catch(r){try{W.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let 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 co(e,t){if(!e||e.length===0)return"them";let n=e.filter(i=>!io.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,l)=>l.t-i.t).map(i=>i.m),r=o.length>0?o:[...n].reverse();for(let i of r){let l=i.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function uo(e){let t=Bt.join(e,"conversations.json"),n=lo(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,l=0;for(let c of Object.keys(n)){let s=n[c];if(!s||typeof s!="object")continue;Object.prototype.hasOwnProperty.call(s,"_cardSynced")&&(delete s._cardSynced,i++);let u=Array.isArray(s.messages)?s.messages:[],a=co(u,o),d=a==="me"?"awaiting_reply":"unanswered_by_us";s.lastMessageBy!==a&&l++,s.lastMessageBy=a,s.conversationStatus=d,r++}if(r===0){console.log(" No conversations to recompute.");return}ao(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ze={};ge(Ze,{NAME:()=>po,VERSION:()=>fo,up:()=>yo});import*as Y from"fs";import*as Ut from"path";var fo=4,po="split-connection-timestamps",mo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ho(e){if(!Y.existsSync(e))return null;let t=Y.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function go(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 yo(e){let t=Ut.join(e,"people.json"),n=ho(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let i of Object.keys(n)){let l=n[i];!l||typeof l!="object"||(r++,mo.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}go(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as U from"path";import{fileURLToPath as wo}from"url";var So=wo(import.meta.url),bo=U.dirname(U.dirname(So)),xe=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(bo,"market-research"),Dr=U.join(xe,"scouted-jobs.json"),_r=U.join(xe,"discovered-people.json"),Rr=U.join(xe,"visit-log.json"),Tr=U.join(xe,"companies.json"),Or=U.join(xe,"job-decisions.json");function Jt(){ko=null,vo=null,$o=null,Co=null,xo=null}var ko=null;var vo=null;var $o=null;var Co=null;var xo=null;var Eo=Ao(import.meta.url),Io=E.dirname(Eo),Do=E.dirname(E.dirname(Io));function _o(e){return e&&(e==="~"?tt.homedir():e.startsWith("~/")||e.startsWith("~\\")?E.join(tt.homedir(),e.slice(2)):e)}var K=process.env.DATA_DIR?E.resolve(_o(process.env.DATA_DIR)):Do,ue=E.join(K,"collected-profiles"),de=E.join(K,"market-research"),q=E.join(K,".schema-version"),Vt=[E.join(ue,".schema-version"),E.join(de,".schema-version")],se=4,ee=[{version:1,module:ze},{version:2,module:Qe},{version:3,module:Xe},{version:4,module:Ze}];(function(){ee.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of ee){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=ee.length?ee[ee.length-1].version:0;if(n!==se)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${se}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<ee.length;o++){let r=o+1;if(ee[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${ee[o].version}`)}})();function Gt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
253
253
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
254
254
  `),process.exit(1));try{g.mkdirSync(K,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
255
255
  [FATAL] Cannot create DATA_DIR (${K}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -259,7 +259,7 @@ ${o.join(`
259
259
  [FATAL] DATA_DIR (${K}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
260
260
  `),process.exit(1));for(let t of[ue,de]){let n;try{n=g.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
261
261
  [FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
262
- `),process.exit(1))}}var ce=A.join(K,".migration-lock");function Ro(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return g.writeFileSync(ce,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(g.readFileSync(ce,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}o&&i<r&&(console.error(`
262
+ `),process.exit(1))}}var ce=E.join(K,".migration-lock");function Ro(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return g.writeFileSync(ce,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(g.readFileSync(ce,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,i=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(i=Date.now()-l)}o&&i<r&&(console.error(`
263
263
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${ce}
264
264
  `),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
265
265
  `),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=ce+".tmp";try{return g.writeFileSync(n,e),g.renameSync(n,ce),!0}catch(o){try{g.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function nt(){try{if(JSON.parse(g.readFileSync(ce,"utf-8")).pid!==process.pid)return;g.unlinkSync(ce)}catch{}}var Ht=!1;function To(){if(Ht)return;Ht=!0;let e=()=>{try{nt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Oo(){if(g.existsSync(q))return;let e=[],t=[];for(let i of Vt)if(g.existsSync(i))try{e.push({file:i,schema:Te(i)})}catch(l){t.push({file:i,err:l.message})}if(t.length>0){console.error(`
@@ -271,7 +271,7 @@ ${o.join(`
271
271
  [FATAL] ${q} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
272
272
  `),process.exit(1)}let t=jo(e);return t===null&&(console.error(`
273
273
  [FATAL] ${q} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
274
- `),process.exit(1)),t}function Kt(e){try{g.chmodSync(e,384)}catch{}}function No(e){if(Gt(),g.existsSync(q))try{if(g.lstatSync(q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${q}. 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=q+".tmp";try{g.writeFileSync(t,JSON.stringify(e,null,2)),Kt(t),g.renameSync(t,q)}catch(n){try{g.unlinkSync(t)}catch{}throw n}}function Yt(e,t){if(!g.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=g.readdirSync(e).filter(c=>{let s=c.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return g.statSync(A.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let c of o){let s=A.join(e,c),u=A.join(e,c+n);if(g.existsSync(u)){i++;continue}try{Qt(s,u),r++}catch(a){l.push({file:c,err:a.message})}}if(l.length>0){let c=new Error(`Failed to back up ${l.length} file(s) in ${A.basename(e)}/: `+l.map(s=>`${s.file} (${s.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${A.basename(e)}/ (${n})${c}`)}}var et=!1;async function zt(){if(et)return;Gt(),qo();let t=Wt().version;if(t===se){et=!0;return}To(),Ro(),process.on("exit",nt),t>se&&(console.error(`
274
+ `),process.exit(1)),t}function Kt(e){try{g.chmodSync(e,384)}catch{}}function No(e){if(Gt(),g.existsSync(q))try{if(g.lstatSync(q).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${q}. 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=q+".tmp";try{g.writeFileSync(t,JSON.stringify(e,null,2)),Kt(t),g.renameSync(t,q)}catch(n){try{g.unlinkSync(t)}catch{}throw n}}function Yt(e,t){if(!g.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=g.readdirSync(e).filter(c=>{let s=c.toLowerCase();if(s.includes(".backup")||s===".schema-version"||s.endsWith(".tmp"))return!1;try{return g.statSync(E.join(e,c)).isFile()}catch{return!1}}),r=0,i=0,l=[];for(let c of o){let s=E.join(e,c),u=E.join(e,c+n);if(g.existsSync(u)){i++;continue}try{Qt(s,u),r++}catch(a){l.push({file:c,err:a.message})}}if(l.length>0){let c=new Error(`Failed to back up ${l.length} file(s) in ${E.basename(e)}/: `+l.map(s=>`${s.file} (${s.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(r>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${E.basename(e)}/ (${n})${c}`)}}var et=!1;async function zt(){if(et)return;Gt(),qo();let t=Wt().version;if(t===se){et=!0;return}To(),Ro(),process.on("exit",nt),t>se&&(console.error(`
275
275
  [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${se}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
276
276
  `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${se}.
277
277
  `),process.exit(1)),console.log(`
@@ -289,7 +289,7 @@ ${o.join(`
289
289
  [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.
290
290
  `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{kt()}catch{}try{Jt()}catch{}et=!0,nt(),console.log(`
291
291
  \u2713 Schema is now at v${se}
292
- `)}var Fo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Mo(e){let t=e.toLowerCase();return Fo.some(n=>n.test(t))}var Lo=6e4;function Po(){let e=Date.now(),t=[];for(let n of[K,ue,de]){if(!g.existsSync(n))continue;let o;try{o=g.readdirSync(n)}catch{continue}for(let r of o){if(!Mo(r))continue;let i=A.join(n,r);try{let l=g.statSync(i);if(!l.isFile()||e-l.mtimeMs<Lo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function qo({verbose:e=!1}={}){let t=Po();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{g.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${A.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 Bo(){let e=[];for(let t of[ue,de]){if(!g.existsSync(t))continue;let n=g.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=A.join(t,o);try{Te(r)}catch(i){e.push({dir:A.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Uo(e){let t=[],n=[];for(let i of[ue,de]){if(!g.existsSync(i))continue;let l=g.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let s=A.join(i,c),u=c.slice(0,-e.length),a=A.join(i,u);try{u.toLowerCase().endsWith(".json")?Te(s):g.accessSync(s,g.constants.R_OK),t.push({backupPath:s,originalPath:a,fileName:c,dir:i})}catch(d){n.push(`${A.basename(i)}/${c}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:l,fileName:c,dir:s}of t)try{Qt(i,l),o++}catch(u){r.push(`${A.basename(s)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Qt(e,t){let n=t+".tmp";try{g.copyFileSync(e,n),Kt(n)}catch(o){try{g.unlinkSync(n)}catch{}throw o}try{g.renameSync(n,t)}catch(o){try{g.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}import Xt from"fs";import Jo from"path";var Vo="cookies.json";function Ho(){let e=process.env.ILML_SCOPE_DIR;return e?Jo.join(e,"plugins-state","linkedin","cookies.json"):Vo}function Zt(){let e=Ho();if(!Xt.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Xt.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}await zt();function Yo(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function Go(){let e=Yo();if(e.list){console.log(`
292
+ `)}var Fo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Mo(e){let t=e.toLowerCase();return Fo.some(n=>n.test(t))}var Lo=6e4;function Po(){let e=Date.now(),t=[];for(let n of[K,ue,de]){if(!g.existsSync(n))continue;let o;try{o=g.readdirSync(n)}catch{continue}for(let r of o){if(!Mo(r))continue;let i=E.join(n,r);try{let l=g.statSync(i);if(!l.isFile()||e-l.mtimeMs<Lo)continue;t.push({dir:n,file:r,fullPath:i})}catch{}}}return t}function qo({verbose:e=!1}={}){let t=Po();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{g.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${E.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Bo(){let e=[];for(let t of[ue,de]){if(!g.existsSync(t))continue;let n=g.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=E.join(t,o);try{Te(r)}catch(i){e.push({dir:E.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Uo(e){let t=[],n=[];for(let i of[ue,de]){if(!g.existsSync(i))continue;let l=g.readdirSync(i).filter(c=>c.endsWith(e));for(let c of l){let s=E.join(i,c),u=c.slice(0,-e.length),a=E.join(i,u);try{u.toLowerCase().endsWith(".json")?Te(s):g.accessSync(s,g.constants.R_OK),t.push({backupPath:s,originalPath:a,fileName:c,dir:i})}catch(d){n.push(`${E.basename(i)}/${c}: ${d.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:i,originalPath:l,fileName:c,dir:s}of t)try{Qt(i,l),o++}catch(u){r.push(`${E.basename(s)}/${c}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Qt(e,t){let n=t+".tmp";try{g.copyFileSync(e,n),Kt(n)}catch(o){try{g.unlinkSync(n)}catch{}throw o}try{g.renameSync(n,t)}catch(o){try{g.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}import Xt from"fs";import Jo from"path";var Vo="cookies.json";function Ho(){let e=process.env.ILML_SCOPE_DIR;return e?Jo.join(e,"plugins-state","linkedin","cookies.json"):Vo}function Zt(){let e=Ho();if(!Xt.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Xt.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}await zt();function Yo(){let e={source:"recruiters-from-jobs",date:null,viewOnly:!1,max:20,list:!1,useCustomMessage:!0,message:"Hi {name}, I just applied for a position at your company and would love to connect!",excludeLocations:[]};process.env.FUNNEL_EXCLUDE_LOCATIONS&&(e.excludeLocations=process.env.FUNNEL_EXCLUDE_LOCATIONS.split(",").map(t=>t.trim()).filter(Boolean));for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--view-only"?e.viewOnly=!0:t==="--no-note"?e.useCustomMessage=!1:t==="--with-note"?e.useCustomMessage=!0:t.startsWith("--source=")?e.source=t.split("=")[1]:t.startsWith("--date=")?e.date=t.split("=")[1]:t.startsWith("--max=")?e.max=parseInt(t.split("=")[1],10):t.startsWith("--message=")?e.message=t.split("=")[1]:t.startsWith("--exclude-locations=")&&(e.excludeLocations=t.split("=")[1].split(",").map(n=>n.trim()).filter(Boolean));return e}async function Go(){let e=Yo();if(e.list){console.log(`
293
293
  \u{1F4C2} Available profile files:
294
294
  `);let s=Pt();if(s.length===0)console.log(" No files found in collected-profiles/ (DATA_DIR)");else for(let u of s)console.log(` ${u.file}`),console.log(` Total: ${u.count}, Unprocessed: ${u.unprocessed}`);console.log(""),process.exit(0)}console.log(`
295
295
  ========================================`),console.log("Profile Funnel Runner"),console.log(`========================================
@@ -1,4 +1,4 @@
1
- var ke=Object.defineProperty;var P=(e,o)=>{for(var n in o)ke(e,n,{get:o[n],enumerable:!0})};import"dotenv/config";import"dotenv/config";import*as i from"fs";import*as z from"os";import*as l from"path";import{fileURLToPath as uo}from"url";var q={};P(q,{NAME:()=>Ae,VERSION:()=>we,up:()=>Ee});import*as A from"fs";import*as J from"path";var we=1,Ae="normalize-jobs-and-questions",$e=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],je=50;function V(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function W(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{A.writeFileSync(t,n)}catch(s){try{A.unlinkSync(t)}catch{}throw s}try{A.renameSync(t,e)}catch(s){try{A.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Ee(e,o){let n=J.join(e,"jobs.json"),t=J.join(o,"scouted-jobs.json"),s=J.join(e,"application-questions.json"),r=V(n)||{},c=V(t)||{},O=0,u=[];for(let f of Object.keys(r)){if(!c[f])continue;let b=c[f],d=r[f];for(let I of $e)b[I]!=null&&d[I]==null&&(d[I]=b[I]);u.push(f),O++}O>0?(W(n,r),console.log(` Phase 1: Merged ${O} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let p=V(s);if(p&&Array.isArray(p.applications)){let f={},b=0;for(let d of p.applications){let I=d.jobId||"unknown";f[I]||(f[I]={applications:[]});let T=(d.questions||[]).map(g=>{let v={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=je?v.options=g.options:(v.optionsOmitted=!0,b++)),g.page&&(v.page=g.page),g.wasPreFilled&&(v.wasPreFilled=!0),g.wasRetry&&(v.wasRetry=!0),v});f[I].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||T.length,questions:T})}W(s,f),console.log(` Phase 2: Rekeyed ${p.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),b>0&&console.log(` Phase 2: Stripped bloated options from ${b} questions`)}else p&&!p.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(u.length>0){for(let f of u)delete c[f];W(t,c),console.log(` Phase 3: Removed ${u.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Y={};P(Y,{NAME:()=>Ie,VERSION:()=>Oe,up:()=>De});import*as $ from"fs";import*as X from"path";var Oe=2,Ie="reset-unread-flags";function Re(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Ne(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{$.writeFileSync(t,n)}catch(s){try{$.unlinkSync(t)}catch{}throw s}try{$.renameSync(t,e)}catch(s){try{$.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function De(e){let o=X.join(e,"conversations.json"),n=Re(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Ne(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var G={};P(G,{NAME:()=>Ce,VERSION:()=>Te,up:()=>Me});import*as j from"fs";import*as Z from"path";var Te=3,Ce="recompute-last-message-by",_e=new Set(["draft","confirmed","rejected","needs_review"]);function xe(e){return j.existsSync(e)?JSON.parse(j.readFileSync(e,"utf-8")):null}function Fe(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{j.writeFileSync(t,n)}catch(s){try{j.unlinkSync(t)}catch{}throw s}try{j.renameSync(t,e)}catch(s){try{j.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Le(e,o){if(!e||e.length===0)return"them";let n=e.filter(r=>!_e.has(r.status));if(n.length===0)return"them";let t=n.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,c)=>c.t-r.t).map(r=>r.m),s=t.length>0?t:[...n].reverse();for(let r of s){let c=r.sender;if(c===o)return"me";if(c!=="Unknown"&&c!=="")return"them"}return"them"}async function Me(e){let o=Z.join(e,"conversations.json"),n=xe(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,c=0;for(let O of Object.keys(n)){let u=n[O];if(!u||typeof u!="object")continue;Object.prototype.hasOwnProperty.call(u,"_cardSynced")&&(delete u._cardSynced,r++);let p=Array.isArray(u.messages)?u.messages:[],f=Le(p,t),b=f==="me"?"awaiting_reply":"unanswered_by_us";u.lastMessageBy!==f&&c++,u.lastMessageBy=f,u.conversationStatus=b,s++}if(s===0){console.log(" No conversations to recompute.");return}Fe(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${c} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var H={};P(H,{NAME:()=>Je,VERSION:()=>Pe,up:()=>We});import*as E from"fs";import*as ee from"path";var Pe=4,Je="split-connection-timestamps",Ue=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Be(e){if(!E.existsSync(e))return null;let o=E.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Ve(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{E.writeFileSync(t,n)}catch(s){try{E.unlinkSync(t)}catch{}throw s}try{E.renameSync(t,e)}catch(s){try{E.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function We(e){let o=ee.join(e,"people.json"),n=Be(o);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,s=0;for(let r of Object.keys(n)){let c=n[r];!c||typeof c!="object"||(s++,Ue.has(c.connectionStatus)&&c.connectionDate&&!c.requestedConnectionAt&&(c.requestedConnectionAt=c.connectionDate,c.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ve(o,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import{getPluginConfig as qe}from"@ilivemylife/graph-sdk";var Ye=await qe();for(let[e,o]of Object.entries(Ye))process.env[e]===void 0&&(process.env[e]=o);var Io=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ro=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),No=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as y from"path";import{fileURLToPath as Ge}from"url";var He=Ge(import.meta.url),ze=y.dirname(y.dirname(He)),_=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(ze,"collected-profiles"),xo=y.join(_,"people.json"),Fo=y.join(_,"jobs.json"),Lo=y.join(_,"quota.json"),Mo=y.join(_,"conversations.json"),Po=y.join(_,"sync-state.json"),Jo=y.join(_,"application-questions.json"),Uo=y.join(_,"profile-history"),oe=(e,o)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:o},Bo=oe(process.env.CONNECT_MAX_DAILY,20),Vo=oe(process.env.CONNECT_MAX_WEEKLY,100),Ke=null,Qe=null,Xe=null,Ze=null,eo=null,oo=null;function ne(){Ke=null,Qe=null,Xe=null,Ze=null,eo=null,oo=null}import"dotenv/config";import*as k from"path";import{fileURLToPath as no}from"url";var to=no(import.meta.url),so=k.dirname(k.dirname(to)),L=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"market-research"):k.join(so,"market-research"),Go=k.join(L,"scouted-jobs.json"),Ho=k.join(L,"discovered-people.json"),zo=k.join(L,"visit-log.json"),Ko=k.join(L,"companies.json"),Qo=k.join(L,"job-decisions.json");function te(){ro=null,io=null,co=null,lo=null,ao=null}var ro=null;var io=null;var co=null;var lo=null;var ao=null;var fo=uo(import.meta.url),po=l.dirname(fo),ho=l.dirname(l.dirname(po));function mo(e){return e&&(e==="~"?z.homedir():e.startsWith("~/")||e.startsWith("~\\")?l.join(z.homedir(),e.slice(2)):e)}var S=process.env.DATA_DIR?l.resolve(mo(process.env.DATA_DIR)):ho,N=l.join(S,"collected-profiles"),D=l.join(S,"market-research"),m=l.join(S,".schema-version"),se=[l.join(N,".schema-version"),l.join(D,".schema-version")],U=4,R=[{version:1,module:q},{version:2,module:Y},{version:3,module:G},{version:4,module:H}];(function(){R.sort((t,s)=>t.version-s.version);let o=new Set;for(let t of R){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let s=t.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=R.length?R[R.length-1].version:0;if(n!==U)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${U}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<R.length;t++){let s=t+1;if(R[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${R[t].version}`)}})();function le(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
1
+ var ke=Object.defineProperty;var P=(e,o)=>{for(var n in o)ke(e,n,{get:o[n],enumerable:!0})};import"dotenv/config";import"dotenv/config";import*as i from"fs";import*as z from"os";import*as l from"path";import{fileURLToPath as uo}from"url";var q={};P(q,{NAME:()=>Ae,VERSION:()=>we,up:()=>Ee});import*as A from"fs";import*as J from"path";var we=1,Ae="normalize-jobs-and-questions",$e=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],je=50;function V(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function W(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{A.writeFileSync(t,n)}catch(s){try{A.unlinkSync(t)}catch{}throw s}try{A.renameSync(t,e)}catch(s){try{A.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Ee(e,o){let n=J.join(e,"jobs.json"),t=J.join(o,"scouted-jobs.json"),s=J.join(e,"application-questions.json"),r=V(n)||{},c=V(t)||{},O=0,u=[];for(let f of Object.keys(r)){if(!c[f])continue;let b=c[f],d=r[f];for(let I of $e)b[I]!=null&&d[I]==null&&(d[I]=b[I]);u.push(f),O++}O>0?(W(n,r),console.log(` Phase 1: Merged ${O} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let p=V(s);if(p&&Array.isArray(p.applications)){let f={},b=0;for(let d of p.applications){let I=d.jobId||"unknown";f[I]||(f[I]={applications:[]});let T=(d.questions||[]).map(g=>{let v={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=je?v.options=g.options:(v.optionsOmitted=!0,b++)),g.page&&(v.page=g.page),g.wasPreFilled&&(v.wasPreFilled=!0),g.wasRetry&&(v.wasRetry=!0),v});f[I].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||T.length,questions:T})}W(s,f),console.log(` Phase 2: Rekeyed ${p.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),b>0&&console.log(` Phase 2: Stripped bloated options from ${b} questions`)}else p&&!p.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(u.length>0){for(let f of u)delete c[f];W(t,c),console.log(` Phase 3: Removed ${u.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Y={};P(Y,{NAME:()=>Ie,VERSION:()=>Oe,up:()=>De});import*as $ from"fs";import*as X from"path";var Oe=2,Ie="reset-unread-flags";function Re(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Ne(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{$.writeFileSync(t,n)}catch(s){try{$.unlinkSync(t)}catch{}throw s}try{$.renameSync(t,e)}catch(s){try{$.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function De(e){let o=X.join(e,"conversations.json"),n=Re(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Ne(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var G={};P(G,{NAME:()=>Ce,VERSION:()=>Te,up:()=>Me});import*as j from"fs";import*as Z from"path";var Te=3,Ce="recompute-last-message-by",xe=new Set(["draft","confirmed","rejected","needs_review"]);function _e(e){return j.existsSync(e)?JSON.parse(j.readFileSync(e,"utf-8")):null}function Fe(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{j.writeFileSync(t,n)}catch(s){try{j.unlinkSync(t)}catch{}throw s}try{j.renameSync(t,e)}catch(s){try{j.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Le(e,o){if(!e||e.length===0)return"them";let n=e.filter(r=>!xe.has(r.status));if(n.length===0)return"them";let t=n.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,c)=>c.t-r.t).map(r=>r.m),s=t.length>0?t:[...n].reverse();for(let r of s){let c=r.sender;if(c===o)return"me";if(c!=="Unknown"&&c!=="")return"them"}return"them"}async function Me(e){let o=Z.join(e,"conversations.json"),n=_e(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,c=0;for(let O of Object.keys(n)){let u=n[O];if(!u||typeof u!="object")continue;Object.prototype.hasOwnProperty.call(u,"_cardSynced")&&(delete u._cardSynced,r++);let p=Array.isArray(u.messages)?u.messages:[],f=Le(p,t),b=f==="me"?"awaiting_reply":"unanswered_by_us";u.lastMessageBy!==f&&c++,u.lastMessageBy=f,u.conversationStatus=b,s++}if(s===0){console.log(" No conversations to recompute.");return}Fe(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${c} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var H={};P(H,{NAME:()=>Je,VERSION:()=>Pe,up:()=>We});import*as E from"fs";import*as ee from"path";var Pe=4,Je="split-connection-timestamps",Ue=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Be(e){if(!E.existsSync(e))return null;let o=E.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Ve(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{E.writeFileSync(t,n)}catch(s){try{E.unlinkSync(t)}catch{}throw s}try{E.renameSync(t,e)}catch(s){try{E.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function We(e){let o=ee.join(e,"people.json"),n=Be(o);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,s=0;for(let r of Object.keys(n)){let c=n[r];!c||typeof c!="object"||(s++,Ue.has(c.connectionStatus)&&c.connectionDate&&!c.requestedConnectionAt&&(c.requestedConnectionAt=c.connectionDate,c.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ve(o,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import{getPluginConfig as qe}from"@ilivemylife/graph-sdk";var Ye=await qe();for(let[e,o]of Object.entries(Ye))process.env[e]===void 0&&(process.env[e]=o);var Io=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ro=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),No=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as y from"path";import{fileURLToPath as Ge}from"url";var He=Ge(import.meta.url),ze=y.dirname(y.dirname(He)),x=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(ze,"collected-profiles"),_o=y.join(x,"people.json"),Fo=y.join(x,"jobs.json"),Lo=y.join(x,"quota.json"),Mo=y.join(x,"conversations.json"),Po=y.join(x,"sync-state.json"),Jo=y.join(x,"application-questions.json"),Uo=y.join(x,"profile-history"),oe=(e,o)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:o},Bo=oe(process.env.CONNECT_MAX_DAILY,20),Vo=oe(process.env.CONNECT_MAX_WEEKLY,100),Ke=null,Qe=null,Xe=null,Ze=null,eo=null,oo=null;function ne(){Ke=null,Qe=null,Xe=null,Ze=null,eo=null,oo=null}import"dotenv/config";import*as k from"path";import{fileURLToPath as no}from"url";var to=no(import.meta.url),so=k.dirname(k.dirname(to)),L=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"market-research"):k.join(so,"market-research"),Go=k.join(L,"scouted-jobs.json"),Ho=k.join(L,"discovered-people.json"),zo=k.join(L,"visit-log.json"),Ko=k.join(L,"companies.json"),Qo=k.join(L,"job-decisions.json");function te(){ro=null,io=null,co=null,lo=null,ao=null}var ro=null;var io=null;var co=null;var lo=null;var ao=null;var fo=uo(import.meta.url),po=l.dirname(fo),ho=l.dirname(l.dirname(po));function mo(e){return e&&(e==="~"?z.homedir():e.startsWith("~/")||e.startsWith("~\\")?l.join(z.homedir(),e.slice(2)):e)}var S=process.env.DATA_DIR?l.resolve(mo(process.env.DATA_DIR)):ho,N=l.join(S,"collected-profiles"),D=l.join(S,"market-research"),m=l.join(S,".schema-version"),se=[l.join(N,".schema-version"),l.join(D,".schema-version")],U=4,R=[{version:1,module:q},{version:2,module:Y},{version:3,module:G},{version:4,module:H}];(function(){R.sort((t,s)=>t.version-s.version);let o=new Set;for(let t of R){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let s=t.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=R.length?R[R.length-1].version:0;if(n!==U)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${U}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<R.length;t++){let s=t+1;if(R[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${R[t].version}`)}})();function le(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
2
2
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
3
3
  `),process.exit(1));try{i.mkdirSync(S,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
4
4
  [FATAL] Cannot create DATA_DIR (${S}): ${o.message}`),console.error(` Fix the path or permissions and try again.
@@ -8,10 +8,10 @@ var ke=Object.defineProperty;var P=(e,o)=>{for(var n in o)ke(e,n,{get:o[n],enume
8
8
  [FATAL] DATA_DIR (${S}) 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.
9
9
  `),process.exit(1));for(let o of[N,D]){let n;try{n=i.lstatSync(o)}catch(t){if(t.code==="ENOENT")continue;throw t}n.isSymbolicLink()&&(console.error(`
10
10
  [FATAL] Data subdirectory is a symbolic link: ${o}`),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.
11
- `),process.exit(1))}}var x=l.join(S,".migration-lock");function ae(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return i.writeFileSync(x,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(i.readFileSync(x,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(c){c.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,r=1/0;if(o.startedAt){let c=Date.parse(o.startedAt);Number.isNaN(c)||(r=Date.now()-c)}t&&r<s&&(console.error(`
12
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${x}
11
+ `),process.exit(1))}}var _=l.join(S,".migration-lock");function ae(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return i.writeFileSync(_,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(i.readFileSync(_,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(c){c.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,r=1/0;if(o.startedAt){let c=Date.parse(o.startedAt);Number.isNaN(c)||(r=Date.now()-c)}t&&r<s&&(console.error(`
12
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${_}
13
13
  `),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.
14
- `),process.exit(1)),t&&r>=s&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let n=x+".tmp";try{return i.writeFileSync(n,e),i.renameSync(n,x),!0}catch(t){try{i.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function M(){try{if(JSON.parse(i.readFileSync(x,"utf-8")).pid!==process.pid)return;i.unlinkSync(x)}catch{}}var re=!1;function ue(){if(re)return;re=!0;let e=()=>{try{M()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function go(){if(i.existsSync(m))return;let e=[],o=[];for(let r of se)if(i.existsSync(r))try{e.push({file:r,schema:B(r)})}catch(c){o.push({file:r,err:c.message})}if(o.length>0){console.error(`
14
+ `),process.exit(1)),t&&r>=s&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let n=_+".tmp";try{return i.writeFileSync(n,e),i.renameSync(n,_),!0}catch(t){try{i.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function M(){try{if(JSON.parse(i.readFileSync(_,"utf-8")).pid!==process.pid)return;i.unlinkSync(_)}catch{}}var re=!1;function ue(){if(re)return;re=!0;let e=()=>{try{M()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function go(){if(i.existsSync(m))return;let e=[],o=[];for(let r of se)if(i.existsSync(r))try{e.push({file:r,schema:B(r)})}catch(c){o.push({file:r,err:c.message})}if(o.length>0){console.error(`
15
15
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of o)console.error(` ${r.file}: ${r.err}`);console.error(`
16
16
  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.
17
17
  `),process.exit(1)}if(e.length===0)return;let n=e.map(r=>r.schema.version);if(new Set(n).size>1){console.error(`
@@ -1,9 +1,9 @@
1
- import"dotenv/config";import*as p from"fs";import*as g from"path";import{getPluginConfig as _}from"@ilivemylife/graph-sdk";var T=await _();for(let[e,o]of Object.entries(T))process.env[e]===void 0&&(process.env[e]=o);var Y=process.env.LINKEDIN_NAME,h=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Q=Object.freeze(new Set([h.DRAFT,h.CONFIRMED,h.NEEDS_REVIEW])),B=Object.freeze(new Set([h.DRAFT,h.CONFIRMED,h.REJECTED,h.NEEDS_REVIEW]));import"dotenv/config";import*as r from"fs";import*as i from"path";import{fileURLToPath as x}from"url";var R=x(import.meta.url),k=i.dirname(i.dirname(R)),u=process.env.DATA_DIR?i.resolve(process.env.DATA_DIR,"collected-profiles"):i.join(k,"collected-profiles"),v=i.join(u,"people.json"),Z=i.join(u,"jobs.json"),ee=i.join(u,"quota.json"),ne=i.join(u,"conversations.json"),oe=i.join(u,"sync-state.json"),te=i.join(u,"application-questions.json"),N=i.join(u,"profile-history"),E=(e,o)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:o},se=E(process.env.CONNECT_MAX_DAILY,20),le=E(process.env.CONNECT_MAX_WEEKLY,100),j=null;function L(){r.existsSync(u)||r.mkdirSync(u,{recursive:!0})}function $(e,o){if(!r.existsSync(e))return null;try{let t=JSON.parse(r.readFileSync(e,"utf-8"));try{r.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${i.resolve(e)}`);let s=e+".backup";if(r.existsSync(s))try{let n=JSON.parse(r.readFileSync(s,"utf-8"));console.error(` Restored from ${s}`);try{r.copyFileSync(s,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{r.copyFileSync(e,e+".corrupted")}catch{}return null}}function m(e){if(!e)return null;let o=e.match(/\/in\/([^/?#]+)/);return o?o[1].toLowerCase():null}function M(e){let o=m(e);return o?i.join(N,`${o}.json`):null}function I(e){let o=M(e);return o?$(o,`profile-history/${m(e)}.json`)||[]:[]}function S(){return j||(L(),j=$(v,"people.json")||{},j)}var C=process.argv.slice(2),J=C.includes("--all"),w=C.find(e=>e.startsWith("--since="))?.split("=")[1]||null,d=C.find(e=>e.startsWith("--field="))?.split("=")[1]||null,O=C.find(e=>!e.startsWith("--"))||null,P=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(process.cwd(),"collected-profiles"),y=g.join(P,"profile-history");function F(){return p.existsSync(y)?p.readdirSync(y).filter(e=>e.endsWith(".json")).map(e=>e.replace(/\.json$/,"")):[]}function V(e){let o=S();for(let t of Object.keys(o))if(m(t)===e)return t;return null}function W(e){let o=e.startsWith("http")?m(e):e.toLowerCase();if(!o){console.log("Could not derive slug");return}let t=V(o),s=S(),n=t?s[t]:null,a=t?I(t):(()=>{let l=g.join(y,`${o}.json`);return p.existsSync(l)?JSON.parse(p.readFileSync(l,"utf-8")):[]})();console.log(`
1
+ import"dotenv/config";import*as p from"fs";import*as g from"path";import{getPluginConfig as _}from"@ilivemylife/graph-sdk";var T=await _();for(let[e,o]of Object.entries(T))process.env[e]===void 0&&(process.env[e]=o);var Y=process.env.LINKEDIN_NAME,h=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Q=Object.freeze(new Set([h.DRAFT,h.CONFIRMED,h.NEEDS_REVIEW])),B=Object.freeze(new Set([h.DRAFT,h.CONFIRMED,h.REJECTED,h.NEEDS_REVIEW]));import"dotenv/config";import*as l from"fs";import*as i from"path";import{fileURLToPath as x}from"url";var R=x(import.meta.url),k=i.dirname(i.dirname(R)),u=process.env.DATA_DIR?i.resolve(process.env.DATA_DIR,"collected-profiles"):i.join(k,"collected-profiles"),v=i.join(u,"people.json"),Z=i.join(u,"jobs.json"),ee=i.join(u,"quota.json"),ne=i.join(u,"conversations.json"),oe=i.join(u,"sync-state.json"),te=i.join(u,"application-questions.json"),N=i.join(u,"profile-history"),E=(e,o)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:o},se=E(process.env.CONNECT_MAX_DAILY,20),re=E(process.env.CONNECT_MAX_WEEKLY,100),j=null;function L(){l.existsSync(u)||l.mkdirSync(u,{recursive:!0})}function $(e,o){if(!l.existsSync(e))return null;try{let t=JSON.parse(l.readFileSync(e,"utf-8"));try{l.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${i.resolve(e)}`);let s=e+".backup";if(l.existsSync(s))try{let n=JSON.parse(l.readFileSync(s,"utf-8"));console.error(` Restored from ${s}`);try{l.copyFileSync(s,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{l.copyFileSync(e,e+".corrupted")}catch{}return null}}function m(e){if(!e)return null;let o=e.match(/\/in\/([^/?#]+)/);return o?o[1].toLowerCase():null}function M(e){let o=m(e);return o?i.join(N,`${o}.json`):null}function I(e){let o=M(e);return o?$(o,`profile-history/${m(e)}.json`)||[]:[]}function S(){return j||(L(),j=$(v,"people.json")||{},j)}var A=process.argv.slice(2),J=A.includes("--all"),w=A.find(e=>e.startsWith("--since="))?.split("=")[1]||null,d=A.find(e=>e.startsWith("--field="))?.split("=")[1]||null,O=A.find(e=>!e.startsWith("--"))||null,P=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(process.cwd(),"collected-profiles"),y=g.join(P,"profile-history");function F(){return p.existsSync(y)?p.readdirSync(y).filter(e=>e.endsWith(".json")).map(e=>e.replace(/\.json$/,"")):[]}function V(e){let o=S();for(let t of Object.keys(o))if(m(t)===e)return t;return null}function W(e){let o=e.startsWith("http")?m(e):e.toLowerCase();if(!o){console.log("Could not derive slug");return}let t=V(o),s=S(),n=t?s[t]:null,a=t?I(t):(()=>{let r=g.join(y,`${o}.json`);return p.existsSync(r)?JSON.parse(p.readFileSync(r,"utf-8")):[]})();console.log(`
2
2
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` ${n?.name||"(unknown)"} \u2014 ${o}`),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
3
3
  `),n&&(console.log("CURRENT:"),console.log(` title: ${n.title||"(null)"}`),console.log(` location: ${n.location||"(null)"}`),console.log(` currentCompany: ${n.currentCompany||"(null)"}`),console.log(` connectionDeg: ${n.connectionDegree||"(null)"}`),console.log(` openToWork: ${n.openToWork}`),console.log(` hiring: ${n.hiring}`),console.log(` lastUpdated: ${n.lastUpdated||"(null)"}`),console.log(` lastSnapshotAt: ${n.lastSnapshotAt||"(null)"}`)),console.log(`
4
4
  HISTORY (${a.length} snapshot${a.length===1?"":"s"}):
5
- `);for(let l of a){if(console.log(` ${l.capturedAt} changed: [${(l.changedFields||[]).join(", ")}]`),l.snapshot)for(let c of l.changedFields||[]){let f=l.snapshot[c],A=n?n[c]:"?",D=b=>Array.isArray(b)?b.join(", "):b??"(null)";console.log(` ${c.padEnd(18)} OLD: ${D(f)}`),console.log(` ${" ".repeat(18)} NEW: ${D(A)}`)}console.log()}}function q(){let e=F();console.log(`
5
+ `);for(let r of a){if(console.log(` ${r.capturedAt} changed: [${(r.changedFields||[]).join(", ")}]`),r.snapshot)for(let c of r.changedFields||[]){let f=r.snapshot[c],C=n?n[c]:"?",D=b=>Array.isArray(b)?b.join(", "):b??"(null)";console.log(` ${c.padEnd(18)} OLD: ${D(f)}`),console.log(` ${" ".repeat(18)} NEW: ${D(C)}`)}console.log()}}function q(){let e=F();console.log(`
6
6
  ${e.length} profiles have history files:
7
- `);let o=S(),t=[];for(let s of e){let n=Object.keys(o).find(f=>m(f)===s),a=n?o[n]:null,l=g.join(y,`${s}.json`),c=JSON.parse(p.readFileSync(l,"utf-8"));t.push({slug:s,name:a?.name||"(unknown)",snapshots:c.length,mostRecentChange:c[0]?.capturedAt||null,mostRecentFields:c[0]?.changedFields?.join(", ")||""})}t.sort((s,n)=>(n.mostRecentChange||"").localeCompare(s.mostRecentChange||""));for(let s of t)console.log(` ${s.mostRecentChange?.slice(0,10)||"----------"} ${s.snapshots}\xD7 ${s.name.padEnd(28)} [${s.mostRecentFields}]`)}function U(){let e=F(),o=new Date(w).getTime(),t=S(),s=[];for(let n of e){let a=g.join(y,`${n}.json`),l=JSON.parse(p.readFileSync(a,"utf-8"));for(let c of l){if(new Date(c.capturedAt).getTime()<o||d&&!(c.changedFields||[]).includes(d))continue;let f=Object.keys(t).find(A=>m(A)===n);s.push({date:c.capturedAt,slug:n,name:(f?t[f]:null)?.name||"(unknown)",fields:(c.changedFields||[]).join(", "),...d?{oldValue:c.snapshot?.[d],newValue:(f?t[f]:null)?.[d]}:{}})}}s.sort((n,a)=>a.date.localeCompare(n.date)),console.log(`
7
+ `);let o=S(),t=[];for(let s of e){let n=Object.keys(o).find(f=>m(f)===s),a=n?o[n]:null,r=g.join(y,`${s}.json`),c=JSON.parse(p.readFileSync(r,"utf-8"));t.push({slug:s,name:a?.name||"(unknown)",snapshots:c.length,mostRecentChange:c[0]?.capturedAt||null,mostRecentFields:c[0]?.changedFields?.join(", ")||""})}t.sort((s,n)=>(n.mostRecentChange||"").localeCompare(s.mostRecentChange||""));for(let s of t)console.log(` ${s.mostRecentChange?.slice(0,10)||"----------"} ${s.snapshots}\xD7 ${s.name.padEnd(28)} [${s.mostRecentFields}]`)}function U(){let e=F(),o=new Date(w).getTime(),t=S(),s=[];for(let n of e){let a=g.join(y,`${n}.json`),r=JSON.parse(p.readFileSync(a,"utf-8"));for(let c of r){if(new Date(c.capturedAt).getTime()<o||d&&!(c.changedFields||[]).includes(d))continue;let f=Object.keys(t).find(C=>m(C)===n);s.push({date:c.capturedAt,slug:n,name:(f?t[f]:null)?.name||"(unknown)",fields:(c.changedFields||[]).join(", "),...d?{oldValue:c.snapshot?.[d],newValue:(f?t[f]:null)?.[d]}:{}})}}s.sort((n,a)=>a.date.localeCompare(n.date)),console.log(`
8
8
  ${s.length} change events since ${w}${d?` (field=${d})`:""}:
9
- `);for(let n of s)if(console.log(` ${n.date.slice(0,10)} ${n.name.padEnd(28)} [${n.fields}]`),d){let a=l=>Array.isArray(l)?l.join(", "):l??"(null)";console.log(` OLD: ${a(n.oldValue)}`),console.log(` NEW: ${a(n.newValue)}`)}}O?W(O):J?q():w?U():(console.log("Usage:"),console.log(" node profileHistory.mjs <slug-or-url>"),console.log(" node profileHistory.mjs --all"),console.log(" node profileHistory.mjs --since=YYYY-MM-DD [--field=NAME]"));
9
+ `);for(let n of s)if(console.log(` ${n.date.slice(0,10)} ${n.name.padEnd(28)} [${n.fields}]`),d){let a=r=>Array.isArray(r)?r.join(", "):r??"(null)";console.log(` OLD: ${a(n.oldValue)}`),console.log(` NEW: ${a(n.newValue)}`)}}O?W(O):J?q():w?U():(console.log("Usage:"),console.log(" node profileHistory.mjs <slug-or-url>"),console.log(" node profileHistory.mjs --all"),console.log(" node profileHistory.mjs --since=YYYY-MM-DD [--field=NAME]"));