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.
- package/CHANGELOG.md +4 -0
- package/dist/connect.mjs +46 -46
- package/dist/daily.mjs +13 -13
- package/dist/enrichProfile.mjs +3 -3
- package/dist/funnelRunner.mjs +6 -6
- package/dist/migrationCli.mjs +4 -4
- package/dist/profileHistory.mjs +4 -4
- package/dist/run.mjs +51 -51
- package/dist/syncAll.mjs +2 -2
- package/dist/syncConnections.mjs +71 -0
- package/dist/verifyAbout.mjs +12 -12
- package/dist/version.mjs +1 -1
- package/dist/visit.mjs +4 -4
- package/dist/warmScan.mjs +3 -3
- package/ilml-plugin.json +15 -1
- package/package.json +1 -1
package/dist/syncAll.mjs
CHANGED
|
@@ -235,8 +235,8 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});var wo={};Te(wo,{clickConnectButton:()=>Zt,default:()=>Wr,detectConnectionStatus:()=>xe,findConnectButton:()=>it,runFunnel:()=>yo,sendConnectionRequest:()=>en,shouldExcludeLocation:()=>yt,viewProfile:()=>Xt});async function ho(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 $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function yt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Xt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:r=!1,extractSkills:a=!1,extractRecommendations:l=!1,extractCertifications:i=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await ho(e,t));let c=0;for(let g=0;g<2;g++){let h=await e.evaluate(()=>document.body.scrollHeight);for(let C=1;C<=6;C++)await e.evaluate(x=>window.scrollTo(0,x),h*C/6),await $(900);let k=await e.evaluate(()=>document.body.scrollHeight);if(k===c)break;c=k}await $(800);let f=await e.evaluate(()=>{let g=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"]),h=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"]),k=R=>{let D=(R||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},C={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:[]},x=document.querySelector("main");if(!x)return C;let I=[...Array.from(x.querySelectorAll("h1")),...Array.from(x.querySelectorAll("h2"))],T=Array.from(x.querySelectorAll("h2")),L=I.find(R=>{let D=R.textContent&&R.textContent.trim(),O=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!g.has(O)&&!h.has(O)}),G=L?L.textContent.trim():null,v=L?L.parentElement:null;for(;v&&v!==x&&!Array.from(v.children).filter(D=>D.tagName==="P").some(D=>{let O=D.textContent&&D.textContent.trim();return O&&O.length>5&&!k(O)});)v=v.parentElement;let _=null,A=null,M=null,q=null;if(v&&v!==x){let R=Array.from(v.children).filter(O=>O.tagName==="P").filter(O=>{let fe=O.textContent&&O.textContent.trim();return fe&&fe.length>5&&!k(fe)});if(R[0]&&(_=R[0].textContent.trim()),R[1]){let O=R[1].textContent.trim().split(/\s*[·•]\s*/);A=O[0]||null,O.length>1&&(M=O.slice(1).join(" \xB7 "))}let D=Array.from(v.children).filter(O=>O.tagName==="DIV");for(let O=D.length-1;O>=0;O--){let fe=D[O].textContent&&D[O].textContent.trim();if(fe&&!(G&&fe.startsWith(G))&&(q=fe.split(/[·•]/)[0].trim(),q))break}}let ie=null;if(v){let R=v.querySelectorAll("p, span, div");for(let D of R){let O=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){ie=O;break}}}let ae=!!x.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),F=j&&j.src||null,P=x.textContent||"",H=null,se=P.match(/(\d+\+?)\s+connections\b/i);se&&(H=se[1]+" connections");let lt=null,an=P.match(/(\d+)\s+mutual connection/i),ln=P.match(/and\s+(\d+)\s+other mutual/i),xo=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);an?lt=parseInt(an[1],10):ln?lt=2+parseInt(ln[1],10):xo&&(lt=2);let cn=null,un=null,dn=T.find(R=>R.textContent&&R.textContent.trim()==="About");if(dn){let R=dn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let O=D.match(/Top skills\s*(.+?)$/i);if(O){let bt=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Do=>Do.trim()).filter(Boolean);bt.length>0&&bt.length<10&&(un=bt)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),cn=D||null}}let fn=null,mn=T.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(mn){let R=mn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(fn=parseInt(D[1].replace(/,/g,""),10))}}let Ao=[...new Set(T.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==G).filter(R=>g.has(R)))],Ue=document.body.textContent||"",To=/#OpenToWork\b/i.test(Ue)||/\bOpen to work\b/.test(Ue),Ro=/#Hiring\b/i.test(Ue)||/\bI'?m hiring\b/i.test(Ue)||/\bWe are hiring\b/i.test(Ue);return{name:G,title:_,location:q,currentCompany:A,currentSchool:M,connectionDegree:ie,hasVerifiedBadge:ae,photoUrl:F,connectionsLevel:H,mutualConnectionsCount:lt,followers:fn,openToWork:To,hiring:Ro,about:cn,topSkills:un,availableSections:Ao}});console.log(`Viewed: ${f.name} - ${f.title}`);let d=null,m=null,y=null,p=null,S=null,w=null;if(o||s||r||a||l||i){let g=await Promise.resolve().then(()=>(go(),po));o&&(d=await g.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),s&&(m=await g.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),r&&(y=await g.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),a&&(p=await g.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),l&&(S=await g.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),i&&(w=await g.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...f,profileUrl:t,...d!==null&&{experience:d},...m!==null&&{featured:m},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...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 $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function xe(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),s=u=>Array.from(document.querySelectorAll(u)).filter(o),r=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,i={pendingCount:r.length,pendingLabels:r.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return r.length>0?{status:"pending",debug:i}:a&&!l?{status:"connected",debug:i}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:i}:{status:"not_connected",debug:i}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function it(e){let t=null,n=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=c.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of f){let p=y.getBoundingClientRect();if(p.width===0||p.height===0||y.closest(m))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(d))return y}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 i=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(p=>{let S=p.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&d.test(S)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let y of d){let p=y.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return y}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",r=null;for(let i of o){let u=await e.evaluate((c,f)=>{let d=c.className.includes("muted"),m=c.className.includes("sticky-header")||c.className.includes("sticky"),y=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(c.getAttribute("aria-label")||"").toLowerCase(),S=p.includes("invite"),w=f?p.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:y,hasInvite:S,matchesName:w,ariaLabel:p}},i,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}r=i;break}}for(let i of o)i!==r&&await i.dispose().catch(()=>{});if(r)return console.log(" Found: secondary button"),{button:r,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let a=null,l=await e.$$('button[id*="profile-overflow-action"]');for(let i of l){let u=await e.evaluate(c=>{let f=c.getBoundingClientRect(),d=f.width>0&&f.height>0,m=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},i);if(u.isVisible&&!u.isInStickyHeader){a=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of l)i!==a&&await i.dispose().catch(()=>{});if(!a&&l.length>0&&(a=l[l.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let i=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),y=d.getAttribute("aria-label")||"",p=d.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!c)return null;let f=c.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==c)return m;f=f.parentElement}return null});a=i?.asElement?.()||null,a||await i?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await $(500),await e.evaluate(c=>c.click(),a),await $(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 c=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let m=d.querySelector('a[href*="custom-invite"]');if(m)return m;for(let y of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(y.innerText?.trim()==="Connect")return y}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let y of m.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&d.push(p)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping generic button: wrong person (${i})`),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 Zt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await $(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),r=n.tag==="DIV",a=(n.ariaLabel||"").toLowerCase();if(a.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!a.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await $(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await $(2e3),"premium_redirect"}else r?(await e.evaluate(c=>c.click(),t),await $(3e3)):(await e.evaluate(c=>c.click(),t),await $(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let i=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(i?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Jr(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 $(1500);let n=await it(e);if(n){await e.evaluate(s=>s.click(),n),await $(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function en(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:r=!1}=n;if(!s){let l=_t();if(!l.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${l.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:l.reason,profileInfo:null}}let a=await Vr(e,t,n);return a.connectionSent&&!r&&Tn(t,o),a}async function Vr(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:r=!0,skipIfConnected:a=!0,excludeLocations:l=[]}=n,i={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(`
|
|
239
|
-
--- Connecting: ${u} ---`),l.length>0){let w=J()[t]?.location;if(yt(w,l))return console.log(` \u26A0 Excluded location (stored): ${w}`),i.reason="excluded_location",i.profileInfo={location:w},i}if(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(5e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await ho(e,t),await $(2e3)),i.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"]),b=j=>{let F=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},g={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},h=document.querySelector("main");if(!h)return g;let k=[...Array.from(h.querySelectorAll("h1")),...Array.from(h.querySelectorAll("h2"))],C=Array.from(h.querySelectorAll("h2")),x=k.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!w.has(F)&&F!=="0 notifications"}),I=x?x.textContent.trim():null,T=x?x.parentElement:null;for(;T&&T!==h&&!Array.from(T.children).filter(P=>P.tagName==="P").some(P=>{let H=P.textContent&&P.textContent.trim();return H&&H.length>5&&!b(H)});)T=T.parentElement;let L=null,G=null,v=null;if(T&&T!==h){let j=Array.from(T.children),F=j.filter(H=>H.tagName==="P").filter(H=>{let se=H.textContent&&H.textContent.trim();return se&&se.length>5&&!b(se)});F[0]&&(L=F[0].textContent.trim()),F[1]&&(G=F[1].textContent.trim());let P=j.filter(H=>H.tagName==="DIV");for(let H=P.length-1;H>=0;H--){let se=P[H].textContent&&P[H].textContent.trim();if(se&&!(I&&se.startsWith(I))&&(v=se.split(/[·•]/)[0].trim(),v))break}}let _=null;if(T){let j=T.querySelectorAll("p, span, div");for(let F of j){let P=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){_=P;break}}}let A=null,M=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(M){let j=M.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(A=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,A&&(A=A.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let q=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ie=q&&q.src||null,ae=!!h.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:I,title:L,location:v,about:A,company:G,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:ie,hasVerifiedBadge:ae}}),l.length>0){let w=i.profileInfo?.location,b=J()[t]?.location,g=w||b;if(yt(g,l))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${g}`),i.reason="excluded_location",i;!w&&b==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await xe(e);if(i.profileInfo?.connectionDegree==="1st"&&f!=="pending"&&(f!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),f="connected"),f==="pending"&&r)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(f==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await ye(e);let d=await it(e);if(!d&&(await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),d=await it(e)),!d))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;i.method=d.method;let m=await Zt(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),i.reason="wrong_target",i;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let w=await xe(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await ye(e),await $(1e3);let b=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(b)try{await e.evaluate(h=>h.scrollIntoView({behavior:"smooth",block:"center"}),b),await $(500),await b.click().catch(()=>e.evaluate(h=>h.click(),b)),await $(2e3);let g=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(g){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),g),await $(3e3);let h=e.url();if(h.includes("/premium/")||h.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),i.reason="premium_required",i;if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await $(500),i.reason="premium_required",i}catch(g){return console.log(" More dropdown failed:",g.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}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 $(500),i.reason="email_required",i}let p=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!p&&!S){let w=await e.evaluate(()=>{let b=document.querySelector("#interop-outlet")?.shadowRoot;if(!b)return{addNote:!1,sendWithout:!1};let g=b.querySelector('button[aria-label="Add a note"]'),h=b.querySelector('button[aria-label="Send without a note"]');return{addNote:!!g,sendWithout:!!h}});if(w.addNote){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=b?.asElement?.()||null,p||await b.dispose().catch(()=>{})}if(w.sendWithout){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=b?.asElement?.()||null,S||await b.dispose().catch(()=>{})}}if(s){if(p&&o){if(console.log(" Adding personalized note..."),await p.click(),await $(1500),await e.$("div.modal-upsell")){let g=await Jr(e);return i.success=g,i.connectionSent=g,i.reason=g?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let b=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(b){let g=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),h=o.replace("{name}",g);await b.type(h,{delay:20}),await $(500);let k=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(k){try{await k.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=h,i}}}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 $(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(p&&!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(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let w=S;if(w){try{await w.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3)),await ye(e),await $(500);let b=await e.$$('button[id*="profile-overflow-action"]'),g=null;for(let h of b){let k=await e.evaluate(C=>{let x=C.getBoundingClientRect();return{visible:x.width>0&&x.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},h);if(k.visible&&!k.inSticky){g=h;break}}!g&&b.length>0&&(g=b[b.length-1]);for(let h of b)h!==g&&await h.dispose().catch(()=>{});if(g)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),g),await $(500),await g.click().catch(()=>e.evaluate(k=>k.click(),g)),await $(2e3);let h=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(h){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(I=>I.click(),h),await $(3e3);let k=e.url();if(k.includes("/premium/")||k.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await xe(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let x=await e.$('button[aria-label="Send without a note"]');if(x){console.log(" Modal appeared via More dropdown, sending without note...");try{await x.evaluate(I=>I.click())}catch{}return await $(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(h){console.log(" More dropdown fallback failed:",h.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{i.fatal=!0}return i}}async function yo(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:r=20,viewOnly:a=!1,delayBetweenProfiles:l=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:c="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
238
|
+
`});var wo={};Te(wo,{clickConnectButton:()=>Zt,default:()=>Wr,detectConnectionStatus:()=>xe,findConnectButton:()=>it,runFunnel:()=>yo,sendConnectionRequest:()=>en,shouldExcludeLocation:()=>yt,viewProfile:()=>Xt});async function ho(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 $(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}function yt(e,t=[]){if(!e||!t||t.length===0)return!1;let n=e.toLowerCase();return t.some(o=>n.includes(o.toLowerCase()))}async function Xt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:r=!1,extractSkills:a=!1,extractRecommendations:l=!1,extractCertifications:i=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await $(1500),await ho(e,t));let c=0;for(let g=0;g<2;g++){let h=await e.evaluate(()=>document.body.scrollHeight);for(let C=1;C<=6;C++)await e.evaluate(x=>window.scrollTo(0,x),h*C/6),await $(900);let k=await e.evaluate(()=>document.body.scrollHeight);if(k===c)break;c=k}await $(800);let f=await e.evaluate(()=>{let g=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"]),h=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"]),k=R=>{let D=(R||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(D)},C={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:[]},x=document.querySelector("main");if(!x)return C;let I=[...Array.from(x.querySelectorAll("h1")),...Array.from(x.querySelectorAll("h2"))],T=Array.from(x.querySelectorAll("h2")),L=I.find(R=>{let D=R.textContent&&R.textContent.trim(),O=(D||"").replace(/\s*\(\d+\)$/,"").trim();return D&&D.length>1&&D.length<100&&!g.has(O)&&!h.has(O)}),G=L?L.textContent.trim():null,v=L?L.parentElement:null;for(;v&&v!==x&&!Array.from(v.children).filter(D=>D.tagName==="P").some(D=>{let O=D.textContent&&D.textContent.trim();return O&&O.length>5&&!k(O)});)v=v.parentElement;let _=null,A=null,M=null,q=null;if(v&&v!==x){let R=Array.from(v.children).filter(O=>O.tagName==="P").filter(O=>{let fe=O.textContent&&O.textContent.trim();return fe&&fe.length>5&&!k(fe)});if(R[0]&&(_=R[0].textContent.trim()),R[1]){let O=R[1].textContent.trim().split(/\s*[·•]\s*/);A=O[0]||null,O.length>1&&(M=O.slice(1).join(" \xB7 "))}let D=Array.from(v.children).filter(O=>O.tagName==="DIV");for(let O=D.length-1;O>=0;O--){let fe=D[O].textContent&&D[O].textContent.trim();if(fe&&!(G&&fe.startsWith(G))&&(q=fe.split(/[·•]/)[0].trim(),q))break}}let ie=null;if(v){let R=v.querySelectorAll("p, span, div");for(let D of R){let O=(D.textContent||"").trim().replace(/^[·•]\s*/,"");if(O==="1st"||O==="2nd"||O==="3rd"){ie=O;break}}}let ae=!!x.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),j=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),F=j&&j.src||null,P=x.textContent||"",H=null,se=P.match(/(\d+\+?)\s+connections\b/i);se&&(H=se[1]+" connections");let lt=null,an=P.match(/(\d+)\s+mutual connection/i),ln=P.match(/and\s+(\d+)\s+other mutual/i),xo=P.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);an?lt=parseInt(an[1],10):ln?lt=2+parseInt(ln[1],10):xo&&(lt=2);let cn=null,un=null,dn=T.find(R=>R.textContent&&R.textContent.trim()==="About");if(dn){let R=dn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").trim();D=D.replace(/^About\s*/,"").trim();let O=D.match(/Top skills\s*(.+?)$/i);if(O){let bt=O[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Do=>Do.trim()).filter(Boolean);bt.length>0&&bt.length<10&&(un=bt)}D=D.split(/\n?…\s*more/i)[0].trim(),D=D.split(/\n?\.\.\.\s*more/i)[0].trim(),D=D.split(/\bTop skills\b/i)[0].trim(),D=D.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),cn=D||null}}let fn=null,mn=T.find(R=>R.textContent&&R.textContent.trim()==="Activity");if(mn){let R=mn.parentElement;for(;R&&R.tagName!=="SECTION";)R=R.parentElement;if(R){let D=(R.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);D&&(fn=parseInt(D[1].replace(/,/g,""),10))}}let Ao=[...new Set(T.map(R=>(R.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(R=>R&&R.length>1&&R.length<60&&R!==G).filter(R=>g.has(R)))],Ue=document.body.textContent||"",To=/#OpenToWork\b/i.test(Ue)||/\bOpen to work\b/.test(Ue),Ro=/#Hiring\b/i.test(Ue)||/\bI'?m hiring\b/i.test(Ue)||/\bWe are hiring\b/i.test(Ue);return{name:G,title:_,location:q,currentCompany:A,currentSchool:M,connectionDegree:ie,hasVerifiedBadge:ae,photoUrl:F,connectionsLevel:H,mutualConnectionsCount:lt,followers:fn,openToWork:To,hiring:Ro,about:cn,topSkills:un,availableSections:Ao}});console.log(`Viewed: ${f.name} - ${f.title}`);let d=null,m=null,y=null,p=null,S=null,w=null;if(o||s||r||a||l||i){let g=await Promise.resolve().then(()=>(go(),po));o&&(d=await g.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),s&&(m=await g.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${m.length} entries`)),r&&(y=await g.extractEducationFromDetails(e,t),console.log(` + Education: ${y.length} entries`)),a&&(p=await g.extractSkillsFromDetails(e,t),console.log(` + Skills: ${p.length} entries`)),l&&(S=await g.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${S.length} entries`)),i&&(w=await g.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${w.length} entries`))}return{...f,profileUrl:t,...d!==null&&{experience:d},...m!==null&&{featured:m},...y!==null&&{education:y},...p!==null&&{skillsFull:p},...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 $(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(u.message||""))throw u;return null}}async function xe(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),s=u=>Array.from(document.querySelectorAll(u)).filter(o),r=s('button[aria-label*="Pending"], a[aria-label*="Pending"]'),a=s('button[aria-label*="Message"], a[aria-label*="Message"]')[0]||null,l=s('button[aria-label*="Invite"][aria-label*="connect"], button[aria-label="Connect"], a[href*="custom-invite"]')[0]||null,i={pendingCount:r.length,pendingLabels:r.map(u=>u.getAttribute("aria-label")),hasMessageBtn:!!a,hasConnectBtn:!!l};return r.length>0?{status:"pending",debug:i}:a&&!l?{status:"connected",debug:i}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:i}:{status:"not_connected",debug:i}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function it(e){let t=null,n=await e.evaluate(()=>{let i=document.querySelector("h1")?.textContent?.trim();if(i&&!i.includes("notification"))return i;let u=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(u&&(i=u.textContent?.trim(),i&&!i.includes("notification")))return i;let c=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(c)return c.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${n}"`),n){let i=await e.evaluate(()=>{let c=document.querySelectorAll('a[href*="custom-invite"]');return{count:c.length,labels:Array.from(c).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});i.count>0&&console.log(` S0: ${i.count} custom-invite links: ${JSON.stringify(i.labels)}`),t=await e.evaluateHandle(c=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=c.toLowerCase().split(" ")[0],m='[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"], [class*="discover"], [class*="similar"], aside';for(let y of f){let p=y.getBoundingClientRect();if(p.width===0||p.height===0||y.closest(m))continue;if((y.getAttribute("aria-label")||"").toLowerCase().includes(d))return y}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 i=n.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${i}"`);let u=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),m=document.querySelectorAll("button[aria-label]");return Array.from(m).filter(p=>{let S=p.getAttribute("aria-label")||"";return(S.toLowerCase().includes("invite")||S.toLowerCase().includes("connect"))&&d.test(S)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},i);u.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(u)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let y of d){let p=y.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return y}return null},i);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: button matching profile name"),{button:c,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&n){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping primary button: wrong person (${i})`),t=null)}if(t||(t=await e.$('button.artdeco-button--primary[aria-label="Connect"]:not([class*="sticky-header"]):not([class*="muted"])')),t)return console.log(" Found: primary button"),{button:t,method:"primary_button"};let o=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');o.length===0&&(o=await e.$$('button[aria-label="Connect"]'));let s=n?n.split(" ")[0].toLowerCase():"",r=null;for(let i of o){let u=await e.evaluate((c,f)=>{let d=c.className.includes("muted"),m=c.className.includes("sticky-header")||c.className.includes("sticky"),y=c.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(c.getAttribute("aria-label")||"").toLowerCase(),S=p.includes("invite"),w=f?p.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:y,hasInvite:S,matchesName:w,ariaLabel:p}},i,s);if(!u.isMuted&&!u.isStickyHeader&&!u.inRecommendations){if(u.hasInvite&&!u.matchesName){console.log(` Skipping secondary button: wrong person (${u.ariaLabel})`);continue}r=i;break}}for(let i of o)i!==r&&await i.dispose().catch(()=>{});if(r)return console.log(" Found: secondary button"),{button:r,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let a=null,l=await e.$$('button[id*="profile-overflow-action"]');for(let i of l){let u=await e.evaluate(c=>{let f=c.getBoundingClientRect(),d=f.width>0&&f.height>0,m=c.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},i);if(u.isVisible&&!u.isInStickyHeader){a=i,console.log(" Found More button by ID pattern (main)");break}}for(let i of l)i!==a&&await i.dispose().catch(()=>{});if(!a&&l.length>0&&(a=l[l.length-1],console.log(" Found More button by ID pattern (last)")),a||(a=await e.$('button[aria-label="More actions"]'),a&&console.log(" Found More button by aria-label")),!a){let i=await e.evaluateHandle(()=>{let c=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),y=d.getAttribute("aria-label")||"",p=d.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||y.includes("Follow")||y.includes("Message")||y.includes("Invite")});if(!c)return null;let f=c.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==c)return m;f=f.parentElement}return null});a=i?.asElement?.()||null,a||await i?.dispose?.().catch(()=>{}),a&&console.log(" Found More button by text (near profile actions)")}if(a)try{if(await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),a),await $(500),await e.evaluate(c=>c.click(),a),await $(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 c=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let m=d.querySelector('a[href*="custom-invite"]');if(m)return m;for(let y of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(y.innerText?.trim()==="Connect")return y}return null});u=c?.asElement?.()||null,u||await c?.dispose?.().catch(()=>{})}if(!u){let c=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let y of m.querySelectorAll('[role="menuitem"], a, div')){let p=y.innerText?.trim();p&&p.length<40&&d.push(p)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(c)}`)}if(u)return console.log(" Found: More dropdown"),{button:u,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(i){console.log(" More dropdown click failed:",i.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&n){let i=await e.evaluate(c=>(c.getAttribute("aria-label")||"").toLowerCase(),t),u=n.split(" ")[0].toLowerCase();i.includes("invite")&&!i.includes(u)&&(console.log(` Skipping generic button: wrong person (${i})`),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 Zt(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await $(500);let n=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=n.tag==="A"&&n.href&&n.href.includes("custom-invite"),r=n.tag==="DIV",a=(n.ariaLabel||"").toLowerCase();if(a.includes("invite")){let c=await e.evaluate(()=>((document.querySelector("main h1")||document.querySelector("h1")||document.querySelector("main h2"))?.textContent?.trim()||"").split(" ")[0].toLowerCase());if(c&&!a.includes(c))return console.log(` \u2717 Identity guard: control is for someone else ("${n.ariaLabel}") \u2014 refusing to click (target: ${c})`),"wrong_target"}if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(f=>f.click(),t)]),await $(2e3);let c=e.url();if(c.includes("premium")||c.includes("redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium page - connection limit reached?"),await e.goBack(),await $(2e3),"premium_redirect"}else r?(await e.evaluate(c=>c.click(),t),await $(3e3)):(await e.evaluate(c=>c.click(),t),await $(3e3));let l=e.url();if(l.includes("/premium/")||l.includes("/redeem"))return console.log(" \u26A0 LinkedIn redirected to Premium upsell page"),"premium_redirect";let i=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),u=e.url();return console.log(i?` \u2713 Connect sent \u2014 ${u}`:` \u26A0 No modal after connect click \u2014 ${u}`),"success"}async function Jr(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 $(1500);let n=await it(e);if(n){await e.evaluate(s=>s.click(),n),await $(2e3);let o=await e.$('button[aria-label="Send without a note"]');if(o){try{await o.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function en(e,t,n={}){let{source:o="unknown",skipQuotaGate:s=!1,skipQuotaRecord:r=!1}=n;if(!s){let l=_t();if(!l.allowed)return console.log(` \u26A0 Connection quota reached \u2014 not sending: ${l.reason}`),{success:!1,reason:"quota_exhausted",connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:l.reason,profileInfo:null}}let a=await Vr(e,t,n);return a.connectionSent&&!r&&Tn(t,o),a}async function Vr(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,skipIfPending:r=!0,skipIfConnected:a=!0,excludeLocations:l=[]}=n,i={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(`
|
|
239
|
+
--- Connecting: ${u} ---`),l.length>0){let w=J()[t]?.location;if(yt(w,l))return console.log(` \u26A0 Excluded location (stored): ${w}`),i.reason="excluded_location",i.profileInfo={location:w},i}await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(5e3),await ye(e)&&(console.log(" Dismissed Premium overlay"),await $(2e3),await ho(e,t),await $(2e3)),i.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"]),b=j=>{let F=(j||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(F)},g={name:null,title:null,location:null,about:null,company:null,connectionDegree:null,connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1},h=document.querySelector("main");if(!h)return g;let k=[...Array.from(h.querySelectorAll("h1")),...Array.from(h.querySelectorAll("h2"))],C=Array.from(h.querySelectorAll("h2")),x=k.find(j=>{let F=j.textContent&&j.textContent.trim();return F&&F.length>1&&F.length<100&&!w.has(F)&&F!=="0 notifications"}),I=x?x.textContent.trim():null,T=x?x.parentElement:null;for(;T&&T!==h&&!Array.from(T.children).filter(P=>P.tagName==="P").some(P=>{let H=P.textContent&&P.textContent.trim();return H&&H.length>5&&!b(H)});)T=T.parentElement;let L=null,G=null,v=null;if(T&&T!==h){let j=Array.from(T.children),F=j.filter(H=>H.tagName==="P").filter(H=>{let se=H.textContent&&H.textContent.trim();return se&&se.length>5&&!b(se)});F[0]&&(L=F[0].textContent.trim()),F[1]&&(G=F[1].textContent.trim());let P=j.filter(H=>H.tagName==="DIV");for(let H=P.length-1;H>=0;H--){let se=P[H].textContent&&P[H].textContent.trim();if(se&&!(I&&se.startsWith(I))&&(v=se.split(/[·•]/)[0].trim(),v))break}}let _=null;if(T){let j=T.querySelectorAll("p, span, div");for(let F of j){let P=(F.textContent||"").trim().replace(/^[·•]\s*/,"");if(P==="1st"||P==="2nd"||P==="3rd"){_=P;break}}}let A=null,M=C.find(j=>j.textContent&&j.textContent.trim()==="About");if(M){let j=M.parentElement;for(;j&&j.tagName!=="SECTION";)j=j.parentElement;j&&(A=(j.textContent||"").trim().replace(/^About\s*/,"").trim()||null,A&&(A=A.replace(/(?:…|\.\.\.)?\s*(?:see (?:more|less)|show (?:more|less))\s*$/i,"").trim()||null))}let q=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),ie=q&&q.src||null,ae=!!h.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]');return{name:I,title:L,location:v,about:A,company:G,connectionDegree:_,connectionsCount:null,mutualConnections:null,photoUrl:ie,hasVerifiedBadge:ae}});try{let w=e.url();w&&/\/in\/[^/?#]/.test(w)&&(i.resolvedUrl=w.split("?")[0].replace(/\/+$/,""))}catch{}if(l.length>0){let w=i.profileInfo?.location,b=J()[t]?.location,g=w||b;if(yt(g,l))return console.log(` \u26A0 Excluded location (${w?"live":"stored"}): ${g}`),i.reason="excluded_location",i;!w&&b==null&&console.log(" \u26A0 Location unknown (live scrape null, no stored value) \u2014 proceeding")}let f=await xe(e);if(i.profileInfo?.connectionDegree==="1st"&&f!=="pending"&&(f!=="connected"&&console.log(" (degree badge = 1st \u2192 already connected)"),f="connected"),f==="pending"&&r)return console.log(" \u26A0 Already pending - skipping"),i.reason="pending",i;if(f==="connected"&&a)return console.log(" \u26A0 Already connected - skipping"),i.reason="connected",i;await ye(e);let d=await it(e);if(!d&&(await ye(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await $(2e3),d=await it(e)),!d))return console.log(" \u2717 Connect not found"),i.reason="button_not_found",i;i.method=d.method;let m=await Zt(e,d.button);if(m==="wrong_target")return console.log(" \u2717 Not sent \u2014 connect control did not belong to this profile"),i.reason="wrong_target",i;if(m==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3);let w=await xe(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await ye(e),await $(1e3);let b=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(b)try{await e.evaluate(h=>h.scrollIntoView({behavior:"smooth",block:"center"}),b),await $(500),await b.click().catch(()=>e.evaluate(h=>h.click(),b)),await $(2e3);let g=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(g){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(C=>C.click(),g),await $(3e3);let h=e.url();if(h.includes("/premium/")||h.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),i.reason="premium_required",i;if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.method="more_dropdown",i.withCustomMessage=!1,i;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await $(500),i.reason="premium_required",i}catch(g){return console.log(" More dropdown failed:",g.message),await e.keyboard.press("Escape").catch(()=>{}),i.reason="premium_required",i}else return console.log(" \u2717 No More button found \u2014 Premium required"),i.reason="premium_required",i}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 $(500),i.reason="email_required",i}let p=await e.$('button[aria-label="Add a note"]'),S=await e.$('button[aria-label="Send without a note"]');if(!p&&!S){let w=await e.evaluate(()=>{let b=document.querySelector("#interop-outlet")?.shadowRoot;if(!b)return{addNote:!1,sendWithout:!1};let g=b.querySelector('button[aria-label="Add a note"]'),h=b.querySelector('button[aria-label="Send without a note"]');return{addNote:!!g,sendWithout:!!h}});if(w.addNote){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=b?.asElement?.()||null,p||await b.dispose().catch(()=>{})}if(w.sendWithout){let b=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));S=b?.asElement?.()||null,S||await b.dispose().catch(()=>{})}}if(s){if(p&&o){if(console.log(" Adding personalized note..."),await p.click(),await $(1500),await e.$("div.modal-upsell")){let g=await Jr(e);return i.success=g,i.connectionSent=g,i.reason=g?"sent_without_note_upsell":"upsell_failed",i.withCustomMessage=!1,i}let b=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(b){let g=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),h=o.replace("{name}",g);await b.type(h,{delay:20}),await $(500);let k=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if(k){try{await k.evaluate(C=>C.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (with note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_with_note",i.withCustomMessage=!0,i.messageSent=h,i}}}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 $(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}else if(p&&!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(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}}else{console.log(" Sending without note (custom messages disabled)...");let w=S;if(w){try{await w.evaluate(b=>b.click())}catch{console.log(" Click timeout, likely still sent")}return await $(3e3),console.log(" \u2713 Connection sent (without note)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}}if(d.method!=="more_dropdown"){console.log(" \u26A0 No modal after click \u2014 trying More dropdown fallback..."),e.url().includes("/in/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(4e3)),await ye(e),await $(500);let b=await e.$$('button[id*="profile-overflow-action"]'),g=null;for(let h of b){let k=await e.evaluate(C=>{let x=C.getBoundingClientRect();return{visible:x.width>0&&x.height>0,inSticky:!!C.closest('.sticky-header, [class*="sticky"]')}},h);if(k.visible&&!k.inSticky){g=h;break}}!g&&b.length>0&&(g=b[b.length-1]);for(let h of b)h!==g&&await h.dispose().catch(()=>{});if(g)try{await e.evaluate(k=>k.scrollIntoView({behavior:"smooth",block:"center"}),g),await $(500),await g.click().catch(()=>e.evaluate(k=>k.click(),g)),await $(2e3);let h=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(h){console.log(" Found Connect in More dropdown, clicking..."),i.method="more_dropdown",await e.evaluate(I=>I.click(),h),await $(3e3);let k=e.url();if(k.includes("/premium/")||k.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await $(3e3),await xe(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i):(i.reason="premium_required",i);if(await xe(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i;let x=await e.$('button[aria-label="Send without a note"]');if(x){console.log(" Modal appeared via More dropdown, sending without note...");try{await x.evaluate(I=>I.click())}catch{}return await $(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),i.success=!0,i.connectionSent=!0,i.reason="sent_without_note",i.withCustomMessage=!1,i}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(h){console.log(" More dropdown fallback failed:",h.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),i.reason="modal_failed",i}catch(u){console.error(` \u2717 Error: ${u.message}`),i.reason="error",i.error=u.message;let c=u.message.toLowerCase();if(c.includes("detached")||c.includes("session closed")||c.includes("target closed")||c.includes("browser has disconnected")||c.includes("protocol error"))return i.fatal=!0,i;try{await e.goto("about:blank",{timeout:1e4}),await $(1e3)}catch{i.fatal=!0}return i}}async function yo(e,t,n={}){let{message:o=null,useCustomMessage:s=!0,maxConnections:r=20,viewOnly:a=!1,delayBetweenProfiles:l=3e3,onProfileProcessed:i=null,excludeLocations:u=[],source:c="unknown"}=n,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
240
240
|
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${a?"View Only":`Connect (max ${r})`}`),a||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),u.length>0&&console.log(`Excluding locations: ${u.join(", ")}`),!a){let m=Ke();console.log(`Quota: today ${m.daily.sent}/${m.daily.max} | week ${m.weekly.sent}/${m.weekly.max}`)}console.log("");let d=0;for(let m=0;m<t.length;m++){let y=t[m];try{if(e.isClosed()){console.log(`
|
|
241
241
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
242
242
|
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!y.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let p=_n(y.profileUrl);if(p==="pending"||p==="connected"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl} \u2014 skipped (db: ${p})`),p==="pending"||p==="sent_with_note"||p==="sent_without_note"||p==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,i&&await i(y,f,{success:!1,reason:p,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${y.name||y.profileUrl}`);let S=null;if(a){let w=await Xt(e,y.profileUrl);w?(Se(y.profileUrl,{...w,source:c}),f.viewed++,S={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(f.errors++,S={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=r){console.log(` Max connections per session (${r}) reached`);break}let w=_t();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(S=await en(e,y.profileUrl,{message:o,useCustomMessage:s,excludeLocations:u,source:c,skipQuotaGate:!0}),S.success)f.connectionsSent++;else switch(S.reason){case"pending":f.skipped.pending++;break;case"connected":f.skipped.connected++;break;case"email_required":f.skipped.email++;break;case"button_not_found":f.skipped.notFound++;break;case"excluded_location":f.skipped.excludedLocation++;break;default:f.errors++}}if(S?.fatal){console.log(`
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
var Pe=Object.defineProperty;var B=(e,t)=>{for(var o in t)Pe(e,o,{get:t[o],enumerable:!0})};import{pathToFileURL as uo}from"url";var Y={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Ue={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function M(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let o=parseInt(t[1],10),n=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&o!==12&&(o+=12),!s&&o===12&&(o=0),{hours:o,minutes:n}}function J(e,t){if(!e)return null;let o=e.trim();if(!o)return null;if(t=t||new Date,/^just\s*now$/i.test(o))return t.toISOString();if(/^today\b/i.test(o)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(o)){let l=M(o),c=new Date(t);return l?c.setHours(l.hours,l.minutes,0,0):c.setHours(0,0,0,0),c.toISOString()}let n=o.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(n){let l=Ue[n[1].toLowerCase()],c=M(n[2]||""),a=new Date(t),u=a.getDay()-l;return u<=0&&(u+=7),a.setDate(a.getDate()-u),c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let s=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=Y[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(s[2],10),a=parseInt(s[3],10),f=M(s[4]||"");return new Date(a,l,c,f?.hours||0,f?.minutes||0,0,0).toISOString()}let r=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=Y[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(r[2],10),a=M(r[3]||""),f=t.getFullYear(),u=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return u>t&&u.setFullYear(f-1),u.toISOString()}let i=o.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=Y[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(i[2],10),a=M(i[3]||""),f=t.getFullYear(),u=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return u>t&&u.setFullYear(f-1),u.toISOString()}return null}async function P(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}import{getPluginConfig as qe}from"@ilivemylife/graph-sdk";var Be=await qe();for(let[e,t]of Object.entries(Be))process.env[e]===void 0&&(process.env[e]=t);var Je=process.env.LINKEDIN_NAME,_=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),$o=Object.freeze(new Set([_.DRAFT,_.CONFIRMED,_.NEEDS_REVIEW])),He=Object.freeze(new Set([_.DRAFT,_.CONFIRMED,_.REJECTED,_.NEEDS_REVIEW]));import"dotenv/config";import*as S from"fs";import*as w from"path";import{fileURLToPath as We}from"url";var Ve=We(import.meta.url),Ye=w.dirname(w.dirname(Ve)),x=process.env.DATA_DIR?w.resolve(process.env.DATA_DIR,"collected-profiles"):w.join(Ye,"collected-profiles"),G=w.join(x,"people.json"),xo=w.join(x,"jobs.json"),Io=w.join(x,"quota.json"),Do=w.join(x,"conversations.json"),Ro=w.join(x,"sync-state.json"),_o=w.join(x,"application-questions.json"),Oo=w.join(x,"profile-history"),ce=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},jo=ce(process.env.CONNECT_MAX_DAILY,20),No=ce(process.env.CONNECT_MAX_WEEKLY,100),L=null,Ge=null,Ke=null,ze=null,Qe=null,Xe=null;function le(){L=null,Ge=null,Ke=null,ze=null,Qe=null,Xe=null}function ae(){S.existsSync(x)||S.mkdirSync(x,{recursive:!0})}function Ze(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";S.writeFileSync(n,o);for(let s=0;s<3;s++)try{S.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function et(e,t){if(!S.existsSync(e))return null;try{let o=JSON.parse(S.readFileSync(e,"utf-8"));try{S.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${w.resolve(e)}`);let n=e+".backup";if(S.existsSync(n))try{let s=JSON.parse(S.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{S.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{S.copyFileSync(e,e+".corrupted")}catch{}return null}}function H(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function U(){return L||(ae(),L=et(G,"people.json")||{},L)}function ue(e){ae(),L=e;try{Ze(G,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${w.resolve(G)}`)}}import st from"puppeteer";import{addExtra as rt}from"puppeteer-extra";import it from"puppeteer-extra-plugin-stealth";import fe from"fs";import tt from"path";var ot="cookies.json";function nt(){let e=process.env.ILML_SCOPE_DIR;return e?tt.join(e,"plugins-state","linkedin","cookies.json"):ot}function pe(){let e=nt();if(!fe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=fe.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}var de=rt(st);de.use(it());async function me(){let e=await de.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
|
|
2
|
+
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let o=await e.newPage();await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let n=pe();await o.setCookie(...n),console.log(" Browser launched, cookies loaded.")}catch(n){console.error(`
|
|
3
|
+
[!] ${n.message}
|
|
4
|
+
`),await e.close(),process.exit(1)}return{browser:e,page:o}}import"dotenv/config";import*as k from"fs";import*as D from"path";import{fileURLToPath as pt}from"url";import"dotenv/config";import{createGraphClient as ct,resolveToken as lt}from"@ilivemylife/graph-sdk";import{config as at}from"dotenv";at();var he=lt()||process.env.TOKEN;he||(console.error(`
|
|
5
|
+
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
6
|
+
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
7
|
+
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
8
|
+
`),process.exit(1));var ge=ct({token:he});function ut(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),n=t%60;return n?`${o}m ${n}s`:`${o}m`}function ft({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${ut(s)}`:"",c=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${a} \u2014 ${c} \u2014 ${i}${l}`}async function ye({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let c=`**${ft({scriptName:e,mode:t,status:o,error:s,duration:r})}**
|
|
9
|
+
|
|
10
|
+
${n.join(`
|
|
11
|
+
`)}`;try{await ge.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var dt=pt(import.meta.url),mt=D.dirname(D.dirname(dt)),K=process.env.DATA_DIR?D.resolve(process.env.DATA_DIR,"collected-profiles"):D.join(mt,"collected-profiles"),z=D.join(K,"run-log.json");function ht(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";k.writeFileSync(n,o);for(let s=0;s<3;s++)try{k.renameSync(n,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function Se(){try{if(!k.existsSync(z))return{runs:[]};let e=JSON.parse(k.readFileSync(z,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function we(e){k.existsSync(K)||k.mkdirSync(K,{recursive:!0});try{ht(z,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function be(e,t="default"){let o=Se();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),we(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function Q(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=Se(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,s=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=n,s=c.duration)}we(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";ye({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as p from"fs";import*as re from"os";import*as m from"path";import{fileURLToPath as Yt}from"url";var ee={};B(ee,{NAME:()=>yt,VERSION:()=>gt,up:()=>bt});import*as $ from"fs";import*as W from"path";var gt=1,yt="normalize-jobs-and-questions",St=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],wt=50;function X(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Z(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{$.writeFileSync(n,o)}catch(s){try{$.unlinkSync(n)}catch{}throw s}try{$.renameSync(n,e)}catch(s){try{$.unlinkSync(n)}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 bt(e,t){let o=W.join(e,"jobs.json"),n=W.join(t,"scouted-jobs.json"),s=W.join(e,"application-questions.json"),r=X(o)||{},i=X(n)||{},l=0,c=[];for(let f of Object.keys(r)){if(!i[f])continue;let u=i[f],d=r[f];for(let g of St)u[g]!=null&&d[g]==null&&(d[g]=u[g]);c.push(f),l++}l>0?(Z(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=X(s);if(a&&Array.isArray(a.applications)){let f={},u=0;for(let d of a.applications){let g=d.jobId||"unknown";f[g]||(f[g]={applications:[]});let y=(d.questions||[]).map(h=>{let F={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=wt?F.options=h.options:(F.optionsOmitted=!0,u++)),h.page&&(F.page=h.page),h.wasPreFilled&&(F.wasPreFilled=!0),h.wasRetry&&(F.wasRetry=!0),F});f[g].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||y.length,questions:y})}Z(s,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),u>0&&console.log(` Phase 2: Stripped bloated options from ${u} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];Z(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var te={};B(te,{NAME:()=>kt,VERSION:()=>vt,up:()=>Ct});import*as A from"fs";import*as ve from"path";var vt=2,kt="reset-unread-flags";function $t(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function At(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{A.writeFileSync(n,o)}catch(s){try{A.unlinkSync(n)}catch{}throw s}try{A.renameSync(n,e)}catch(s){try{A.unlinkSync(n)}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 Ct(e){let t=ve.join(e,"conversations.json"),o=$t(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}At(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var oe={};B(oe,{NAME:()=>Tt,VERSION:()=>Et,up:()=>_t});import*as C from"fs";import*as ke from"path";var Et=3,Tt="recompute-last-message-by",xt=new Set(["draft","confirmed","rejected","needs_review"]);function It(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function Dt(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{C.writeFileSync(n,o)}catch(s){try{C.unlinkSync(n)}catch{}throw s}try{C.renameSync(n,e)}catch(s){try{C.unlinkSync(n)}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 Rt(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!xt.has(r.status));if(o.length===0)return"them";let n=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function _t(e){let t=ke.join(e,"conversations.json"),o=It(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.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,i=0;for(let l of Object.keys(o)){let c=o[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let a=Array.isArray(c.messages)?c.messages:[],f=Rt(a,n),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,s++}if(s===0){console.log(" No conversations to recompute.");return}Dt(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} 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 ne={};B(ne,{NAME:()=>jt,VERSION:()=>Ot,up:()=>Mt});import*as E from"fs";import*as $e from"path";var Ot=4,jt="split-connection-timestamps",Nt=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ft(e){if(!E.existsSync(e))return null;let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Lt(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{E.writeFileSync(n,o)}catch(s){try{E.unlinkSync(n)}catch{}throw s}try{E.renameSync(n,e)}catch(s){try{E.unlinkSync(n)}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 Mt(e){let t=$e.join(e,"people.json"),o=Ft(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,s=0;for(let r of Object.keys(o)){let i=o[r];!i||typeof i!="object"||(s++,Nt.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Lt(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as v from"path";import{fileURLToPath as Pt}from"url";var Ut=Pt(import.meta.url),qt=v.dirname(v.dirname(Ut)),q=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"market-research"):v.join(qt,"market-research"),ln=v.join(q,"scouted-jobs.json"),an=v.join(q,"discovered-people.json"),un=v.join(q,"visit-log.json"),fn=v.join(q,"companies.json"),pn=v.join(q,"job-decisions.json");function Ae(){Bt=null,Jt=null,Ht=null,Wt=null,Vt=null}var Bt=null;var Jt=null;var Ht=null;var Wt=null;var Vt=null;var Gt=Yt(import.meta.url),Kt=m.dirname(Gt),zt=m.dirname(m.dirname(Kt));function Qt(e){return e&&(e==="~"?re.homedir():e.startsWith("~/")||e.startsWith("~\\")?m.join(re.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?m.resolve(Qt(process.env.DATA_DIR)):zt,j=m.join(T,"collected-profiles"),N=m.join(T,"market-research"),b=m.join(T,".schema-version"),Ce=[m.join(j,".schema-version"),m.join(N,".schema-version")],R=4,I=[{version:1,module:ee},{version:2,module:te},{version:3,module:oe},{version:4,module:ne}];(function(){I.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of I){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=I.length?I[I.length-1].version:0;if(o!==R)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${R}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<I.length;n++){let s=n+1;if(I[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${I[n].version}`)}})();function Ie(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
12
|
+
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
13
|
+
`),process.exit(1));try{p.mkdirSync(T,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
14
|
+
[FATAL] Cannot create DATA_DIR (${T}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
15
|
+
`),process.exit(1))}let e;try{e=p.statSync(T)}catch(t){console.error(`
|
|
16
|
+
[FATAL] DATA_DIR (${T}) is not accessible: ${t.message}
|
|
17
|
+
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
18
|
+
[FATAL] DATA_DIR (${T}) 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.
|
|
19
|
+
`),process.exit(1));for(let t of[j,N]){let o;try{o=p.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
|
|
20
|
+
[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.
|
|
21
|
+
`),process.exit(1))}}var O=m.join(T,".migration-lock");function Xt(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return p.writeFileSync(O,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(p.readFileSync(O,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}n&&r<s&&(console.error(`
|
|
22
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${O}
|
|
23
|
+
`),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.
|
|
24
|
+
`),process.exit(1)),n&&r>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=O+".tmp";try{return p.writeFileSync(o,e),p.renameSync(o,O),!0}catch(n){try{p.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function ie(){try{if(JSON.parse(p.readFileSync(O,"utf-8")).pid!==process.pid)return;p.unlinkSync(O)}catch{}}var Ee=!1;function Zt(){if(Ee)return;Ee=!0;let e=()=>{try{ie()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function eo(){if(p.existsSync(b))return;let e=[],t=[];for(let r of Ce)if(p.existsSync(r))try{e.push({file:r,schema:V(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
|
|
25
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
|
|
26
|
+
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.
|
|
27
|
+
`),process.exit(1)}if(e.length===0)return;let o=e.map(r=>r.schema.version);if(new Set(o).size>1){console.error(`
|
|
28
|
+
[FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
29
|
+
`),process.exit(1)}let n=e[0].schema,s=b+".tmp";try{p.writeFileSync(s,JSON.stringify(n,null,2)),p.renameSync(s,b)}catch(r){try{p.unlinkSync(s)}catch{}throw r}for(let r of Ce)if(p.existsSync(r))try{p.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${b}`)}function to(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function V(e){let t=p.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Te(){if(eo(),!p.existsSync(b))return{version:0,migrations:[]};let e;try{e=V(b)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
30
|
+
[FATAL] ${b} is not valid JSON: ${o.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.
|
|
31
|
+
`),process.exit(1)}let t=to(e);return t===null&&(console.error(`
|
|
32
|
+
[FATAL] ${b} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
33
|
+
`),process.exit(1)),t}function De(e){try{p.chmodSync(e,384)}catch{}}function oo(e){if(Ie(),p.existsSync(b))try{if(p.lstatSync(b).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${b}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=b+".tmp";try{p.writeFileSync(t,JSON.stringify(e,null,2)),De(t),p.renameSync(t,b)}catch(o){try{p.unlinkSync(t)}catch{}throw o}}function xe(e,t){if(!p.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=p.readdirSync(e).filter(l=>{let c=l.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return p.statSync(m.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let c=m.join(e,l),a=m.join(e,l+o);if(p.existsSync(a)){r++;continue}try{_e(c,a),s++}catch(f){i.push({file:l,err:f.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${m.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${m.basename(e)}/ (${o})${l}`)}}var se=!1;async function Re(){if(se)return;Ie(),co();let t=Te().version;if(t===R){se=!0;return}Zt(),Xt(),process.on("exit",ie),t>R&&(console.error(`
|
|
34
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${R}.`),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.
|
|
35
|
+
`),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${R}.
|
|
36
|
+
`),process.exit(1)),console.log(`
|
|
37
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${R}`);let o=lo();if(!o.ok){console.error(`
|
|
38
|
+
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of o.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
39
|
+
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
40
|
+
`),process.exit(1)}let n=I.filter(s=>s.version>t);for(let s of n){console.log(`
|
|
41
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{xe(j,s.version),xe(N,s.version)}catch(c){console.error(`
|
|
42
|
+
[FATAL] Pre-migration backup failed for ${r}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
43
|
+
`),process.exit(1)}let l=s.module;try{await l.up(j,N)}catch(c){console.error(`
|
|
44
|
+
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=ao(i);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
45
|
+
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
46
|
+
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
47
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:s.version,name:l.NAME||r,appliedAt:c},f=Te();f.version=s.version,f.migratedAt=c,f.migrations=f.migrations||[],f.migrations.push(a),oo(f)}catch(c){console.error(`
|
|
48
|
+
[FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
49
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{le()}catch{}try{Ae()}catch{}se=!0,ie(),console.log(`
|
|
50
|
+
\u2713 Schema is now at v${R}
|
|
51
|
+
`)}var no=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function so(e){let t=e.toLowerCase();return no.some(o=>o.test(t))}var ro=6e4;function io(){let e=Date.now(),t=[];for(let o of[T,j,N]){if(!p.existsSync(o))continue;let n;try{n=p.readdirSync(o)}catch{continue}for(let s of n){if(!so(s))continue;let r=m.join(o,s);try{let i=p.statSync(r);if(!i.isFile()||e-i.mtimeMs<ro)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function co({verbose:e=!1}={}){let t=io();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{p.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${m.basename(n.dir)}/${n.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function lo(){let e=[];for(let t of[j,N]){if(!p.existsSync(t))continue;let o=p.readdirSync(t).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of o){let s=m.join(t,n);try{V(s)}catch(r){e.push({dir:m.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ao(e){let t=[],o=[];for(let r of[j,N]){if(!p.existsSync(r))continue;let i=p.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let c=m.join(r,l),a=l.slice(0,-e.length),f=m.join(r,a);try{a.toLowerCase().endsWith(".json")?V(c):p.accessSync(c,p.constants.R_OK),t.push({backupPath:c,originalPath:f,fileName:l,dir:r})}catch(u){o.push(`${m.basename(r)}/${l}: ${u.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:c}of t)try{_e(r,i),n++}catch(a){s.push(`${m.basename(c)}/${l}: ${a.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function _e(e,t){let o=t+".tmp";try{p.copyFileSync(e,o),De(o)}catch(n){try{p.unlinkSync(o)}catch{}throw n}try{p.renameSync(o,t)}catch(n){try{p.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${t} (${n.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=n.code,s}throw n}}function fo(){let e={list:!1,full:!1,max:1/0,dryRun:!1,verbose:!1};for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--full"?e.full=!0:t==="--dry-run"?e.dryRun=!0:t==="--verbose"?e.verbose=!0:t.startsWith("--max=")&&(e.max=parseInt(t.split("=")[1],10));return e}function po(){let e=U(),t=Object.values(e),o=t.length,n={};for(let r of t){let i=r.connectionStatus||"(none)";n[i]=(n[i]||0)+1}let s={};for(let r of t){for(let i of r.sources||[])s[i]=(s[i]||0)+1;(!r.sources||r.sources.length===0)&&(s["(no source)"]=(s["(no source)"]||0)+1)}console.log(`
|
|
52
|
+
=== People Database: ${o} entries ===
|
|
53
|
+
`),console.log("By connection status:");for(let[r,i]of Object.entries(n).sort((l,c)=>c[1]-l[1]))console.log(` ${r.padEnd(30)} ${i}`);console.log(`
|
|
54
|
+
By source:`);for(let[r,i]of Object.entries(s).sort((l,c)=>c[1]-l[1]))console.log(` ${r.padEnd(30)} ${i}`);console.log()}async function mo(e){let t="https://www.linkedin.com/mynetwork/invite-connect/connections/";console.log(`Navigating to ${t}`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await P(3e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector('main a[href*="/in/"]',{timeout:15e3})}catch{console.warn("\u26A0 No connection cards found after 15s. Page may have changed layout.")}let n=await e.evaluate(()=>{let i=((document.querySelector("main")||document.body).innerText||"").match(/([\d,]+)\s+connections?/i);return i?parseInt(i[1].replace(/,/g,""),10):null});return n&&console.log(` LinkedIn reports: ${n.toLocaleString()} connections`),n}async function je(e){return e.evaluate(()=>{let o=(document.querySelector("main")||document.body).querySelectorAll('a[href*="/in/"]'),n={};for(let r of o){let i=r.getAttribute("href");if(!i)continue;let l;try{let c=new URL(i,location.origin);l=c.origin+c.pathname.replace(/\/+$/,"")}catch{continue}n[l]||(n[l]=[]),n[l].push(r)}let s=[];for(let[r,i]of Object.entries(n)){let l=null;for(let y of i){let h=y.textContent?.trim();!h||y.querySelector("img")||(!l||h.length<l.textContent.trim().length)&&(l=y)}let c=l?.textContent?.trim()||null,a=l||i[0];for(let y=0;y<10&&a?.parentElement;y++){a=a.parentElement;let h=a.innerText||"";if((h.includes("Connected on")||h.includes("Message"))&&(h.match(/Connected on/g)||[]).length<=1)break}let f=(a?.innerText||"").split(`
|
|
55
|
+
`).map(y=>y.trim()).filter(Boolean),u=null,d=null,g=f.indexOf(c);if(g>=0&&g+1<f.length){let y=f[g+1];!y.startsWith("Connected on")&&y!=="Message"&&(u=y)}for(let y of f)if(y.startsWith("Connected on")){d=y;break}s.push({profileUrl:r,name:c,title:u,time:d})}return s})}async function Ne(e){return e.evaluate(()=>{let t=document.querySelector("main")||document.body,o=null,n=[t,...t.querySelectorAll("div, section")];for(let r of n){let i=getComputedStyle(r);if((i.overflowY==="auto"||i.overflowY==="scroll")&&r.scrollHeight>r.clientHeight+10){o=r;break}}o&&o.scrollBy(0,800),window.scrollBy(0,800);let s=document.querySelectorAll("button");for(let r of s){let i=r.textContent?.trim().toLowerCase()||"";if((i.includes("load more")||i.includes("show more"))&&r.getBoundingClientRect().height>0)return r.click(),"clicked"}return o?"scrolled":"window-scroll"})}async function ho(e,t){let{max:o,verbose:n,dryRun:s}=t,r=new Map,i=0,l=0,c=3,a=10;for(;;){i++;let f=await je(e),u=0;for(let g of f)g.profileUrl&&(r.has(g.profileUrl)||(r.set(g.profileUrl,g),u++));if(n?console.log(` Round #${i}: ${u} new | Total: ${r.size}`):process.stdout.write(`\r Connections found: ${r.size} (page #${i})`),!s&&i%a===0&&(Me(Array.from(r.values()),!1),n&&console.log(` \u{1F4BE} Saved progress (${r.size} connections)`)),r.size>=o){console.log(`
|
|
56
|
+
Reached --max=${o}, stopping.`);break}if(u===0){if(l++,l>=c){console.log(`
|
|
57
|
+
${c} rounds with no new cards \u2014 end of list.`);break}}else l=0;let d=await Ne(e);n&&d==="clicked"&&console.log(' \u2192 Clicked "Load more"'),await P(2e3)}return n||process.stdout.write(`
|
|
58
|
+
`),Array.from(r.values())}async function go(e,t){let{max:o,verbose:n}=t,s=U(),r=new Set;for(let[f,u]of Object.entries(s))u.connectionStatus==="connected"&&u.sources?.includes("sync-connections")&&r.add(f);console.log(` Known synced connections in DB: ${r.size}`);let i=new Map,l=0,c=0,a=3;for(;;){l++;let f=await je(e),u=0,d=0;for(let h of f)h.profileUrl&&(i.has(h.profileUrl)||(i.set(h.profileUrl,h),r.has(h.profileUrl)?d++:u++));let g=Array.from(i.values()).filter(h=>!r.has(h.profileUrl)).length;if(n?console.log(` Round #${l}: ${u} new, ${d} known | New total: ${g}`):process.stdout.write(`\r New connections: ${g} (page #${l})`),g>=o){console.log(`
|
|
59
|
+
Reached --max=${o}, stopping.`);break}if(u===0&&d>0){if(c++,c>=a){console.log(`
|
|
60
|
+
${a} consecutive pages of known connections \u2014 caught up.`);break}}else if(u>0)c=0;else if(c++,c>=a){console.log(`
|
|
61
|
+
${a} empty rounds \u2014 end of list.`);break}let y=await Ne(e);n&&y==="clicked"&&console.log(' \u2192 Clicked "Load more"'),await P(2e3)}return n||process.stdout.write(`
|
|
62
|
+
`),Array.from(i.values())}var Fe=new Set(["pending","sent_with_note","sent_without_note","sent_without_note_upsell"]);function Oe(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Le(e){let t=new Map;for(let[o,n]of Object.entries(e)){let s=H(n.profileUrl||o);s&&!t.has(s)&&t.set(s,o)}for(let[o,n]of Object.entries(e))for(let s of n.aliases||[])s&&!t.has(s)&&t.set(s,o);return t}function yo(e,t){let o=[],n=Le(t);for(let s of e){if(!s.profileUrl)continue;let r=n.get(H(s.profileUrl)),i=r?t[r]:void 0;i&&Fe.has(i.connectionStatus)&&o.push({...s,previousStatus:i.connectionStatus})}return o}function Me(e,t){let o=U(),n=new Date().toISOString(),s=n.slice(0,10),r={newPeople:0,updatedToConnected:0,alreadyConnected:0,flaggedDuplicates:0,flagged:[]},i=Le(o),l=new Map;for(let[c,a]of Object.entries(o)){if(!Fe.has(a.connectionStatus))continue;let f=Oe(a.name);f&&(l.has(f)||l.set(f,[]),l.get(f).push(c))}for(let c of e){if(!c.profileUrl)continue;let a=H(c.profileUrl),f=a?i.get(a):null,u=f?o[f]:void 0;if(u){if(u.connectionStatus!=="connected"){u.connectionStatus="connected";let d=c.time?J(c.time.replace(/^Connected\s+on\s+/i,"")):null;u.connectedAt=d||n,u.connectionDate=(d||n).slice(0,10),u.lastUpdated=n,r.updatedToConnected++}else if(r.alreadyConnected++,c.time&&(!u.connectedAt||!u.connectionDate)){let d=J(c.time.replace(/^Connected\s+on\s+/i,""));d&&(u.connectedAt||(u.connectedAt=d),u.connectionDate||(u.connectionDate=d.slice(0,10)),u.lastUpdated=n)}c.name&&!u.name&&(u.name=c.name),c.title&&(u.title=c.title),u.sources||(u.sources=[]),u.sources.includes("sync-connections")||u.sources.push("sync-connections"),u.lastSeen=s,u.seenCount=(u.seenCount||1)+1,u.lastUpdated=n}else{let d={name:c.name,title:c.title,location:null,company:null,connectionDegree:"1st",connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1,firstSeen:s,lastSeen:s,seenCount:1,sources:["sync-connections"],connectionStatus:"connected",connectionDate:s,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n},g=Oe(c.name),y=g?l.get(g)||[]:[];y.length&&(d.possibleDuplicateOf=[...y],r.flaggedDuplicates++,r.flagged.push({name:c.name,candidates:y.length})),o[c.profileUrl]=d,a&&i.set(a,c.profileUrl),r.newPeople++}}return t||ue(o),r}function So(e,t,o,n,s,r){if(console.log(`
|
|
63
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` Sync Connections Summary (${r})`),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"),s&&console.log(` LinkedIn header: ${s.toLocaleString()}`),console.log(` Connections scraped: ${e.length}`),console.log(` New people added: ${o.newPeople}`),console.log(` Updated to connected: ${o.updatedToConnected}`),console.log(` Already connected: ${o.alreadyConnected}`),t.length>0){console.log(`
|
|
64
|
+
Newly accepted (${t.length}):`);for(let i of t)console.log(` \u2713 ${i.name||"Unknown"} (was: ${i.previousStatus})`)}if(o.flaggedDuplicates>0){console.log(`
|
|
65
|
+
\u26A0 Possible duplicates (${o.flaggedDuplicates}) \u2014 new connection shares a name with a still-pending person (likely the same person accepting under a vanity url we couldn't match by slug). Flagged for review, NOT merged:`);for(let i of o.flagged||[])console.log(` ? ${i.name||"Unknown"}${i.candidates>1?` (${i.candidates} candidates)`:""}`)}n&&console.log(`
|
|
66
|
+
[DRY RUN \u2014 nothing written to DB]`),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
|
|
67
|
+
`)}async function wo(){let e=fo();if(await Re(),e.list){po();return}let t=e.full?"full":"incremental",o=be("sync",t);console.log(`
|
|
68
|
+
\u{1F504} Sync LinkedIn Connections (${t})
|
|
69
|
+
`),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let{browser:n,page:s}=await me();try{let r=await mo(s),i=e.full?await ho(s,{max:e.max,verbose:e.verbose,dryRun:e.dryRun}):await go(s,{max:e.max,verbose:e.verbose});console.log(`
|
|
70
|
+
Extracted ${i.length} connections.`);let l=U(),c=yo(i,l),a=Me(i,e.dryRun);So(i,c,a,e.dryRun,r,t),Q(o,"success",{scraped:i.length,newPeople:a.newPeople,updatedToConnected:a.updatedToConnected})}catch(r){console.error(`
|
|
71
|
+
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),Q(o,"error",null,r.message)}finally{await n.close().catch(()=>{})}}process.argv[1]&&import.meta.url===uo(process.argv[1]).href&&wo();export{Le as buildSlugIndex,yo as detectNewlyAccepted,Oe as normName,Me as syncToDatabaseBatch};
|
package/dist/verifyAbout.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
var De=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{for(var o in t)De(e,o,{get:t[o],enumerable:!0})};async function d(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function me(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let n of t){let s=n.innerText||"",m=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),u=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),h=s.includes("Get hired faster")||s.includes("Get hired 2x");if(m||u||h){let D=n.querySelector('button[aria-label="Dismiss"]')||n.querySelector("button.artdeco-modal__dismiss")||n.querySelector("button[data-test-modal-close-btn]");if(D)return D.click(),{dismissed:!0,matched:s.substring(0,80)};let $=n.querySelectorAll("button");for(let l of $){let S=l.innerText?.trim().toLowerCase()||"",f=l.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||f.includes("dismiss"))return l.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let o=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(o){let n=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(n)return n.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var j=de(()=>{});var ye={};Te(ye,{extractCertificationsFromDetails:()=>Ze,extractEducationFromDetails:()=>Qe,extractExperienceFromDetails:()=>Ge,extractFeaturedFromDetails:()=>Ke,extractRecommendationsFromDetails:()=>Xe,extractSkillsFromDetails:()=>ze});async function Ge(e,t){let o=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await d(3e3);let n=e.url();if(/\/(login|authwall|checkpoint)/i.test(n))throw new Error(`Session expired \u2014 bounced to ${n} when fetching /details/experience/`);for(let m=0;m<5;m++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await d(900);await d(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let u of document.querySelectorAll("button"))if(/^Load more$/i.test((u.textContent||"").trim()))return u.click(),!0;return!1});)s++,await d(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await d(700);return await e.evaluate(()=>{let m=document.querySelector("main");if(!m)return[];function u(l){let S=[];for(let f of l.querySelectorAll("div")){let p=Array.from(f.children).filter(x=>x.tagName==="DIV");if(p.length<3)continue;let w=p.filter(x=>(x.textContent||"").trim().length>50);w.length<3||(f.textContent||"").length<500||S.push({el:f,count:w.length,totalText:(f.textContent||"").length})}return S.sort((f,p)=>p.count-f.count||f.totalText-p.totalText),S[0]?.el}let h=u(m);if(!h)return[];let D=Array.from(h.children).filter(l=>l.tagName==="DIV").filter(l=>(l.textContent||"").trim().length>50);function $(l){let S=l[0]||null,f=null,p=null;if(l[1]){let a=l[1].split("\xB7").map(C=>C.trim());f=a[0]||null,a[1]&&(p=a[1])}let w=l.findIndex(a=>/(\d{4}|present)/i.test(a)&&/(-|–|—)/i.test(a)&&a.length<80),x=null,T=null;if(w>=0){let a=l[w].split("\xB7").map(C=>C.trim());x=a[0]||null,a[1]&&(T=a[1])}let L=null,J=-1;if(w>=0&&l[w+1]){let a=l[w+1],C=/^[>*\-•]|^>/.test(a),R=/https?:\/\//.test(a),v=/\d{4}/.test(a),H=/,/.test(a)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(a);!C&&!R&&!v&&a.length<100&&H&&(L=a,J=w+1)}let y=null,q=-1,E=l[l.length-1];if(E&&/and\s+\+\d+\s+skills?$/i.test(E)){q=l.length-1;let a=E.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);a&&(y={listed:a[1].split(",").map(C=>C.trim()),additional:parseInt(a[2],10)})}let M=new Set([0,1,w,J,q].filter(a=>a>=0)),k=l.filter((a,C)=>!M.has(C)),Y=k.length>0?k.join(`
|
|
2
2
|
|
|
3
3
|
`):null;return{title:S,company:f,employmentType:p,dates:x,duration:T,location:L,description:Y,skills:y,_raw:l}}return D.map(l=>{let f=(l.innerText||"").trim().split(`
|
|
4
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return $(f)}).filter(l=>l.title)})}catch(n){if(/session expired|bounced to|authwall|checkpoint/i.test(n.message||""))throw n;return console.error(`extractExperienceFromDetails failed for ${t}: ${n.message?.slice(0,120)}`),[]}}async function
|
|
5
|
-
${
|
|
4
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return $(f)}).filter(l=>l.title)})}catch(n){if(/session expired|bounced to|authwall|checkpoint/i.test(n.message||""))throw n;return console.error(`extractExperienceFromDetails failed for ${t}: ${n.message?.slice(0,120)}`),[]}}async function O(e,t,o){let n=t.replace(/\/+$/,"")+`/details/${o}/`;await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await d(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${o}/`);if(!s.toLowerCase().includes(`/details/${o.toLowerCase()}/`))throw new Error(`Section /details/${o}/ not available on profile (landed on ${s})`);for(let u=0;u<4;u++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await d(700);await d(800);let m=0;for(;m<5&&await e.evaluate(()=>{for(let h of document.querySelectorAll("button"))if(/^Load more$/i.test((h.textContent||"").trim()))return h.click(),!0;return!1});)m++,await d(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await d(600)}async function B(e,t,o,n){try{return await n()}catch(s){let m=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(m))throw s;return/not available on profile/i.test(m)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${o} failed for ${e}: ${m.slice(0,120)}`),[])}}async function Ke(e,t){return B(t,"featured","extractFeaturedFromDetails",async()=>(await O(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${N}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var De=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
42
42
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
43
|
return true;
|
|
44
44
|
});
|
|
45
|
-
})()`)))}async function Qe(e,t){return B(t,"education","extractEducationFromDetails",async()=>(await
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function Qe(e,t){return B(t,"education","extractEducationFromDetails",async()=>(await O(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${N}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var De=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
79
79
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
80
|
return true;
|
|
81
81
|
});
|
|
82
|
-
})()`)))}async function ze(e,t){return B(t,"skills","extractSkillsFromDetails",async()=>(await
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function ze(e,t){return B(t,"skills","extractSkillsFromDetails",async()=>(await O(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${N}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var De=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function Ze(e,t){return B(t,"certifications","extractCertificationsFromDetails",async()=>(await
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function Ze(e,t){return B(t,"certifications","extractCertificationsFromDetails",async()=>(await O(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${N}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var De=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function Xe(e,t){return B(t,"recommendations","extractRecommendationsFromDetails",async()=>(await
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function Xe(e,t){return B(t,"recommendations","extractRecommendationsFromDetails",async()=>(await O(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${N}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var De=Object.defineProperty;var de=(e,t)=>()=>(e&&(t=e(e=0)),t);var Te=(e,t)=>{
|
|
|
172
172
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
|
-
})()`)))}var
|
|
175
|
+
})()`)))}var N,be=de(()=>{j();N=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,7 +235,7 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});import
|
|
238
|
+
`});import Oe from"puppeteer";import{addExtra as Ne}from"puppeteer-extra";import Be from"puppeteer-extra-plugin-stealth";j();import{getPluginConfig as Le}from"@ilivemylife/graph-sdk";var Me=await Le();for(let[e,t]of Object.entries(Me))process.env[e]===void 0&&(process.env[e]=t);var Fe=process.env.LINKEDIN_NAME,F=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),at=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.NEEDS_REVIEW])),qe=Object.freeze(new Set([F.DRAFT,F.CONFIRMED,F.REJECTED,F.NEEDS_REVIEW]));import fe from"fs";import Re from"path";var Pe="cookies.json";function je(){let e=process.env.ILML_SCOPE_DIR;return e?Re.join(e,"plugins-state","linkedin","cookies.json"):Pe}function pe(){let e=je();if(!fe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=fe.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}var he=Ne(Oe);he.use(Be());async function ge(){let e=await he.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
|
|
239
239
|
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let o=await e.newPage();await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let n=pe();await o.setCookie(...n),console.log(" Browser launched, cookies loaded.")}catch(n){console.error(`
|
|
240
240
|
[!] ${n.message}
|
|
241
241
|
`),await e.close(),process.exit(1)}return{browser:e,page:o}}j();import"dotenv/config";import*as g from"fs";import*as b from"path";import{fileURLToPath as He}from"url";var Ve=He(import.meta.url),Ue=b.dirname(b.dirname(Ve)),A=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"collected-profiles"):b.join(Ue,"collected-profiles"),We=b.join(A,"people.json"),Et=b.join(A,"jobs.json"),At=b.join(A,"quota.json"),$t=b.join(A,"conversations.json"),It=b.join(A,"sync-state.json"),Dt=b.join(A,"application-questions.json"),Tt=b.join(A,"profile-history"),we=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},Lt=we(process.env.CONNECT_MAX_DAILY,20),Mt=we(process.env.CONNECT_MAX_WEEKLY,100),W=null;function Je(){g.existsSync(A)||g.mkdirSync(A,{recursive:!0})}function Ye(e,t){if(!g.existsSync(e))return null;try{let o=JSON.parse(g.readFileSync(e,"utf-8"));try{g.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${b.resolve(e)}`);let n=e+".backup";if(g.existsSync(n))try{let s=JSON.parse(g.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{g.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{g.copyFileSync(e,e+".corrupted")}catch{}return null}}function Q(){return W||(Je(),W=Ye(We,"people.json")||{},W)}async function et(e,t){let o=e.url();if(o.includes("/in/"))return!1;if(o.includes("/login")||o.includes("/authwall")||o.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await d(3e3);let n=e.url();return n.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${n.slice(0,80)}`),!0}async function Se(e,t,o={}){let{extractExperience:n=!1,extractFeatured:s=!1,extractEducation:m=!1,extractSkills:u=!1,extractRecommendations:h=!1,extractCertifications:D=!1}=o;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await d(3e3),await me(e)&&(console.log(" Dismissed Premium overlay"),await d(1500),await et(e,t));let l=0;for(let y=0;y<2;y++){let q=await e.evaluate(()=>document.body.scrollHeight);for(let M=1;M<=6;M++)await e.evaluate(k=>window.scrollTo(0,k),q*M/6),await d(900);let E=await e.evaluate(()=>document.body.scrollHeight);if(E===l)break;l=E}await d(800);let S=await e.evaluate(()=>{let y=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),q=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"]),E=i=>{let r=(i||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(r)},M={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:[]},k=document.querySelector("main");if(!k)return M;let Y=[...Array.from(k.querySelectorAll("h1")),...Array.from(k.querySelectorAll("h2"))],a=Array.from(k.querySelectorAll("h2")),C=Y.find(i=>{let r=i.textContent&&i.textContent.trim(),c=(r||"").replace(/\s*\(\d+\)$/,"").trim();return r&&r.length>1&&r.length<100&&!y.has(c)&&!q.has(c)}),R=C?C.textContent.trim():null,v=C?C.parentElement:null;for(;v&&v!==k&&!Array.from(v.children).filter(r=>r.tagName==="P").some(r=>{let c=r.textContent&&r.textContent.trim();return c&&c.length>5&&!E(c)});)v=v.parentElement;let H=null,Z=null,X=null,G=null;if(v&&v!==k){let i=Array.from(v.children).filter(c=>c.tagName==="P").filter(c=>{let I=c.textContent&&c.textContent.trim();return I&&I.length>5&&!E(I)});if(i[0]&&(H=i[0].textContent.trim()),i[1]){let c=i[1].textContent.trim().split(/\s*[·•]\s*/);Z=c[0]||null,c.length>1&&(X=c.slice(1).join(" \xB7 "))}let r=Array.from(v.children).filter(c=>c.tagName==="DIV");for(let c=r.length-1;c>=0;c--){let I=r[c].textContent&&r[c].textContent.trim();if(I&&!(R&&I.startsWith(R))&&(G=I.split(/[·•]/)[0].trim(),G))break}}let ee=null;if(v){let i=v.querySelectorAll("p, span, div");for(let r of i){let c=(r.textContent||"").trim().replace(/^[·•]\s*/,"");if(c==="1st"||c==="2nd"||c==="3rd"){ee=c;break}}}let ve=!!k.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),te=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),xe=te&&te.src||null,V=k.textContent||"",ne=null,oe=V.match(/(\d+\+?)\s+connections\b/i);oe&&(ne=oe[1]+" connections");let U=null,ie=V.match(/(\d+)\s+mutual connection/i),se=V.match(/and\s+(\d+)\s+other mutual/i),_e=V.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ie?U=parseInt(ie[1],10):se?U=2+parseInt(se[1],10):_e&&(U=2);let re=null,le=null,ae=a.find(i=>i.textContent&&i.textContent.trim()==="About");if(ae){let i=ae.parentElement;for(;i&&i.tagName!=="SECTION";)i=i.parentElement;if(i){let r=(i.textContent||"").trim();r=r.replace(/^About\s*/,"").trim();let c=r.match(/Top skills\s*(.+?)$/i);if(c){let K=c[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ie=>Ie.trim()).filter(Boolean);K.length>0&&K.length<10&&(le=K)}r=r.split(/\n?…\s*more/i)[0].trim(),r=r.split(/\n?\.\.\.\s*more/i)[0].trim(),r=r.split(/\bTop skills\b/i)[0].trim(),r=r.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),re=r||null}}let ce=null,ue=a.find(i=>i.textContent&&i.textContent.trim()==="Activity");if(ue){let i=ue.parentElement;for(;i&&i.tagName!=="SECTION";)i=i.parentElement;if(i){let r=(i.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);r&&(ce=parseInt(r[1].replace(/,/g,""),10))}}let Ee=[...new Set(a.map(i=>(i.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(i=>i&&i.length>1&&i.length<60&&i!==R).filter(i=>y.has(i)))],P=document.body.textContent||"",Ae=/#OpenToWork\b/i.test(P)||/\bOpen to work\b/.test(P),$e=/#Hiring\b/i.test(P)||/\bI'?m hiring\b/i.test(P)||/\bWe are hiring\b/i.test(P);return{name:R,title:H,location:G,currentCompany:Z,currentSchool:X,connectionDegree:ee,hasVerifiedBadge:ve,photoUrl:xe,connectionsLevel:ne,mutualConnectionsCount:U,followers:ce,openToWork:Ae,hiring:$e,about:re,topSkills:le,availableSections:Ee}});console.log(`Viewed: ${S.name} - ${S.title}`);let f=null,p=null,w=null,x=null,T=null,L=null;if(n||s||m||u||h||D){let y=await Promise.resolve().then(()=>(be(),ye));n&&(f=await y.extractExperienceFromDetails(e,t),console.log(` + Experience: ${f.length} entries`)),s&&(p=await y.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),m&&(w=await y.extractEducationFromDetails(e,t),console.log(` + Education: ${w.length} entries`)),u&&(x=await y.extractSkillsFromDetails(e,t),console.log(` + Skills: ${x.length} entries`)),h&&(T=await y.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${T.length} entries`)),D&&(L=await y.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${L.length} entries`))}return{...S,profileUrl:t,...f!==null&&{experience:f},...p!==null&&{featured:p},...w!==null&&{education:w},...x!==null&&{skillsFull:x},...T!==null&&{recommendations:T},...L!==null&&{certifications:L}}}catch($){console.error(`Error viewing profile ${t}:`,$.message);try{await e.goto("about:blank",{timeout:1e4}),await d(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}j();var z=process.argv.slice(2),Ce=z.filter(e=>e.startsWith("http")),ke=parseInt(z.find(e=>e.startsWith("--pick="))?.split("=")[1]||"0"),tt=z.includes("--has-about");function nt(e,t){return[...e].sort(()=>Math.random()-.5).slice(0,t)}function ot(){if(Ce.length>0)return Ce.map(t=>({url:t,name:"(arg)"}));if(ke>0){let t=Q(),o=Object.entries(t).filter(([n])=>n.startsWith("http")).filter(([,n])=>tt?!!(n.about&&n.about.trim()):!n.about);return nt(o,ke).map(([n,s])=>({url:n,name:s.name}))}let e=process.env.MY_LINKEDIN_URL;return e||(console.error("Pass a URL, use --pick=N, or set MY_LINKEDIN_URL in .env"),process.exit(1)),[{url:e,name:"(self)"}]}function _(e,t,o=80){if(t==null){console.log(` ${e.padEnd(20)} (null)`);return}let n=String(t),s=n.length>o?n.slice(0,o)+`\u2026 (+${n.length-o} chars)`:n;console.log(` ${e.padEnd(20)} ${s} [len=${n.length}]`)}async function it(){let e=ot();console.log(`
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.16.0";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
|