ilml-plugin-linkedin 1.3.1 → 1.5.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 +17 -0
- package/dist/applyQueue.mjs +3 -3
- package/dist/daily.mjs +8 -8
- package/dist/funnelRunner.mjs +10 -10
- package/dist/messageBot.mjs +1 -1
- package/dist/run.mjs +38 -36
- package/dist/scout.mjs +1 -1
- package/dist/syncAll.mjs +1 -1
- package/dist/viewers.mjs +1 -1
- package/dist/visit.mjs +1 -1
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/funnelRunner.mjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var Nt=Object.defineProperty;var Je=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ve=(e,t)=>{for(var o in t)Nt(e,o,{get:t[o],enumerable:!0})};var dt={};Ve(dt,{addEncounter:()=>
|
|
1
|
+
var Nt=Object.defineProperty;var Je=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ve=(e,t)=>{for(var o in t)Nt(e,o,{get:t[o],enumerable:!0})};var dt={};Ve(dt,{addEncounter:()=>pe,canSendConnection:()=>Se,commitDataSnapshot:()=>ut,default:()=>oo,getAllApplications:()=>lt,getPersonStatus:()=>me,getQuestionStats:()=>at,getQuotaStatus:()=>ee,getRecentConnections:()=>ye,linkPersonToJob:()=>ot,loadApplicationQuestions:()=>Me,loadConversations:()=>Ze,loadJobs:()=>de,loadPeople:()=>R,loadQuota:()=>he,loadSyncState:()=>st,logApplicationQuestions:()=>ct,migrateFromDailyFiles:()=>nt,recordConnectionSent:()=>we,resetCaches:()=>Xt,saveConversations:()=>et,saveJobs:()=>fe,savePeople:()=>J,saveQuota:()=>Oe,saveSyncState:()=>rt,updateConnectionStatus:()=>ge,upsertJob:()=>tt,upsertPerson:()=>Ae});import"dotenv/config";import*as v from"fs";import*as k from"path";import{fileURLToPath as Qt}from"url";import{execSync as xe}from"child_process";function Xt(){H=null,G=null,F=null,U=null,z=null,q=null}function _(){v.existsSync(D)||v.mkdirSync(D,{recursive:!0})}function B(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";v.writeFileSync(r,o);for(let s=0;s<3;s++)try{v.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function Z(e,t){if(!v.existsSync(e))return null;try{let o=JSON.parse(v.readFileSync(e,"utf-8"));try{v.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${k.resolve(e)}`);let r=e+".backup";if(v.existsSync(r))try{let s=JSON.parse(v.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{v.copyFileSync(r,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{v.copyFileSync(e,e+".corrupted")}catch{}return null}}function Q(){return new Date().toISOString().split("T")[0]}function R(){return H||(_(),H=Z(De,"people.json")||{},H)}function J(e){_(),H=e;try{B(De,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${k.resolve(De)}`)}}function de(){return G||(_(),G=Z(_e,"jobs.json")||{},G)}function fe(e){_(),G=e;try{B(_e,e)}catch(t){console.error(`[!] Failed to save jobs.json: ${t.message}`),console.error(` Path: ${k.resolve(_e)}`)}}function Ze(){return U||(_(),U=Z(ue,"conversations.json")||{},Zt(U),U)}function Zt(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let s=(o.messages||[]).find(i=>i.status==="draft");s&&o.draftStatus&&o.draftStatus!=="pending"&&(s.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{B(ue,e)}catch{}}}function et(e){_(),U=e;try{B(ue,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${k.resolve(ue)}`)}}function Ae(e,t={}){if(!e)return null;let o=R(),r=Q(),s=new Date().toISOString(),i=o[e];if(i){i.seenCount=(i.seenCount||1)+1,i.lastSeen=r,i.lastUpdated=s,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of Ee)t[l]!=null&&(i[l]=t[l])}else o[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,firstSeen:r,lastSeen:r,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s};return J(o),o[e]}function tt(e,t={}){if(!e)return null;let o=de(),r=Q(),s=o[e];if(s){let i=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let l of i)t[l]!=null&&(s[l]=t[l])}else o[e]={title:t.title||null,company:t.company||null,location:t.location||null,salary:t.salary||null,url:t.url||null,applied:t.applied||!1,appliedDate:t.appliedDate||r,recruiterUrl:t.recruiterUrl||null,firstSeen:r};return fe(o),o[e]}function ot(e,t){if(!e||!t)return;let o=R(),r=o[e];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t)||(r.jobIds.push(t),r.lastUpdated=new Date().toISOString(),J(o)))}function pe(e,t){if(!e||!t)return;let o=R(),r=o[e];if(!r)return;r.encounters||(r.encounters=[]);let i={date:Q(),source:t.source||"unknown",action:t.action||"unknown"};t.jobId&&(i.jobId=String(t.jobId)),t.jobTitle&&(i.jobTitle=t.jobTitle),t.jobCompany&&(i.jobCompany=t.jobCompany),!r.encounters.some(u=>u.date===i.date&&u.source===i.source&&u.action===i.action&&(u.jobId||"")===(i.jobId||""))&&(r.encounters.push(i),r.lastUpdated=new Date().toISOString(),J(o))}function me(e){return e&&R()[e]?.connectionStatus||null}function ge(e,t,o={}){if(!e)return;let r=R(),s=r[e];if(s||(Ae(e,o.profileInfo||{}),s=r[e]),!!s){if(s.connectionStatus=t,s.connectionDate=Q(),s.connectionMethod=o.method||s.connectionMethod,s.messageSent=o.messageSent||s.messageSent,s.lastUpdated=new Date().toISOString(),o.profileInfo)for(let i of Ee)o.profileInfo[i]!=null&&(s[i]=o.profileInfo[i]);J(r)}}function he(){return F||(_(),F=Z(Ke,"quota.json"),(!F||!F.connections)&&(F={connections:[]}),F)}function Oe(e){_(),F=e;try{B(Ke,e)}catch(t){console.error(`[!] Failed to save quota.json: ${t.message}`)}}function we(e,t="unknown"){let o=he(),r=new Date;o.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:e,source:t}),Oe(o)}function ye(){let e=he(),t=new Date;t.setDate(t.getDate()-7);let o=t.toISOString().split("T")[0];return e.connections.filter(r=>r.date>=o)}function Se(){let e=ye(),t=Q(),o=e.filter(n=>n.date===t).length,r=e.length,s=o>=K,i=r>=X,l=!s&&!i,u={allowed:l,daily:{sent:o,max:K},weekly:{sent:r,max:X}};return l||(u.reason=s?`Daily limit reached (${o}/${K})`:`Weekly limit reached (${r}/${X})`),u}function ee(){let e=ye(),t=Q(),o=e.filter(s=>s.date===t).length,r=e.length;return{daily:{sent:o,max:K,remaining:K-o},weekly:{sent:r,max:X,remaining:X-r}}}function eo(e){if(!e)return null;let t=e.match(/jobs\/view\/(\d+)/);return t?t[1]:null}function nt(){_();let e=v.readdirSync(D).filter(i=>i.endsWith(".json")&&i!=="people.json"&&i!=="jobs.json"&&i!=="quota.json");if(e.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
2
2
|
Migrating from ${e.length} daily files...
|
|
3
|
-
`);let t=
|
|
4
|
-
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${s} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function st(){return z||(_(),z=Z(Xe,"sync-state.json")||{},z)}function rt(e){_(),z=e;try{B(Xe,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Me(){if(q)return q;_();try{v.existsSync(je)&&(q=JSON.parse(v.readFileSync(je,"utf-8")))}catch{}return q||(q={}),q}function it(e){return Array.isArray(e.applications)}function lt(){let e=Me();if(it(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function ct(e){if(!e||!e.questions||e.questions.length===0)return;let t=Me(),o=e.jobId||"unknown",s={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let l={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=to?l.options=i.options:l.optionsOmitted=!0),i.page&&(l.page=i.page),i.wasPreFilled&&(l.wasPreFilled=!0),i.wasRetry&&(l.wasRetry=!0),l})};it(t)?(s.jobId=o,s.jobTitle=e.jobTitle||null,s.jobCompany=e.jobCompany||null,s.jobUrl=e.jobUrl||null,t.applications.push(s)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(s));try{B(je,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function at(){let e=lt(),t=new Map;for(let i of e)for(let l of i.questions||[]){let u=l.question.toLowerCase().trim();if(!u)continue;t.has(u)||t.set(u,{question:l.question,count:0,answers:new Map});let n=t.get(u);n.count++;let c=(l.answer||"").trim();n.answers.set(c,(n.answers.get(c)||0)+1)}let o=[...t.values()].sort((i,l)=>l.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((l,u)=>u[1]-l[1])[0]?.[0]||""})),s=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((l,u)=>u[1]-l[1]).map(([l,u])=>`${l} (${u}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:s}}function ut(e){if(v.existsSync(k.join(D,".git")))try{let t={cwd:D,stdio:"pipe",timeout:1e4};xe("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{xe("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');xe(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Yt,Kt,D,De,_e,Ke,ue,Xe,je,K,X,H,G,F,U,z,q,Ee,to,oo,Fe=Je(()=>{Yt=Qt(import.meta.url),Kt=k.dirname(k.dirname(Yt)),D=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"collected-profiles"):k.join(Kt,"collected-profiles"),De=k.join(D,"people.json"),_e=k.join(D,"jobs.json"),Ke=k.join(D,"quota.json"),ue=k.join(D,"conversations.json"),Xe=k.join(D,"sync-state.json"),je=k.join(D,"application-questions.json"),K=20,X=100,H=null,G=null,F=null,U=null,z=null,q=null;Ee=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];to=50;oo={loadPeople:
|
|
3
|
+
`);let t=R(),o=de(),r=0,s=0;e.sort();for(let i of e){let l=k.join(D,i),u;try{u=JSON.parse(v.readFileSync(l,"utf-8"))}catch(a){console.log(` Skipping ${i}: ${a.message}`);continue}let n=u.date||i.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,c=u.source||i.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!u.profiles||!Array.isArray(u.profiles)){console.log(` Skipping ${i}: no profiles array`);continue}console.log(` ${i}: ${u.profiles.length} profiles`);for(let a of u.profiles){let f=a.profileUrl;if(!f)continue;let d=t[f];if(d){d.seenCount=(d.seenCount||1)+1,n&&(!d.lastSeen||n>d.lastSeen)&&(d.lastSeen=n),n&&(!d.firstSeen||n<d.firstSeen)&&(d.firstSeen=n),c&&!d.sources?.includes(c)&&(d.sources=d.sources||[],d.sources.push(c));for(let p of Ee)a[p]!=null&&(d[p]=a[p]);a.status&&a.processed&&(d.connectionStatus=a.status,d.connectionDate=n,a.funnelResult&&(d.connectionMethod=a.funnelResult.method||d.connectionMethod,d.messageSent=a.funnelResult.message||d.messageSent)),d.lastUpdated=new Date().toISOString()}else t[f]={name:a.name||null,title:a.title||null,location:a.location||null,company:a.company||null,connectionDegree:a.connectionDegree||null,connectionsCount:a.connectionsCount||null,mutualConnections:a.mutualConnections||null,photoUrl:a.photoUrl||null,hasVerifiedBadge:a.hasVerifiedBadge||!1,firstSeen:n,lastSeen:n,seenCount:1,sources:c?[c]:[],connectionStatus:a.processed&&a.status||null,connectionDate:a.processed?n:null,connectionMethod:a.funnelResult?.method||null,messageSent:a.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(a.fromJob?.url){let p=eo(a.fromJob.url);p&&(t[f].jobIds||(t[f].jobIds=[]),t[f].jobIds.includes(p)||t[f].jobIds.push(p),o[p]?o[p].recruiterUrl||(o[p].recruiterUrl=f):(o[p]={title:a.fromJob.title||null,company:a.fromJob.company||null,location:null,salary:null,url:a.fromJob.url,applied:!0,appliedDate:n,recruiterUrl:f,firstSeen:n},s++))}}}return J(t),fe(o),console.log(`
|
|
4
|
+
Migration complete!`),console.log(` People: ${Object.keys(t).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(o).length} total (${s} new)`),{people:Object.keys(t).length,jobs:Object.keys(o).length}}function st(){return z||(_(),z=Z(Xe,"sync-state.json")||{},z)}function rt(e){_(),z=e;try{B(Xe,e)}catch(t){console.error(`[!] Failed to save sync-state.json: ${t.message}`)}}function Me(){if(q)return q;_();try{v.existsSync(je)&&(q=JSON.parse(v.readFileSync(je,"utf-8")))}catch{}return q||(q={}),q}function it(e){return Array.isArray(e.applications)}function lt(){let e=Me();if(it(e))return e.applications;let t=[];for(let o of Object.values(e))o.applications&&t.push(...o.applications);return t}function ct(e){if(!e||!e.questions||e.questions.length===0)return;let t=Me(),o=e.jobId||"unknown",s={applicationId:`${o}_${Date.now()}`,date:new Date().toISOString(),result:e.result||"submitted",formPages:e.formPages||null,duration:e.duration||null,retries:e.retries||0,failedField:e.failedField||null,questionCount:e.questions.length,questions:e.questions.map(i=>{let l={type:i.type||"input",question:i.labelText||i.question||"",answer:i.answer||""};return i.options&&(i.options.length<=to?l.options=i.options:l.optionsOmitted=!0),i.page&&(l.page=i.page),i.wasPreFilled&&(l.wasPreFilled=!0),i.wasRetry&&(l.wasRetry=!0),typeof i.isRequired=="boolean"&&(l.isRequired=i.isRequired),i.wasOptional&&(l.wasOptional=!0),l})};it(t)?(s.jobId=o,s.jobTitle=e.jobTitle||null,s.jobCompany=e.jobCompany||null,s.jobUrl=e.jobUrl||null,t.applications.push(s)):(t[o]||(t[o]={applications:[]}),t[o].applications.push(s));try{B(je,t)}catch(i){console.error(`[!] Failed to save application-questions.json: ${i.message}`)}}function at(){let e=lt(),t=new Map;for(let i of e)for(let l of i.questions||[]){let u=l.question.toLowerCase().trim();if(!u)continue;t.has(u)||t.set(u,{question:l.question,count:0,answers:new Map});let n=t.get(u);n.count++;let c=(l.answer||"").trim();n.answers.set(c,(n.answers.get(c)||0)+1)}let o=[...t.values()].sort((i,l)=>l.count-i.count),r=o.slice(0,15).map(i=>({question:i.question,count:i.count,topAnswer:[...i.answers.entries()].sort((l,u)=>u[1]-l[1])[0]?.[0]||""})),s=o.filter(i=>i.answers.size>1&&i.count>=3).map(i=>({question:i.question,count:i.count,answers:[...i.answers.entries()].sort((l,u)=>u[1]-l[1]).map(([l,u])=>`${l} (${u}x)`)}));return{totalApplications:e.length,uniqueQuestions:t.size,topQuestions:r,inconsistent:s}}function ut(e){if(v.existsSync(k.join(D,".git")))try{let t={cwd:D,stdio:"pipe",timeout:1e4};xe("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",t);try{xe("git diff --cached --quiet",t);return}catch{}let o=(e||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');xe(`git commit -m "${o}"`,t)}catch(t){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${t.message?.slice(0,80)}`)}}var Yt,Kt,D,De,_e,Ke,ue,Xe,je,K,X,H,G,F,U,z,q,Ee,to,oo,Fe=Je(()=>{Yt=Qt(import.meta.url),Kt=k.dirname(k.dirname(Yt)),D=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"collected-profiles"):k.join(Kt,"collected-profiles"),De=k.join(D,"people.json"),_e=k.join(D,"jobs.json"),Ke=k.join(D,"quota.json"),ue=k.join(D,"conversations.json"),Xe=k.join(D,"sync-state.json"),je=k.join(D,"application-questions.json"),K=20,X=100,H=null,G=null,F=null,U=null,z=null,q=null;Ee=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];to=50;oo={loadPeople:R,savePeople:J,loadJobs:de,saveJobs:fe,loadConversations:Ze,saveConversations:et,upsertPerson:Ae,upsertJob:tt,linkPersonToJob:ot,addEncounter:pe,getPersonStatus:me,updateConnectionStatus:ge,migrateFromDailyFiles:nt,loadQuota:he,saveQuota:Oe,recordConnectionSent:we,canSendConnection:Se,getRecentConnections:ye,getQuotaStatus:ee,loadSyncState:st,saveSyncState:rt,commitDataSnapshot:ut,logApplicationQuestions:ct,getQuestionStats:at}});var xt={};Ve(xt,{getJobDecision:()=>So,getLastVisit:()=>ko,getScoutStats:()=>$o,loadCompanies:()=>It,loadDiscoveredPeople:()=>Ne,loadJobDecisions:()=>Le,loadScoutedJobs:()=>Re,loadVisitLog:()=>be,recordVisit:()=>vo,resetCaches:()=>ho,saveCompany:()=>Co,saveDiscoveredPerson:()=>bo,saveScoutedJob:()=>wo,setJobDecision:()=>yo});import"dotenv/config";import*as O from"fs";import*as j from"path";import{fileURLToPath as po}from"url";function le(){O.existsSync(W)||O.mkdirSync(W,{recursive:!0})}function ce(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";O.writeFileSync(r,o);for(let s=0;s<3;s++)try{O.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function ae(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function ho(){ne=null,se=null,re=null,ie=null,V=null}function Re(){return ne||(ne=ae(bt)||{},ne)}function wo(e,t){if(!e)return;le();let o=Re(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[s,i]of Object.entries(t))i!=null&&(o[e][s]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{ce(bt,o)}catch(s){console.error(`[!] Failed to save scouted-jobs.json: ${s.message}`)}}function Le(){return se||(se=ae($t)||{},se)}function yo(e,t,o={}){if(!e||!t)return;le();let r=Le(),s=new Date().toISOString().slice(0,10);r[e]?(r[e].status=t,r[e].updatedAt=s,o.reason&&(r[e].reason=o.reason),o.score!=null&&(r[e].score=o.score),o.source&&(r[e].source=o.source)):r[e]={status:t,decidedAt:s,updatedAt:s,reason:o.reason||null,score:o.score??null,source:o.source||null};try{ce($t,r)}catch(i){console.error(`[!] Failed to save job-decisions.json: ${i.message}`)}}function So(e){return Le()[e]||null}function Ne(){return re||(re=ae(Ct)||{},re)}function bo(e,t){if(!e)return;le();let o=Ne(),r=new Date().toISOString().slice(0,10);if(o[e]){let s=o[e];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[e]={name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{ce(Ct,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}function It(){return ie||(ie=ae(kt)||{},ie)}function Co(e,t){if(!e)return;le();let o=It(),r=new Date().toISOString().slice(0,10);if(o[e]){let s=o[e];t.name&&(s.name=t.name),t.about&&(s.about=t.about),t.size&&(s.size=t.size),t.industries&&(s.industries=t.industries),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),t.recruiterUrl&&(s.recruiterUrls||(s.recruiterUrls=[]),s.recruiterUrls.includes(t.recruiterUrl)||s.recruiterUrls.push(t.recruiterUrl)),s.lastSeen=r,s.jobCount=s.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{ce(kt,o)}catch(s){console.error(`[!] Failed to save companies.json: ${s.message}`)}}function be(){return V||(V=ae(vt)||{visits:[]},Array.isArray(V.visits)||(V.visits=[]),V)}function vo(e,t={}){if(!e)return;le();let o=be();o.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let r=Date.now()-90*24*60*60*1e3;o.visits=o.visits.filter(s=>new Date(s.date).getTime()>r);try{ce(vt,o)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function ko(e){let t=be();for(let o=t.visits.length-1;o>=0;o--)if(t.visits[o].profileUrl===e)return t.visits[o].date;return null}function $o(){let e=Re(),t=Ne(),o=Object.values(e),r=Object.values(t),s={};for(let d of o)d.company&&(s[d.company]=(s[d.company]||0)+1);let i=Object.entries(s).sort((d,p)=>p[1]-d[1]).slice(0,5).map(([d,p])=>`${d} (${p})`),l={};for(let d of o)for(let p of d.techStack||[])l[p]=(l[p]||0)+1;let u=Object.entries(l).sort((d,p)=>p[1]-d[1]).slice(0,8).map(([d,p])=>`${d} (${p})`),n=be(),c=new Date().toISOString().slice(0,10),a=n.visits.filter(d=>d.date.startsWith(c)).length,f=new Set(n.visits.map(d=>d.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:u,totalVisited:f,todayVisited:a,lastScoutDate:o.length>0?o.sort((d,p)=>(p.scoutedAt||"").localeCompare(d.scoutedAt||""))[0]?.scoutedAt:null}}var mo,go,W,bt,Ct,vt,kt,$t,ne,se,re,ie,V,Dt=Je(()=>{mo=po(import.meta.url),go=j.dirname(j.dirname(mo)),W=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"market-research"):j.join(go,"market-research"),bt=j.join(W,"scouted-jobs.json"),Ct=j.join(W,"discovered-people.json"),vt=j.join(W,"visit-log.json"),kt=j.join(W,"companies.json"),$t=j.join(W,"job-decisions.json");ne=null;se=null;re=null;ie=null;V=null});import Mo from"puppeteer";import"dotenv/config";import*as A from"fs";import*as P from"path";import{fileURLToPath as Wt}from"url";import"dotenv/config";import{createGraphClient as qt,resolveToken as Ut}from"@ilivemylife/graph-sdk";import{config as Bt}from"dotenv";Bt();var We=Ut()||process.env.TOKEN;We||(console.error(`
|
|
5
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
6
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
7
7
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
8
8
|
`),process.exit(1));var He=qt({token:We});function Jt(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),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function Vt({scriptName:e,mode:t,status:o,error:r,duration:s}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),u=s?` ${Jt(s)}`:"",n=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",c=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${c} \u2014 ${n} \u2014 ${l}${u}`}async function Ge({scriptName:e,mode:t,status:o,summaryLines:r,error:s,duration:i}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(r)||r.length===0)return;let n=`**${Vt({scriptName:e,mode:t,status:o,error:s,duration:i})}**
|
|
9
9
|
|
|
10
10
|
${r.join(`
|
|
11
|
-
`)}`;try{await He.addMessage(l,n)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Ht=Wt(import.meta.url),Gt=P.dirname(P.dirname(Ht)),ke=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(Gt,"collected-profiles"),$e=P.join(ke,"run-log.json");function zt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";A.writeFileSync(r,o);for(let s=0;s<3;s++)try{A.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function ze(){try{if(!A.existsSync($e))return{runs:[]};let e=JSON.parse(A.readFileSync($e,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Qe(e){A.existsSync(ke)||A.mkdirSync(ke,{recursive:!0});try{zt($e,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ye(e,t="default"){let o=ze();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,s={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>i),Qe(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Ie(e,t,o=null,r=null){if(!e)return;let s=null;try{let l=ze(),u=l.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=o,u.error=r,s=u.duration;else{let n=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());n&&(n.status=t,n.result=t,n.duration=Date.now()-e.startTime,n.stats=o,n.error=r,s=n.duration)}Qe(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Ge({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:r,duration:s??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function N(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let s=r.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),u=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||l||u){let n=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:s.substring(0,80)};let c=r.querySelectorAll("button");for(let a of c){let f=a.innerText?.trim().toLowerCase()||"",d=a.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return a.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 r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}Fe();async function ft(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 g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function no(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function so(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(2e3+Math.random()*2e3),await N(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await ft(e,t));let r=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim()||null,i=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,u=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,c=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,m=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,y=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),w=y?parseInt(y[1],10):null,b=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,C=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:s,title:i,location:l,about:u,company:c,connectionDegree:f,connectionsCount:m,mutualConnections:w,photoUrl:b,hasVerifiedBadge:C}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}return null}}async function te(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(n=>n.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!s,hasConnectBtn:!!i};return o.length>0?{status:"pending",debug:l}:s&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Te(e){let t=null,o=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(n=c.textContent?.trim(),n&&!n.includes("notification")))return n;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let n=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),t=await e.evaluateHandle(a=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=a.toLowerCase().split(" ")[0],m=null,h=null;for(let p of f){let y=p.getBoundingClientRect();if(y.width===0||y.height===0)continue;if((p.getAttribute("aria-label")||"").toLowerCase().includes(d)){m=p;break}h||(h=p)}return m||h||null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let n=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let c=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 y=p.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y)}).map(p=>p.getAttribute("aria-label")?.slice(0,50))},n);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),m=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of d){let p=h.getAttribute("aria-label")||"";if((p.toLowerCase().includes("invite")||p.toLowerCase().includes("connect"))&&m.test(p))return h}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping primary button: wrong person (${n})`),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 r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let s=o?o.split(" ")[0].toLowerCase():"",i=null;for(let n of r){let c=await e.evaluate((a,f)=>{let d=a.className.includes("muted"),m=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,p=(a.getAttribute("aria-label")||"").toLowerCase(),y=p.includes("invite"),w=f?p.includes(f):!0;return{isMuted:d,isStickyHeader:m,inRecommendations:h,hasInvite:y,matchesName:w,ariaLabel:p}},n,s);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=n;break}}for(let n of r)n!==i&&await n.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let n of u){let c=await e.evaluate(a=>{let f=a.getBoundingClientRect(),d=f.width>0&&f.height>0,m=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:m,top:f.top}},n);if(c.isVisible&&!c.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of u)n!==l&&await n.dispose().catch(()=>{});if(!l&&u.length>0&&(l=u[u.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let n=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(d=>{let m=d.innerText?.trim(),h=d.getAttribute("aria-label")||"",p=d.getBoundingClientRect();return p.top<100||p.top>600||p.width===0?!1:m==="Follow"||m==="Message"||m==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let f=a.parentElement;for(let d=0;d<8&&f;d++){for(let m of f.querySelectorAll("button"))if(m.innerText?.trim()==="More"&&m!==a)return m;f=f.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(a=>a.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let a=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 h of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});c=a?.asElement?.()||null,c||await a?.dispose?.().catch(()=>{})}if(!c){let a=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let m of f)for(let h of m.querySelectorAll('[role="menuitem"], a, div')){let p=h.innerText?.trim();p&&p.length<40&&d.push(p)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping generic button: wrong person (${n})`),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 ro(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV";if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(a=>a.click(),t)]),await g(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 g(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await g(3e3)):(await e.evaluate(c=>c.click(),t),await g(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 u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function io(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 g(1500);let o=await Te(e);if(o){await e.evaluate(s=>s.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function lo(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:u=[]}=o,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
12
|
-
--- Connecting: ${c} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await N(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await ft(e,t),await g(2e3)),n.profileInfo=await e.evaluate(()=>{let w=document.querySelector("h1")?.textContent?.trim()||null,S=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,b=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,$=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,R=document.querySelector(".dist-value")?.textContent?.trim()||null,Tt=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Be=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),Pt=Be?parseInt(Be[1],10):null,Lt=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,Rt=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:w,title:S,location:b,company:$,connectionDegree:R,connectionsCount:Tt,mutualConnections:Pt,photoUrl:Lt,hasVerifiedBadge:Rt}}),u.length>0&&no(n.profileInfo?.location,u))return console.log(` \u26A0 Excluded location: ${n.profileInfo.location}`),n.reason="excluded_location",n;let f=await te(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await N(e);let d=await Te(e);if(!d&&(await N(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),d=await Te(e)),!d))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=d.method,await ro(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let w=await te(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await N(e),await g(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),S),await g(500),await S.click().catch(()=>e.evaluate(C=>C.click(),S)),await g(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),b),await g(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),n.reason="premium_required",n;if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),n.reason="premium_required",n}catch(b){return console.log(" More dropdown failed:",b.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}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 g(500),n.reason="email_required",n}let p=await e.$('button[aria-label="Add a note"]'),y=await e.$('button[aria-label="Send without a note"]');if(!p&&!y){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let b=S.querySelector('button[aria-label="Add a note"]'),C=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!C}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));p=S?.asElement?.()||null,p||await S.dispose().catch(()=>{})}if(w.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));y=S?.asElement?.()||null,y||await S.dispose().catch(()=>{})}}if(s){if(p&&r){if(console.log(" Adding personalized note..."),await p.click(),await g(1500),await e.$("div.modal-upsell")){let b=await io(e);return n.success=b,n.connectionSent=b,n.reason=b?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=r.replace("{name}",b);await S.type(C,{delay:20}),await g(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(M=>M.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=C,n}}}else if(y){console.log(" Sending without note...");try{await y.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(p&&!r){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(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let w=y;if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}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 g(4e3)),await N(e),await g(500);let S=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let C of S){let $=await e.evaluate(M=>{let R=M.getBoundingClientRect();return{visible:R.width>0&&R.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){b=C;break}}!b&&S.length>0&&(b=S[S.length-1]);for(let C of S)C!==b&&await C.dispose().catch(()=>{});if(b)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),b),await g(500),await b.click().catch(()=>e.evaluate($=>$.click(),b)),await g(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(Y=>Y.click(),C),await g(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let R=await e.$('button[aria-label="Send without a note"]');if(R){console.log(" Modal appeared via More dropdown, sending without note...");try{await R.evaluate(Y=>Y.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(c){console.error(` \u2717 Error: ${c.message}`),n.reason="error",n.error=c.message;let a=c.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{n.fatal=!0}return n}}async function mt(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:n=null,excludeLocations:c=[],source:a="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
13
|
-
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let
|
|
11
|
+
`)}`;try{await He.addMessage(l,n)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Ht=Wt(import.meta.url),Gt=P.dirname(P.dirname(Ht)),ke=process.env.DATA_DIR?P.resolve(process.env.DATA_DIR,"collected-profiles"):P.join(Gt,"collected-profiles"),$e=P.join(ke,"run-log.json");function zt(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";A.writeFileSync(r,o);for(let s=0;s<3;s++)try{A.renameSync(r,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw i}}function ze(){try{if(!A.existsSync($e))return{runs:[]};let e=JSON.parse(A.readFileSync($e,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Qe(e){A.existsSync(ke)||A.mkdirSync(ke,{recursive:!0});try{zt($e,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ye(e,t="default"){let o=ze();for(let l of o.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let r=new Date,s={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(l=>new Date(l.timestamp).getTime()>i),Qe(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Ie(e,t,o=null,r=null){if(!e)return;let s=null;try{let l=ze(),u=l.runs[e.runIndex];if(u&&u.status==="running"&&u.script===e.script)u.status=t,u.result=t,u.duration=Date.now()-e.startTime,u.stats=o,u.error=r,s=u.duration;else{let n=l.runs.find(c=>c.script===e.script&&c.status==="running"&&c.timestamp===new Date(e.startTime).toISOString());n&&(n.status=t,n.result=t,n.duration=Date.now()-e.startTime,n.stats=o,n.error=r,s=n.duration)}Qe(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Ge({scriptName:e.script,mode:e.mode,status:l,summaryLines:i,error:r,duration:s??Date.now()-e.startTime}).catch(u=>console.error(`[runLog] postRunReport failed: ${u.message}`))}}async function g(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function N(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let r of t){let s=r.innerText||"",i=s.includes("Premium")||s.includes("premium")||s.includes("Upgrade")||s.includes("upgrade"),l=s.includes("Try for")||s.includes("free trial")||s.includes("/month")||s.includes("per month")||s.includes("Start my")||s.includes("Subscribe"),u=s.includes("Get hired faster")||s.includes("Get hired 2x");if(i||l||u){let n=r.querySelector('button[aria-label="Dismiss"]')||r.querySelector("button.artdeco-modal__dismiss")||r.querySelector("button[data-test-modal-close-btn]");if(n)return n.click(),{dismissed:!0,matched:s.substring(0,80)};let c=r.querySelectorAll("button");for(let a of c){let f=a.innerText?.trim().toLowerCase()||"",d=a.getAttribute("aria-label")?.toLowerCase()||"";if(f==="not now"||f==="no thanks"||f==="dismiss"||d.includes("dismiss"))return a.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 r=o.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||o.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(r)return r.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}Fe();async function ft(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 g(3e3);let r=e.url();return r.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${r.slice(0,80)}`),!0}function no(e,t=[]){if(!e||!t||t.length===0)return!1;let o=e.toLowerCase();return t.some(r=>o.includes(r.toLowerCase()))}async function so(e,t){try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(2e3+Math.random()*2e3),await N(e)&&(console.log(" Dismissed Premium overlay"),await g(1500),await ft(e,t));let r=await e.evaluate(()=>{let s=document.querySelector("h1")?.textContent?.trim()||null,i=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,l=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,u=document.querySelector("section#about div.display-flex")?.textContent?.trim()||null,c=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,f=document.querySelector(".dist-value")?.textContent?.trim()||null,p=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,y=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),w=y?parseInt(y[1],10):null,b=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,C=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:s,title:i,location:l,about:u,company:c,connectionDegree:f,connectionsCount:p,mutualConnections:w,photoUrl:b,hasVerifiedBadge:C}});return console.log(`Viewed: ${r.name} - ${r.title}`),{...r,profileUrl:t}}catch(o){console.error(`Error viewing profile ${t}:`,o.message);try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{}return null}}async function te(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll('button[aria-label*="Pending"]'),r=Array.from(o).map(n=>n.getAttribute("aria-label")),s=document.querySelector('button[aria-label*="Message"]'),i=document.querySelector('button[aria-label*="Invite"][aria-label*="connect"]')||document.querySelector('button[aria-label="Connect"]'),l={pendingCount:o.length,pendingLabels:r,hasMessageBtn:!!s,hasConnectBtn:!!i};return o.length>0?{status:"pending",debug:l}:s&&!i?{status:"connected",debug:l}:document.body.innerText.includes("1st degree connection")?{status:"connected",debug:l}:{status:"not_connected",debug:l}});return console.log(" DEBUG connection status:",JSON.stringify(t.debug)),t.status}async function Te(e){let t=null,o=await e.evaluate(()=>{let n=document.querySelector("h1")?.textContent?.trim();if(n&&!n.includes("notification"))return n;let c=document.querySelector('main h2, [class*="profile"] h2, [class*="top-card"] h2');if(c&&(n=c.textContent?.trim(),n&&!n.includes("notification")))return n;let a=document.querySelector('[class*="text-heading-xlarge"]')||document.querySelector('[class*="profile-card-title"]')||document.querySelector(".pv-text-details__left-panel h1");if(a)return a.textContent?.trim()||"";let f=document.title;return f&&f.includes("|")?f.split("|")[0].trim():""});if(console.log(` Profile name: "${o}"`),o){let n=await e.evaluate(()=>{let a=document.querySelectorAll('a[href*="custom-invite"]');return{count:a.length,labels:Array.from(a).map(f=>f.getAttribute("aria-label")?.slice(0,50))}});n.count>0&&console.log(` S0: ${n.count} custom-invite links: ${JSON.stringify(n.labels)}`),t=await e.evaluateHandle(a=>{let f=document.querySelectorAll('a[href*="custom-invite"]'),d=a.toLowerCase().split(" ")[0],p=null,h=null;for(let m of f){let y=m.getBoundingClientRect();if(y.width===0||y.height===0)continue;if((m.getAttribute("aria-label")||"").toLowerCase().includes(d)){p=m;break}h||(h=m)}return p||h||null},o);let c=t?.asElement?.()||null;if(c||await t?.dispose?.().catch(()=>{}),c)return console.log(" Found: Connect link (new LinkedIn 2025)"),{button:c,method:"connect_link"}}if(o){let n=o.split(" ")[0].toLowerCase();console.log(` Looking for button with name: "${n}"`);let c=await e.evaluate(f=>{let d=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i"),p=document.querySelectorAll("button[aria-label]");return Array.from(p).filter(m=>{let y=m.getAttribute("aria-label")||"";return(y.toLowerCase().includes("invite")||y.toLowerCase().includes("connect"))&&d.test(y)}).map(m=>m.getAttribute("aria-label")?.slice(0,50))},n);c.length>0&&console.log(` S1: matched buttons: ${JSON.stringify(c)}`),t=await e.evaluateHandle(f=>{let d=document.querySelectorAll("button[aria-label]"),p=new RegExp("\\b"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i");for(let h of d){let m=h.getAttribute("aria-label")||"";if((m.toLowerCase().includes("invite")||m.toLowerCase().includes("connect"))&&p.test(m))return h}return null},n);let a=t?.asElement?.()||null;if(a||await t?.dispose?.().catch(()=>{}),a)return console.log(" Found: button matching profile name"),{button:a,method:"name_matched_button"}}if(t=await e.$('button.artdeco-button--primary[aria-label*="Invite"]:not([class*="sticky-header"]):not([class*="muted"])'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping primary button: wrong person (${n})`),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 r=await e.$$('button[aria-label*="Invite"][aria-label*="connect"]');r.length===0&&(r=await e.$$('button[aria-label="Connect"]'));let s=o?o.split(" ")[0].toLowerCase():"",i=null;for(let n of r){let c=await e.evaluate((a,f)=>{let d=a.className.includes("muted"),p=a.className.includes("sticky-header")||a.className.includes("sticky"),h=a.closest('[class*="pymk"], [class*="people-also-viewed"], [class*="browse-map"]')!==null,m=(a.getAttribute("aria-label")||"").toLowerCase(),y=m.includes("invite"),w=f?m.includes(f):!0;return{isMuted:d,isStickyHeader:p,inRecommendations:h,hasInvite:y,matchesName:w,ariaLabel:m}},n,s);if(!c.isMuted&&!c.isStickyHeader&&!c.inRecommendations){if(c.hasInvite&&!c.matchesName){console.log(` Skipping secondary button: wrong person (${c.ariaLabel})`);continue}i=n;break}}for(let n of r)n!==i&&await n.dispose().catch(()=>{});if(i)return console.log(" Found: secondary button"),{button:i,method:"secondary_button"};if(t=await e.$('section.pv-supplementary-action button[aria-label*="Invite"]'),t||(t=await e.$('section.pv-supplementary-action button[aria-label="Connect"]')),t)return console.log(" Found: supplementary section"),{button:t,method:"supplementary_section"};console.log(" Trying More actions dropdown...");let l=null,u=await e.$$('button[id*="profile-overflow-action"]');for(let n of u){let c=await e.evaluate(a=>{let f=a.getBoundingClientRect(),d=f.width>0&&f.height>0,p=a.closest('.sticky-header, [class*="sticky"]')!==null;return{isVisible:d,isInStickyHeader:p,top:f.top}},n);if(c.isVisible&&!c.isInStickyHeader){l=n,console.log(" Found More button by ID pattern (main)");break}}for(let n of u)n!==l&&await n.dispose().catch(()=>{});if(!l&&u.length>0&&(l=u[u.length-1],console.log(" Found More button by ID pattern (last)")),l||(l=await e.$('button[aria-label="More actions"]'),l&&console.log(" Found More button by aria-label")),!l){let n=await e.evaluateHandle(()=>{let a=Array.from(document.querySelectorAll("button, a")).find(d=>{let p=d.innerText?.trim(),h=d.getAttribute("aria-label")||"",m=d.getBoundingClientRect();return m.top<100||m.top>600||m.width===0?!1:p==="Follow"||p==="Message"||p==="Connect"||h.includes("Follow")||h.includes("Message")||h.includes("Invite")});if(!a)return null;let f=a.parentElement;for(let d=0;d<8&&f;d++){for(let p of f.querySelectorAll("button"))if(p.innerText?.trim()==="More"&&p!==a)return p;f=f.parentElement}return null});l=n?.asElement?.()||null,l||await n?.dispose?.().catch(()=>{}),l&&console.log(" Found More button by text (near profile actions)")}if(l)try{if(await e.evaluate(a=>a.scrollIntoView({behavior:"smooth",block:"center"}),l),await g(500),await e.evaluate(a=>a.click(),l),await g(2e3),!e.url().includes("/in/"))return console.log(" Redirect detected after More click, aborting"),null;let c=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]');if(c||(c=await e.$('.artdeco-dropdown__item[aria-label*="connect"]')),c||(c=await e.$('.artdeco-dropdown__item[aria-label="Connect"]')),c||(c=await e.$('div[role="button"][aria-label*="Invite"]')),c||(c=await e.$('div[role="button"][aria-label*="connect"]')),!c){let a=await e.evaluateHandle(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content');for(let d of f){let p=d.querySelector('a[href*="custom-invite"]');if(p)return p;for(let h of d.querySelectorAll('a, div[role="menuitem"], div[role="button"]'))if(h.innerText?.trim()==="Connect")return h}return null});c=a?.asElement?.()||null,c||await a?.dispose?.().catch(()=>{})}if(!c){let a=await e.evaluate(()=>{let f=document.querySelectorAll('[role="menu"], [popover], .artdeco-dropdown__content'),d=[];for(let p of f)for(let h of p.querySelectorAll('[role="menuitem"], a, div')){let m=h.innerText?.trim();m&&m.length<40&&d.push(m)}return[...new Set(d)].slice(0,10)});console.log(` More dropdown items: ${JSON.stringify(a)}`)}if(c)return console.log(" Found: More dropdown"),{button:c,method:"more_dropdown"};await e.keyboard.press("Escape")}catch(n){console.log(" More dropdown click failed:",n.message),await e.keyboard.press("Escape")}if(t=await e.$('button[aria-label*="Invite"]'),t&&o){let n=await e.evaluate(a=>(a.getAttribute("aria-label")||"").toLowerCase(),t),c=o.split(" ")[0].toLowerCase();n.includes("invite")&&!n.includes(c)&&(console.log(` Skipping generic button: wrong person (${n})`),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 ro(e,t){await e.evaluate(c=>c.scrollIntoView({behavior:"smooth",block:"center"}),t),await g(500);let o=await e.evaluate(c=>({tag:c.tagName,ariaLabel:c.getAttribute("aria-label"),href:c.getAttribute("href")}),t),s=o.tag==="A"&&o.href&&o.href.includes("custom-invite"),i=o.tag==="DIV";if(s){console.log(" Clicking custom-invite link (will navigate)..."),await Promise.all([e.waitForNavigation({waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),e.evaluate(a=>a.click(),t)]),await g(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 g(2e3),"premium_redirect"}else i?(await e.evaluate(c=>c.click(),t),await g(3e3)):(await e.evaluate(c=>c.click(),t),await g(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 u=await e.evaluate(()=>!!document.querySelector('[role="dialog"], .artdeco-modal, .send-invite')),n=e.url();return console.log(u?` \u2713 Connect sent \u2014 ${n}`:` \u26A0 No modal after connect click \u2014 ${n}`),"success"}async function io(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 g(1500);let o=await Te(e);if(o){await e.evaluate(s=>s.click(),o),await g(2e3);let r=await e.$('button[aria-label="Send without a note"]');if(r){try{await r.evaluate(s=>s.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),!0}}return!1}async function lo(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,skipIfPending:i=!0,skipIfConnected:l=!0,excludeLocations:u=[]}=o,n={success:!1,reason:null,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null};try{let c=t.split("/in/")[1]?.replace("/","")||"unknown";if(console.log(`
|
|
12
|
+
--- Connecting: ${c} ---`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(5e3),await N(e)&&(console.log(" Dismissed Premium overlay"),await g(2e3),await ft(e,t),await g(2e3)),n.profileInfo=await e.evaluate(()=>{let w=document.querySelector("h1")?.textContent?.trim()||null,S=document.querySelector("div.text-body-medium")?.textContent?.trim()||null,b=document.querySelector(".text-body-small.inline.t-black--light.break-words")?.textContent?.trim()||null,$=document.querySelector('button[aria-label^="Current company"] span.hoverable-link-text')?.textContent?.trim()||null,L=document.querySelector(".dist-value")?.textContent?.trim()||null,Tt=document.querySelector('a[href*="connectionOf"] span.t-bold')?.textContent?.trim()||null,Be=(document.querySelector('a[href*="facetConnectionOf"] span.t-normal')?.textContent?.trim()||null)?.match(/(\d+)\s+other\s+mutual/),Pt=Be?parseInt(Be[1],10):null,Rt=document.querySelector("img.pv-top-card-profile-picture__image--show")?.src||null,Lt=!!document.querySelector(".pv-text-details__verified-badge-icon");return{name:w,title:S,location:b,company:$,connectionDegree:L,connectionsCount:Tt,mutualConnections:Pt,photoUrl:Rt,hasVerifiedBadge:Lt}}),u.length>0&&no(n.profileInfo?.location,u))return console.log(` \u26A0 Excluded location: ${n.profileInfo.location}`),n.reason="excluded_location",n;let f=await te(e);if(f==="pending"&&i)return console.log(" \u26A0 Already pending - skipping"),n.reason="pending",n;if(f==="connected"&&l)return console.log(" \u26A0 Already connected - skipping"),n.reason="connected",n;await N(e);let d=await Te(e);if(!d&&(await N(e)&&(console.log(" Dismissed overlay, retrying connect button search..."),await g(2e3),d=await Te(e)),!d))return console.log(" \u2717 Connect not found"),n.reason="button_not_found",n;if(n.method=d.method,await ro(e,d.button)==="premium_redirect"){console.log(" \u26A0 Premium upsell redirect \u2014 navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(4e3);let w=await te(e);if(w==="pending")return console.log(" \u2713 Connection was sent (detected Pending after upsell redirect)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;console.log(` Status after upsell: ${w} \u2014 trying More dropdown...`),await N(e),await g(1e3);let S=await e.$('button[id*="profile-overflow-action"]:not([class*="sticky"])');if(S)try{await e.evaluate(C=>C.scrollIntoView({behavior:"smooth",block:"center"}),S),await g(500),await S.click().catch(()=>e.evaluate(C=>C.click(),S)),await g(2e3);let b=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(b){console.log(" Found Connect in More dropdown, clicking..."),await e.evaluate(M=>M.click(),b),await g(3e3);let C=e.url();if(C.includes("/premium/")||C.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),n.reason="premium_required",n;if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.method="more_dropdown",n.withCustomMessage=!1,n;console.log(" More dropdown clicked, checking for modal...")}else return console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape"),await g(500),n.reason="premium_required",n}catch(b){return console.log(" More dropdown failed:",b.message),await e.keyboard.press("Escape").catch(()=>{}),n.reason="premium_required",n}else return console.log(" \u2717 No More button found \u2014 Premium required"),n.reason="premium_required",n}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 g(500),n.reason="email_required",n}let m=await e.$('button[aria-label="Add a note"]'),y=await e.$('button[aria-label="Send without a note"]');if(!m&&!y){let w=await e.evaluate(()=>{let S=document.querySelector("#interop-outlet")?.shadowRoot;if(!S)return{addNote:!1,sendWithout:!1};let b=S.querySelector('button[aria-label="Add a note"]'),C=S.querySelector('button[aria-label="Send without a note"]');return{addNote:!!b,sendWithout:!!C}});if(w.addNote){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Add a note"]'));m=S?.asElement?.()||null,m||await S.dispose().catch(()=>{})}if(w.sendWithout){let S=await e.evaluateHandle(()=>document.querySelector("#interop-outlet")?.shadowRoot?.querySelector('button[aria-label="Send without a note"]'));y=S?.asElement?.()||null,y||await S.dispose().catch(()=>{})}}if(s){if(m&&r){if(console.log(" Adding personalized note..."),await m.click(),await g(1500),await e.$("div.modal-upsell")){let b=await io(e);return n.success=b,n.connectionSent=b,n.reason=b?"sent_without_note_upsell":"upsell_failed",n.withCustomMessage=!1,n}let S=await e.$('textarea[name="message"]')||await e.$("textarea#custom-message")||await e.$("textarea");if(S){let b=await e.evaluate(()=>document.querySelector("h1")?.textContent?.trim()?.split(" ")[0]||""),C=r.replace("{name}",b);await S.type(C,{delay:20}),await g(500);let $=await e.$('button[aria-label="Send invitation"]')||await e.$('button[aria-label="Send now"]');if($){try{await $.evaluate(M=>M.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (with note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_with_note",n.withCustomMessage=!0,n.messageSent=C,n}}}else if(y){console.log(" Sending without note...");try{await y.evaluate(w=>w.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}else if(m&&!r){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(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}}else{console.log(" Sending without note (custom messages disabled)...");let w=y;if(w){try{await w.evaluate(S=>S.click())}catch{console.log(" Click timeout, likely still sent")}return await g(3e3),console.log(" \u2713 Connection sent (without note)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}}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 g(4e3)),await N(e),await g(500);let S=await e.$$('button[id*="profile-overflow-action"]'),b=null;for(let C of S){let $=await e.evaluate(M=>{let L=M.getBoundingClientRect();return{visible:L.width>0&&L.height>0,inSticky:!!M.closest('.sticky-header, [class*="sticky"]')}},C);if($.visible&&!$.inSticky){b=C;break}}!b&&S.length>0&&(b=S[S.length-1]);for(let C of S)C!==b&&await C.dispose().catch(()=>{});if(b)try{await e.evaluate($=>$.scrollIntoView({behavior:"smooth",block:"center"}),b),await g(500),await b.click().catch(()=>e.evaluate($=>$.click(),b)),await g(2e3);let C=await e.$('.artdeco-dropdown__item[aria-label*="Invite"]')||await e.$('.artdeco-dropdown__item[aria-label*="connect"]')||await e.$('.artdeco-dropdown__item[aria-label="Connect"]')||await e.$('div[role="button"][aria-label*="Invite"]')||await e.$('div[role="button"][aria-label*="connect"]');if(C){console.log(" Found Connect in More dropdown, clicking..."),n.method="more_dropdown",await e.evaluate(Y=>Y.click(),C),await g(3e3);let $=e.url();if($.includes("/premium/")||$.includes("/redeem"))return console.log(" \u2717 More dropdown also redirected to Premium"),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await g(3e3),await te(e)==="pending"?(console.log(" \u2713 Connection was sent (detected Pending)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n):(n.reason="premium_required",n);if(await te(e)==="pending")return console.log(" \u2713 Connection sent via More dropdown"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n;let L=await e.$('button[aria-label="Send without a note"]');if(L){console.log(" Modal appeared via More dropdown, sending without note...");try{await L.evaluate(Y=>Y.click())}catch{}return await g(3e3),console.log(" \u2713 Connection sent (without note, via More dropdown)"),n.success=!0,n.connectionSent=!0,n.reason="sent_without_note",n.withCustomMessage=!1,n}console.log(" More dropdown: no modal either")}else console.log(" No Connect option in More dropdown"),await e.keyboard.press("Escape")}catch(C){console.log(" More dropdown fallback failed:",C.message),await e.keyboard.press("Escape").catch(()=>{})}}return console.log(" \u2717 Could not complete connection request"),n.reason="modal_failed",n}catch(c){console.error(` \u2717 Error: ${c.message}`),n.reason="error",n.error=c.message;let a=c.message.toLowerCase();if(a.includes("detached")||a.includes("session closed")||a.includes("target closed")||a.includes("browser has disconnected")||a.includes("protocol error"))return n.fatal=!0,n;try{await e.goto("about:blank",{timeout:1e4}),await g(1e3)}catch{n.fatal=!0}return n}}async function pt(e,t,o={}){let{message:r=null,useCustomMessage:s=!0,maxConnections:i=20,viewOnly:l=!1,delayBetweenProfiles:u=3e3,onProfileProcessed:n=null,excludeLocations:c=[],source:a="unknown"}=o,f={viewed:0,connectionsSent:0,skipped:{pending:0,connected:0,email:0,notFound:0,excludedLocation:0},errors:0};if(console.log(`
|
|
13
|
+
=== Running Funnel: ${t.length} profiles ===`),console.log(`Mode: ${l?"View Only":`Connect (max ${i})`}`),l||console.log(`Custom messages: ${s?"Enabled":"Disabled (saving quota)"}`),c.length>0&&console.log(`Excluding locations: ${c.join(", ")}`),!l){let p=ee();console.log(`Quota: today ${p.daily.sent}/${p.daily.max} | week ${p.weekly.sent}/${p.weekly.max}`)}console.log("");let d=0;for(let p=0;p<t.length;p++){let h=t[p];try{if(e.isClosed()){console.log(`
|
|
14
14
|
\u26A0 Browser page is closed \u2014 aborting funnel`);break}}catch{console.log(`
|
|
15
|
-
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${
|
|
15
|
+
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!h.profileUrl){console.log(`[${p+1}/${t.length}] Skipping - no URL`);continue}let m=me(h.profileUrl);if(m==="pending"||m==="connected"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"){console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl} \u2014 skipped (db: ${m})`),m==="pending"||m==="sent_with_note"||m==="sent_without_note"||m==="sent_without_note_upsell"?f.skipped.pending++:f.skipped.connected++,n&&await n(h,f,{success:!1,reason:m,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${p+1}/${t.length}] ${h.name||h.profileUrl}`);let y=null;if(l){let w=await so(e,h.profileUrl);w?(f.viewed++,y={success:!0,reason:"viewed",connectionSent:!1,profileInfo:w}):(f.errors++,y={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(f.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let w=Se();if(!w.allowed){console.log(` \u26A0 Global quota exhausted: ${w.reason}`);break}if(y=await lo(e,h.profileUrl,{message:r,useCustomMessage:s,excludeLocations:c}),y.success)f.connectionsSent++,y.connectionSent&&we(h.profileUrl,a);else switch(y.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(y?.fatal){console.log(`
|
|
16
16
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),f.errors++;break}if(y?.reason==="error"){if(d++,d>=3){console.log(`
|
|
17
|
-
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(y&&y.reason&&(ge(h.profileUrl,y.reason,{method:y.method,messageSent:y.messageSent,profileInfo:y.profileInfo}),
|
|
18
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let
|
|
17
|
+
\u26A0 ${d} consecutive errors \u2014 aborting funnel`);break}}else d=0;if(y&&y.reason&&(ge(h.profileUrl,y.reason,{method:y.method,messageSent:y.messageSent,profileInfo:y.profileInfo}),pe(h.profileUrl,{source:a||"funnel",jobId:h.jobId||h.fromJob?.jobId||null,jobTitle:h.fromJob?.title||null,jobCompany:h.fromJob?.company||null,action:y.reason})),n&&await n(h,f,y),p<t.length-1){let w=u+Math.random()*2e3;await g(w)}}if(console.log(`
|
|
18
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${f.viewed}`),console.log(` Connections sent: ${f.connectionsSent}`),console.log(` Skipped (pending): ${f.skipped.pending}`),console.log(` Skipped (connected): ${f.skipped.connected}`),console.log(` Skipped (email req): ${f.skipped.email}`),console.log(` Skipped (not found): ${f.skipped.notFound}`),f.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${f.skipped.excludedLocation}`),console.log(` Errors: ${f.errors}`),!l){let p=ee();console.log(` Quota remaining: today ${p.daily.remaining}/${p.daily.max} | week ${p.weekly.remaining}/${p.weekly.max}`)}return f}import"dotenv/config";import*as x from"fs";import*as T from"path";import{fileURLToPath as co}from"url";var ao=co(import.meta.url),uo=T.dirname(T.dirname(ao)),oe=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(uo,"collected-profiles");function Pe(){x.existsSync(oe)||x.mkdirSync(oe,{recursive:!0})}function fo(){return new Date().toISOString().split("T")[0]}function mt(e,t=null){let o=t||fo();return T.join(oe,`${e}-${o}.json`)}function gt(e,t=null){Pe();let o=mt(e,t);try{if(x.existsSync(o)){let r=x.readFileSync(o,"utf-8"),s=JSON.parse(r);return console.log(`\u{1F4C2} Loaded ${s.profiles.length} profiles from ${o}`),s.profiles}}catch(r){console.error(`Error loading profiles from ${o}:`,r.message)}return[]}function ht(e,t=null){return gt(e,t).filter(r=>!r.processed)}function wt(e,t,o,r=null){Pe();let s=mt(e,r);try{if(!x.existsSync(s))return;let i=JSON.parse(x.readFileSync(s,"utf-8")),l=i.profiles.find(u=>u.profileUrl===t);if(l){if(l.processed=!0,l.processedAt=new Date().toISOString(),typeof o=="string")l.status=o;else if(typeof o=="object"){if(l.status=o.status,o.profileInfo){let u=o.profileInfo;u.name&&(l.name=u.name),u.title&&(l.title=u.title),u.location&&(l.location=u.location),u.company&&(l.company=u.company),u.connectionDegree&&(l.connectionDegree=u.connectionDegree),u.connectionsCount&&(l.connectionsCount=u.connectionsCount),u.mutualConnections&&(l.mutualConnections=u.mutualConnections),u.photoUrl&&(l.photoUrl=u.photoUrl),u.hasVerifiedBadge!==void 0&&(l.hasVerifiedBadge=u.hasVerifiedBadge)}l.funnelResult={connectionSent:o.connectionSent||!1,withCustomMessage:o.withCustomMessage||!1,message:o.message||null,method:o.method||null,reason:o.reason||null,error:o.error||null}}i.lastUpdated=new Date().toISOString(),x.writeFileSync(s,JSON.stringify(i,null,2))}}catch(i){console.error("Error marking profile processed:",i.message)}}function yt(e){let t=gt(e),o=t.filter(s=>s.processed),r=t.filter(s=>!s.processed);return{total:t.length,processed:o.length,unprocessed:r.length,statuses:o.reduce((s,i)=>(s[i.status]=(s[i.status]||0)+1,s),{})}}function St(){Pe();try{return x.readdirSync(oe).filter(t=>t.endsWith(".json")).map(t=>{let[o,r]=t.replace(".json","").split(/-(?=\d{4}-\d{2}-\d{2}$)/);try{let s=JSON.parse(x.readFileSync(T.join(oe,t),"utf-8"));return{file:t,source:o,date:r,count:s.profiles?.length||0,unprocessed:s.profiles?.filter(i=>!i.processed).length||0}}catch{return{file:t,source:o,date:r,count:0,unprocessed:0}}})}catch(e){return console.error("Error listing files:",e.message),[]}}import"dotenv/config";import*as E from"fs";import*as I from"path";import{fileURLToPath as Io}from"url";var xo=Io(import.meta.url),Do=I.dirname(xo),Et=I.dirname(I.dirname(Do)),Ce=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(Et,"collected-profiles"),ve=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"market-research"):I.join(Et,"market-research"),qe=1,_o=[{version:1,file:"./v001-normalize-jobs-and-questions.mjs"}];function At(e){return I.join(e,".schema-version")}function Ue(e){let t=At(e);if(!E.existsSync(t))return{version:0,migrations:[]};try{return JSON.parse(E.readFileSync(t,"utf-8"))}catch{return{version:0,migrations:[]}}}function jo(e,t){E.writeFileSync(At(e),JSON.stringify(t,null,2))}function _t(e,t){if(!E.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=E.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.includes(".backup"));for(let s of r){let i=I.join(e,s),l=I.join(e,s+o);try{E.copyFileSync(i,l)}catch(u){console.error(` [!] Failed to backup ${s}: ${u.message}`)}}r.length>0&&console.log(` Backed up ${r.length} files in ${I.basename(e)}/ (${o})`)}var jt=!1;async function Ot(){if(jt)return;jt=!0;let e=Ue(Ce),t=Ue(ve),o=Math.min(e.version,t.version);if(o>=qe)return;console.log(`
|
|
19
19
|
\u{1F4E6} Schema migration: v${o} \u2192 v${qe}`);let r=_o.filter(s=>s.version>o);for(let s of r){console.log(`
|
|
20
20
|
Running migration v${String(s.version).padStart(3,"0")}...`),_t(Ce,s.version),_t(ve,s.version);let i=await import(s.file);try{await i.up(Ce,ve)}catch(n){console.error(`
|
|
21
21
|
[FATAL] Migration v${s.version} failed: ${n.message}`),console.error(` Backups are in collected-profiles/ and market-research/ (.pre-v${String(s.version).padStart(3,"0")}.backup)`),console.error(` Fix the issue and restart.
|
|
@@ -34,7 +34,7 @@ Press Enter to start, or Ctrl+C to cancel...`),await new Promise(n=>{process.std
|
|
|
34
34
|
`);let o=await Mo.launch({headless:!1,devtools:!1,defaultViewport:null,protocolTimeout:3e5}),r=await o.newPage();try{let n=Ft();await r.setCookie(...n),console.log(`\u2713 Cookies loaded
|
|
35
35
|
`)}catch(n){console.error(`
|
|
36
36
|
[!] ${n.message}
|
|
37
|
-
`),await o.close(),process.exit(1)}let s=e.viewOnly?"view-only":"connect",i=Ye("funnel",s),l=await
|
|
37
|
+
`),await o.close(),process.exit(1)}let s=e.viewOnly?"view-only":"connect",i=Ye("funnel",s),l=await pt(r,t,{message:e.message,useCustomMessage:e.useCustomMessage,maxConnections:e.max,viewOnly:e.viewOnly,excludeLocations:e.excludeLocations,source:e.source||"funnel-runner",delayBetweenProfiles:3e3,onProfileProcessed:async(n,c,a)=>{wt(e.source,n.profileUrl,{status:a.reason,connectionSent:a.connectionSent,withCustomMessage:a.withCustomMessage,message:a.messageSent,method:a.method,reason:a.reason,error:a.error,profileInfo:a.profileInfo})}});console.log(`
|
|
38
38
|
========================================`),console.log("Funnel Complete!"),console.log(`========================================
|
|
39
39
|
`);let u=yt(e.source);if(console.log(`Processed: ${u.processed}/${u.total}`),console.log(`Remaining: ${u.unprocessed}`),Object.keys(u.statuses).length>0){console.log(`
|
|
40
40
|
Status breakdown:`);for(let[n,c]of Object.entries(u.statuses))console.log(` ${n}: ${c}`)}Ie(i,"success",{sent:l.connectionsSent,viewed:l.viewed,errors:l.errors,skippedPending:l.skipped?.pending||0,skippedConnected:l.skipped?.connected||0}),await o.close(),process.exit(0)}To().catch(e=>{console.error("Funnel failed:",e);try{Ie(null,"error",null,e.message)}catch{}process.exit(1)});
|
package/dist/messageBot.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var tX=Object.create;var VE=Object.defineProperty;var rX=Object.getOwnPropertyDescriptor;var iX=Object.getOwnPropertyNames;var nX=Object.getPrototypeOf,sX=Object.prototype.hasOwnProperty;var Y=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,A)=>(typeof require<"u"?require:e)[A]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var XE=(t,e)=>()=>(t&&(e=t(t=0)),e);var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ZE=(t,e)=>{for(var A in e)VE(t,A,{get:e[A],enumerable:!0})},p1=(t,e,A,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iX(e))!sX.call(t,i)&&i!==A&&VE(t,i,{get:()=>e[i],enumerable:!(r=rX(e,i))||r.enumerable});return t};var D1=(t,e,A)=>(A=t!=null?tX(nX(t)):{},p1(e||!t||!t.__esModule?VE(A,"default",{value:t,enumerable:!0}):A,t)),st=t=>p1(VE({},"__esModule",{value:!0}),t);var J1={};ZE(J1,{addEncounter:()=>k1,canSendConnection:()=>N1,commitDataSnapshot:()=>H1,default:()=>EX,getAllApplications:()=>K1,getPersonStatus:()=>M1,getQuestionStats:()=>O1,getQuotaStatus:()=>x1,getRecentConnections:()=>tB,linkPersonToJob:()=>v1,loadApplicationQuestions:()=>aw,loadConversations:()=>Zt,loadJobs:()=>$E,loadPeople:()=>Rt,loadQuota:()=>AB,loadSyncState:()=>U1,logApplicationQuestions:()=>T1,migrateFromDailyFiles:()=>L1,recordConnectionSent:()=>_1,resetCaches:()=>cX,saveConversations:()=>Pr,saveJobs:()=>eB,savePeople:()=>In,saveQuota:()=>ow,saveSyncState:()=>G1,updateConnectionStatus:()=>R1,upsertJob:()=>b1,upsertPerson:()=>sw});import"dotenv/config";import*as rt from"fs";import*as mt from"path";import{fileURLToPath as aX}from"url";import{execSync as Aw}from"child_process";function cX(){eu=null,Au=null,vs=null,Ma=null,tu=null,ka=null}function Si(){rt.existsSync(mi)||rt.mkdirSync(mi,{recursive:!0})}function Ra(t,e){let A=JSON.stringify(e,null,2),r=t+".tmp";rt.writeFileSync(r,A);for(let i=0;i<3;i++)try{rt.renameSync(r,t);return}catch(n){if(i<2&&(n.code==="EPERM"||n.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw n}}function ql(t,e){if(!rt.existsSync(t))return null;try{let A=JSON.parse(rt.readFileSync(t,"utf-8"));try{rt.copyFileSync(t,t+".backup")}catch{}return A}catch(A){console.error(`[!] ${e} is corrupted: ${A.message}`),console.error(` File: ${mt.resolve(t)}`);let r=t+".backup";if(rt.existsSync(r))try{let i=JSON.parse(rt.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{rt.copyFileSync(r,t)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{rt.copyFileSync(t,t+".corrupted")}catch{}return null}}function ru(){return new Date().toISOString().split("T")[0]}function Rt(){return eu||(Si(),eu=ql(tw,"people.json")||{},eu)}function In(t){Si(),eu=t;try{Ra(tw,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${mt.resolve(tw)}`)}}function $E(){return Au||(Si(),Au=ql(rw,"jobs.json")||{},Au)}function eB(t){Si(),Au=t;try{Ra(rw,t)}catch(e){console.error(`[!] Failed to save jobs.json: ${e.message}`),console.error(` Path: ${mt.resolve(rw)}`)}}function Zt(){return Ma||(Si(),Ma=ql(zE,"conversations.json")||{},lX(Ma),Ma)}function lX(t){let e=0;for(let A of Object.values(t)){if(!(A.draftStatus!==void 0||A.draftPreparedAt!==void 0))continue;let i=(A.messages||[]).find(n=>n.status==="draft");i&&A.draftStatus&&A.draftStatus!=="pending"&&(i.status=A.draftStatus),delete A.draftStatus,delete A.draftPreparedAt,e++}if(e>0){console.log(` [migration] Moved draft state from conv to msg.status for ${e} conversations`);try{Ra(zE,t)}catch{}}}function Pr(t){Si(),Ma=t;try{Ra(zE,t)}catch(e){console.error(`[!] Failed to save conversations.json: ${e.message}`),console.error(` Path: ${mt.resolve(zE)}`)}}function sw(t,e={}){if(!t)return null;let A=Rt(),r=ru(),i=new Date().toISOString(),n=A[t];if(n){n.seenCount=(n.seenCount||1)+1,n.lastSeen=r,n.lastUpdated=i,e.source&&!n.sources?.includes(e.source)&&(n.sources=n.sources||[],n.sources.push(e.source));for(let s of nw)e[s]!=null&&(n[s]=e[s])}else A[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,firstSeen:r,lastSeen:r,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i};return In(A),A[t]}function b1(t,e={}){if(!t)return null;let A=$E(),r=ru(),i=A[t];if(i){let n=["title","company","companyUrl","location","salary","url","applied","appliedDate","recruiterUrl","description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","scoutedAt","lastSeen"];for(let s of n)e[s]!=null&&(i[s]=e[s])}else A[t]={title:e.title||null,company:e.company||null,location:e.location||null,salary:e.salary||null,url:e.url||null,applied:e.applied||!1,appliedDate:e.appliedDate||r,recruiterUrl:e.recruiterUrl||null,firstSeen:r};return eB(A),A[t]}function v1(t,e){if(!t||!e)return;let A=Rt(),r=A[t];r&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(e)||(r.jobIds.push(e),r.lastUpdated=new Date().toISOString(),In(A)))}function k1(t,e){if(!t||!e)return;let A=Rt(),r=A[t];if(!r)return;r.encounters||(r.encounters=[]);let n={date:ru(),source:e.source||"unknown",action:e.action||"unknown"};e.jobId&&(n.jobId=String(e.jobId)),e.jobTitle&&(n.jobTitle=e.jobTitle),e.jobCompany&&(n.jobCompany=e.jobCompany),!r.encounters.some(o=>o.date===n.date&&o.source===n.source&&o.action===n.action&&(o.jobId||"")===(n.jobId||""))&&(r.encounters.push(n),r.lastUpdated=new Date().toISOString(),In(A))}function M1(t){return t&&Rt()[t]?.connectionStatus||null}function R1(t,e,A={}){if(!t)return;let r=Rt(),i=r[t];if(i||(sw(t,A.profileInfo||{}),i=r[t]),!!i){if(i.connectionStatus=e,i.connectionDate=ru(),i.connectionMethod=A.method||i.connectionMethod,i.messageSent=A.messageSent||i.messageSent,i.lastUpdated=new Date().toISOString(),A.profileInfo)for(let n of nw)A.profileInfo[n]!=null&&(i[n]=A.profileInfo[n]);In(r)}}function AB(){return vs||(Si(),vs=ql(S1,"quota.json"),(!vs||!vs.connections)&&(vs={connections:[]}),vs)}function ow(t){Si(),vs=t;try{Ra(S1,t)}catch(e){console.error(`[!] Failed to save quota.json: ${e.message}`)}}function _1(t,e="unknown"){let A=AB(),r=new Date;A.connections.push({date:r.toISOString().split("T")[0],time:r.toTimeString().split(" ")[0],profileUrl:t,source:e}),ow(A)}function tB(){let t=AB(),e=new Date;e.setDate(e.getDate()-7);let A=e.toISOString().split("T")[0];return t.connections.filter(r=>r.date>=A)}function N1(){let t=tB(),e=ru(),A=t.filter(g=>g.date===e).length,r=t.length,i=A>=Yl,n=r>=jl,s=!i&&!n,o={allowed:s,daily:{sent:A,max:Yl},weekly:{sent:r,max:jl}};return s||(o.reason=i?`Daily limit reached (${A}/${Yl})`:`Weekly limit reached (${r}/${jl})`),o}function x1(){let t=tB(),e=ru(),A=t.filter(i=>i.date===e).length,r=t.length;return{daily:{sent:A,max:Yl,remaining:Yl-A},weekly:{sent:r,max:jl,remaining:jl-r}}}function IX(t){if(!t)return null;let e=t.match(/jobs\/view\/(\d+)/);return e?e[1]:null}function L1(){Si();let t=rt.readdirSync(mi).filter(n=>n.endsWith(".json")&&n!=="people.json"&&n!=="jobs.json"&&n!=="quota.json");if(t.length===0)return console.log("No daily files found to migrate."),{people:0,jobs:0};console.log(`
|
|
2
2
|
Migrating from ${t.length} daily files...
|
|
3
3
|
`);let e=Rt(),A=$E(),r=0,i=0;t.sort();for(let n of t){let s=mt.join(mi,n),o;try{o=JSON.parse(rt.readFileSync(s,"utf-8"))}catch(a){console.log(` Skipping ${n}: ${a.message}`);continue}let g=o.date||n.match(/\d{4}-\d{2}-\d{2}/)?.[0]||null,u=o.source||n.split("-").slice(0,-1).join("-").replace(/-\d{4}$/,"")||"unknown";if(!o.profiles||!Array.isArray(o.profiles)){console.log(` Skipping ${n}: no profiles array`);continue}console.log(` ${n}: ${o.profiles.length} profiles`);for(let a of o.profiles){let I=a.profileUrl;if(!I)continue;let l=e[I];if(l){l.seenCount=(l.seenCount||1)+1,g&&(!l.lastSeen||g>l.lastSeen)&&(l.lastSeen=g),g&&(!l.firstSeen||g<l.firstSeen)&&(l.firstSeen=g),u&&!l.sources?.includes(u)&&(l.sources=l.sources||[],l.sources.push(u));for(let c of nw)a[c]!=null&&(l[c]=a[c]);a.status&&a.processed&&(l.connectionStatus=a.status,l.connectionDate=g,a.funnelResult&&(l.connectionMethod=a.funnelResult.method||l.connectionMethod,l.messageSent=a.funnelResult.message||l.messageSent)),l.lastUpdated=new Date().toISOString()}else e[I]={name:a.name||null,title:a.title||null,location:a.location||null,company:a.company||null,connectionDegree:a.connectionDegree||null,connectionsCount:a.connectionsCount||null,mutualConnections:a.mutualConnections||null,photoUrl:a.photoUrl||null,hasVerifiedBadge:a.hasVerifiedBadge||!1,firstSeen:g,lastSeen:g,seenCount:1,sources:u?[u]:[],connectionStatus:a.processed&&a.status||null,connectionDate:a.processed?g:null,connectionMethod:a.funnelResult?.method||null,messageSent:a.funnelResult?.message||null,jobIds:[],lastUpdated:new Date().toISOString()},r++;if(a.fromJob?.url){let c=IX(a.fromJob.url);c&&(e[I].jobIds||(e[I].jobIds=[]),e[I].jobIds.includes(c)||e[I].jobIds.push(c),A[c]?A[c].recruiterUrl||(A[c].recruiterUrl=I):(A[c]={title:a.fromJob.title||null,company:a.fromJob.company||null,location:null,salary:null,url:a.fromJob.url,applied:!0,appliedDate:g,recruiterUrl:I,firstSeen:g},i++))}}}return In(e),eB(A),console.log(`
|
|
4
|
-
Migration complete!`),console.log(` People: ${Object.keys(e).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(A).length} total (${i} new)`),{people:Object.keys(e).length,jobs:Object.keys(A).length}}function U1(){return tu||(Si(),tu=ql(F1,"sync-state.json")||{},tu)}function G1(t){Si(),tu=t;try{Ra(F1,t)}catch(e){console.error(`[!] Failed to save sync-state.json: ${e.message}`)}}function aw(){if(ka)return ka;Si();try{rt.existsSync(iw)&&(ka=JSON.parse(rt.readFileSync(iw,"utf-8")))}catch{}return ka||(ka={}),ka}function P1(t){return Array.isArray(t.applications)}function K1(){let t=aw();if(P1(t))return t.applications;let e=[];for(let A of Object.values(t))A.applications&&e.push(...A.applications);return e}function T1(t){if(!t||!t.questions||t.questions.length===0)return;let e=aw(),A=t.jobId||"unknown",i={applicationId:`${A}_${Date.now()}`,date:new Date().toISOString(),result:t.result||"submitted",formPages:t.formPages||null,duration:t.duration||null,retries:t.retries||0,failedField:t.failedField||null,questionCount:t.questions.length,questions:t.questions.map(n=>{let s={type:n.type||"input",question:n.labelText||n.question||"",answer:n.answer||""};return n.options&&(n.options.length<=CX?s.options=n.options:s.optionsOmitted=!0),n.page&&(s.page=n.page),n.wasPreFilled&&(s.wasPreFilled=!0),n.wasRetry&&(s.wasRetry=!0),s})};P1(e)?(i.jobId=A,i.jobTitle=t.jobTitle||null,i.jobCompany=t.jobCompany||null,i.jobUrl=t.jobUrl||null,e.applications.push(i)):(e[A]||(e[A]={applications:[]}),e[A].applications.push(i));try{Ra(iw,e)}catch(n){console.error(`[!] Failed to save application-questions.json: ${n.message}`)}}function O1(){let t=K1(),e=new Map;for(let n of t)for(let s of n.questions||[]){let o=s.question.toLowerCase().trim();if(!o)continue;e.has(o)||e.set(o,{question:s.question,count:0,answers:new Map});let g=e.get(o);g.count++;let u=(s.answer||"").trim();g.answers.set(u,(g.answers.get(u)||0)+1)}let A=[...e.values()].sort((n,s)=>s.count-n.count),r=A.slice(0,15).map(n=>({question:n.question,count:n.count,topAnswer:[...n.answers.entries()].sort((s,o)=>o[1]-s[1])[0]?.[0]||""})),i=A.filter(n=>n.answers.size>1&&n.count>=3).map(n=>({question:n.question,count:n.count,answers:[...n.answers.entries()].sort((s,o)=>o[1]-s[1]).map(([s,o])=>`${s} (${o}x)`)}));return{totalApplications:t.length,uniqueQuestions:e.size,topQuestions:r,inconsistent:i}}function H1(t){if(rt.existsSync(mt.join(mi,".git")))try{let e={cwd:mi,stdio:"pipe",timeout:1e4};Aw("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",e);try{Aw("git diff --cached --quiet",e);return}catch{}let A=(t||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Aw(`git commit -m "${A}"`,e)}catch(e){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${e.message?.slice(0,80)}`)}}var gX,uX,mi,tw,rw,S1,zE,F1,iw,Yl,jl,eu,Au,vs,Ma,tu,ka,nw,CX,EX,gw=XE(()=>{gX=aX(import.meta.url),uX=mt.dirname(mt.dirname(gX)),mi=process.env.DATA_DIR?mt.resolve(process.env.DATA_DIR,"collected-profiles"):mt.join(uX,"collected-profiles"),tw=mt.join(mi,"people.json"),rw=mt.join(mi,"jobs.json"),S1=mt.join(mi,"quota.json"),zE=mt.join(mi,"conversations.json"),F1=mt.join(mi,"sync-state.json"),iw=mt.join(mi,"application-questions.json"),Yl=20,jl=100,eu=null,Au=null,vs=null,Ma=null,tu=null,ka=null;nw=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];CX=50;EX={loadPeople:Rt,savePeople:In,loadJobs:$E,saveJobs:eB,loadConversations:Zt,saveConversations:Pr,upsertPerson:sw,upsertJob:b1,linkPersonToJob:v1,addEncounter:k1,getPersonStatus:M1,updateConnectionStatus:R1,migrateFromDailyFiles:L1,loadQuota:AB,saveQuota:ow,recordConnectionSent:_1,canSendConnection:N1,getRecentConnections:tB,getQuotaStatus:x1,loadSyncState:U1,saveSyncState:G1,commitDataSnapshot:H1,logApplicationQuestions:T1,getQuestionStats:O1}});var z1=w((Wke,Z1)=>{var nu=1e3,su=nu*60,ou=su*60,Na=ou*24,FX=Na*7,bX=Na*365.25;Z1.exports=function(t,e){e=e||{};var A=typeof t;if(A==="string"&&t.length>0)return vX(t);if(A==="number"&&isFinite(t))return e.long?MX(t):kX(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function vX(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var A=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return A*bX;case"weeks":case"week":case"w":return A*FX;case"days":case"day":case"d":return A*Na;case"hours":case"hour":case"hrs":case"hr":case"h":return A*ou;case"minutes":case"minute":case"mins":case"min":case"m":return A*su;case"seconds":case"second":case"secs":case"sec":case"s":return A*nu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return}}}}function kX(t){var e=Math.abs(t);return e>=Na?Math.round(t/Na)+"d":e>=ou?Math.round(t/ou)+"h":e>=su?Math.round(t/su)+"m":e>=nu?Math.round(t/nu)+"s":t+"ms"}function MX(t){var e=Math.abs(t);return e>=Na?rB(t,e,Na,"day"):e>=ou?rB(t,e,ou,"hour"):e>=su?rB(t,e,su,"minute"):e>=nu?rB(t,e,nu,"second"):t+" ms"}function rB(t,e,A,r){var i=e>=A*1.5;return Math.round(t/A)+" "+r+(i?"s":"")}});var Iw=w((Vke,$1)=>{function RX(t){A.debug=A,A.default=A,A.coerce=g,A.disable=n,A.enable=i,A.enabled=s,A.humanize=z1(),A.destroy=u,Object.keys(t).forEach(a=>{A[a]=t[a]}),A.names=[],A.skips=[],A.formatters={};function e(a){let I=0;for(let l=0;l<a.length;l++)I=(I<<5)-I+a.charCodeAt(l),I|=0;return A.colors[Math.abs(I)%A.colors.length]}A.selectColor=e;function A(a){let I,l=null,c,C;function E(...B){if(!E.enabled)return;let h=E,Q=Number(new Date),d=Q-(I||Q);h.diff=d,h.prev=I,h.curr=Q,I=Q,B[0]=A.coerce(B[0]),typeof B[0]!="string"&&B.unshift("%O");let p=0;B[0]=B[0].replace(/%([a-zA-Z%])/g,(F,y)=>{if(F==="%%")return"%";p++;let D=A.formatters[y];if(typeof D=="function"){let S=B[p];F=D.call(h,S),B.splice(p,1),p--}return F}),A.formatArgs.call(h,B),(h.log||A.log).apply(h,B)}return E.namespace=a,E.useColors=A.useColors(),E.color=A.selectColor(a),E.extend=r,E.destroy=A.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>l!==null?l:(c!==A.namespaces&&(c=A.namespaces,C=A.enabled(a)),C),set:B=>{l=B}}),typeof A.init=="function"&&A.init(E),E}function r(a,I){let l=A(this.namespace+(typeof I>"u"?":":I)+a);return l.log=this.log,l}function i(a){A.save(a),A.namespaces=a,A.names=[],A.skips=[];let I,l=(typeof a=="string"?a:"").split(/[\s,]+/),c=l.length;for(I=0;I<c;I++)l[I]&&(a=l[I].replace(/\*/g,".*?"),a[0]==="-"?A.skips.push(new RegExp("^"+a.slice(1)+"$")):A.names.push(new RegExp("^"+a+"$")))}function n(){let a=[...A.names.map(o),...A.skips.map(o).map(I=>"-"+I)].join(",");return A.enable(""),a}function s(a){if(a[a.length-1]==="*")return!0;let I,l;for(I=0,l=A.skips.length;I<l;I++)if(A.skips[I].test(a))return!1;for(I=0,l=A.names.length;I<l;I++)if(A.names[I].test(a))return!0;return!1}function o(a){return a.toString().substring(2,a.toString().length-2).replace(/\.\*\?$/,"*")}function g(a){return a instanceof Error?a.stack||a.message:a}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return A.enable(A.load()),A}$1.exports=RX});var ex=w((si,iB)=>{si.formatArgs=NX;si.save=xX;si.load=LX;si.useColors=_X;si.storage=UX();si.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();si.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function _X(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function NX(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+iB.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let A=0,r=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(A++,i==="%c"&&(r=A))}),t.splice(r,0,e)}si.log=console.debug||console.log||(()=>{});function xX(t){try{t?si.storage.setItem("debug",t):si.storage.removeItem("debug")}catch{}}function LX(){let t;try{t=si.storage.getItem("debug")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function UX(){try{return localStorage}catch{}}iB.exports=Iw()(si);var{formatters:GX}=iB.exports;GX.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var tx=w((Xke,Ax)=>{"use strict";Ax.exports=(t,e)=>{e=e||process.argv;let A=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(A+t),i=e.indexOf("--");return r!==-1&&(i===-1?!0:r<i)}});var ix=w((Zke,rx)=>{"use strict";var PX=Y("os"),En=tx(),ir=process.env,au;En("no-color")||En("no-colors")||En("color=false")?au=!1:(En("color")||En("colors")||En("color=true")||En("color=always"))&&(au=!0);"FORCE_COLOR"in ir&&(au=ir.FORCE_COLOR.length===0||parseInt(ir.FORCE_COLOR,10)!==0);function KX(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function TX(t){if(au===!1)return 0;if(En("color=16m")||En("color=full")||En("color=truecolor"))return 3;if(En("color=256"))return 2;if(t&&!t.isTTY&&au!==!0)return 0;let e=au?1:0;if(process.platform==="win32"){let A=PX.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(A[0])>=10&&Number(A[2])>=10586?Number(A[2])>=14931?3:2:1}if("CI"in ir)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(A=>A in ir)||ir.CI_NAME==="codeship"?1:e;if("TEAMCITY_VERSION"in ir)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ir.TEAMCITY_VERSION)?1:0;if(ir.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ir){let A=parseInt((ir.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ir.TERM_PROGRAM){case"iTerm.app":return A>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ir.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ir.TERM)||"COLORTERM"in ir?1:(ir.TERM==="dumb",e)}function Cw(t){let e=TX(t);return KX(e)}rx.exports={supportsColor:Cw,stdout:Cw(process.stdout),stderr:Cw(process.stderr)}});var sx=w((_t,sB)=>{var OX=Y("tty"),nB=Y("util");_t.init=VX;_t.log=jX;_t.formatArgs=JX;_t.save=qX;_t.load=WX;_t.useColors=HX;_t.destroy=nB.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");_t.colors=[6,2,3,4,5,1];try{let t=ix();t&&(t.stderr||t).level>=2&&(_t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}_t.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let A=e.substring(6).toLowerCase().replace(/_([a-z])/g,(i,n)=>n.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[A]=r,t},{});function HX(){return"colors"in _t.inspectOpts?!!_t.inspectOpts.colors:OX.isatty(process.stderr.fd)}function JX(t){let{namespace:e,useColors:A}=this;if(A){let r=this.color,i="\x1B[3"+(r<8?r:"8;5;"+r),n=` ${i};1m${e} \x1B[0m`;t[0]=n+t[0].split(`
|
|
4
|
+
Migration complete!`),console.log(` People: ${Object.keys(e).length} total (${r} new)`),console.log(` Jobs: ${Object.keys(A).length} total (${i} new)`),{people:Object.keys(e).length,jobs:Object.keys(A).length}}function U1(){return tu||(Si(),tu=ql(F1,"sync-state.json")||{},tu)}function G1(t){Si(),tu=t;try{Ra(F1,t)}catch(e){console.error(`[!] Failed to save sync-state.json: ${e.message}`)}}function aw(){if(ka)return ka;Si();try{rt.existsSync(iw)&&(ka=JSON.parse(rt.readFileSync(iw,"utf-8")))}catch{}return ka||(ka={}),ka}function P1(t){return Array.isArray(t.applications)}function K1(){let t=aw();if(P1(t))return t.applications;let e=[];for(let A of Object.values(t))A.applications&&e.push(...A.applications);return e}function T1(t){if(!t||!t.questions||t.questions.length===0)return;let e=aw(),A=t.jobId||"unknown",i={applicationId:`${A}_${Date.now()}`,date:new Date().toISOString(),result:t.result||"submitted",formPages:t.formPages||null,duration:t.duration||null,retries:t.retries||0,failedField:t.failedField||null,questionCount:t.questions.length,questions:t.questions.map(n=>{let s={type:n.type||"input",question:n.labelText||n.question||"",answer:n.answer||""};return n.options&&(n.options.length<=CX?s.options=n.options:s.optionsOmitted=!0),n.page&&(s.page=n.page),n.wasPreFilled&&(s.wasPreFilled=!0),n.wasRetry&&(s.wasRetry=!0),typeof n.isRequired=="boolean"&&(s.isRequired=n.isRequired),n.wasOptional&&(s.wasOptional=!0),s})};P1(e)?(i.jobId=A,i.jobTitle=t.jobTitle||null,i.jobCompany=t.jobCompany||null,i.jobUrl=t.jobUrl||null,e.applications.push(i)):(e[A]||(e[A]={applications:[]}),e[A].applications.push(i));try{Ra(iw,e)}catch(n){console.error(`[!] Failed to save application-questions.json: ${n.message}`)}}function O1(){let t=K1(),e=new Map;for(let n of t)for(let s of n.questions||[]){let o=s.question.toLowerCase().trim();if(!o)continue;e.has(o)||e.set(o,{question:s.question,count:0,answers:new Map});let g=e.get(o);g.count++;let u=(s.answer||"").trim();g.answers.set(u,(g.answers.get(u)||0)+1)}let A=[...e.values()].sort((n,s)=>s.count-n.count),r=A.slice(0,15).map(n=>({question:n.question,count:n.count,topAnswer:[...n.answers.entries()].sort((s,o)=>o[1]-s[1])[0]?.[0]||""})),i=A.filter(n=>n.answers.size>1&&n.count>=3).map(n=>({question:n.question,count:n.count,answers:[...n.answers.entries()].sort((s,o)=>o[1]-s[1]).map(([s,o])=>`${s} (${o}x)`)}));return{totalApplications:t.length,uniqueQuestions:e.size,topQuestions:r,inconsistent:i}}function H1(t){if(rt.existsSync(mt.join(mi,".git")))try{let e={cwd:mi,stdio:"pipe",timeout:1e4};Aw("git add conversations.json people.json jobs.json quota.json sync-state.json run-log.json application-questions.json",e);try{Aw("git diff --cached --quiet",e);return}catch{}let A=(t||`sync ${new Date().toISOString().slice(0,16)}`).replace(/"/g,'\\"');Aw(`git commit -m "${A}"`,e)}catch(e){process.env.VERBOSE&&console.log(` [git] snapshot skipped: ${e.message?.slice(0,80)}`)}}var gX,uX,mi,tw,rw,S1,zE,F1,iw,Yl,jl,eu,Au,vs,Ma,tu,ka,nw,CX,EX,gw=XE(()=>{gX=aX(import.meta.url),uX=mt.dirname(mt.dirname(gX)),mi=process.env.DATA_DIR?mt.resolve(process.env.DATA_DIR,"collected-profiles"):mt.join(uX,"collected-profiles"),tw=mt.join(mi,"people.json"),rw=mt.join(mi,"jobs.json"),S1=mt.join(mi,"quota.json"),zE=mt.join(mi,"conversations.json"),F1=mt.join(mi,"sync-state.json"),iw=mt.join(mi,"application-questions.json"),Yl=20,jl=100,eu=null,Au=null,vs=null,Ma=null,tu=null,ka=null;nw=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge"];CX=50;EX={loadPeople:Rt,savePeople:In,loadJobs:$E,saveJobs:eB,loadConversations:Zt,saveConversations:Pr,upsertPerson:sw,upsertJob:b1,linkPersonToJob:v1,addEncounter:k1,getPersonStatus:M1,updateConnectionStatus:R1,migrateFromDailyFiles:L1,loadQuota:AB,saveQuota:ow,recordConnectionSent:_1,canSendConnection:N1,getRecentConnections:tB,getQuotaStatus:x1,loadSyncState:U1,saveSyncState:G1,commitDataSnapshot:H1,logApplicationQuestions:T1,getQuestionStats:O1}});var z1=w((Wke,Z1)=>{var nu=1e3,su=nu*60,ou=su*60,Na=ou*24,FX=Na*7,bX=Na*365.25;Z1.exports=function(t,e){e=e||{};var A=typeof t;if(A==="string"&&t.length>0)return vX(t);if(A==="number"&&isFinite(t))return e.long?MX(t):kX(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function vX(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var A=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return A*bX;case"weeks":case"week":case"w":return A*FX;case"days":case"day":case"d":return A*Na;case"hours":case"hour":case"hrs":case"hr":case"h":return A*ou;case"minutes":case"minute":case"mins":case"min":case"m":return A*su;case"seconds":case"second":case"secs":case"sec":case"s":return A*nu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return A;default:return}}}}function kX(t){var e=Math.abs(t);return e>=Na?Math.round(t/Na)+"d":e>=ou?Math.round(t/ou)+"h":e>=su?Math.round(t/su)+"m":e>=nu?Math.round(t/nu)+"s":t+"ms"}function MX(t){var e=Math.abs(t);return e>=Na?rB(t,e,Na,"day"):e>=ou?rB(t,e,ou,"hour"):e>=su?rB(t,e,su,"minute"):e>=nu?rB(t,e,nu,"second"):t+" ms"}function rB(t,e,A,r){var i=e>=A*1.5;return Math.round(t/A)+" "+r+(i?"s":"")}});var Iw=w((Vke,$1)=>{function RX(t){A.debug=A,A.default=A,A.coerce=g,A.disable=n,A.enable=i,A.enabled=s,A.humanize=z1(),A.destroy=u,Object.keys(t).forEach(a=>{A[a]=t[a]}),A.names=[],A.skips=[],A.formatters={};function e(a){let I=0;for(let l=0;l<a.length;l++)I=(I<<5)-I+a.charCodeAt(l),I|=0;return A.colors[Math.abs(I)%A.colors.length]}A.selectColor=e;function A(a){let I,l=null,c,C;function E(...B){if(!E.enabled)return;let h=E,Q=Number(new Date),d=Q-(I||Q);h.diff=d,h.prev=I,h.curr=Q,I=Q,B[0]=A.coerce(B[0]),typeof B[0]!="string"&&B.unshift("%O");let p=0;B[0]=B[0].replace(/%([a-zA-Z%])/g,(F,y)=>{if(F==="%%")return"%";p++;let D=A.formatters[y];if(typeof D=="function"){let S=B[p];F=D.call(h,S),B.splice(p,1),p--}return F}),A.formatArgs.call(h,B),(h.log||A.log).apply(h,B)}return E.namespace=a,E.useColors=A.useColors(),E.color=A.selectColor(a),E.extend=r,E.destroy=A.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>l!==null?l:(c!==A.namespaces&&(c=A.namespaces,C=A.enabled(a)),C),set:B=>{l=B}}),typeof A.init=="function"&&A.init(E),E}function r(a,I){let l=A(this.namespace+(typeof I>"u"?":":I)+a);return l.log=this.log,l}function i(a){A.save(a),A.namespaces=a,A.names=[],A.skips=[];let I,l=(typeof a=="string"?a:"").split(/[\s,]+/),c=l.length;for(I=0;I<c;I++)l[I]&&(a=l[I].replace(/\*/g,".*?"),a[0]==="-"?A.skips.push(new RegExp("^"+a.slice(1)+"$")):A.names.push(new RegExp("^"+a+"$")))}function n(){let a=[...A.names.map(o),...A.skips.map(o).map(I=>"-"+I)].join(",");return A.enable(""),a}function s(a){if(a[a.length-1]==="*")return!0;let I,l;for(I=0,l=A.skips.length;I<l;I++)if(A.skips[I].test(a))return!1;for(I=0,l=A.names.length;I<l;I++)if(A.names[I].test(a))return!0;return!1}function o(a){return a.toString().substring(2,a.toString().length-2).replace(/\.\*\?$/,"*")}function g(a){return a instanceof Error?a.stack||a.message:a}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return A.enable(A.load()),A}$1.exports=RX});var ex=w((si,iB)=>{si.formatArgs=NX;si.save=xX;si.load=LX;si.useColors=_X;si.storage=UX();si.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();si.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function _X(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function NX(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+iB.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let A=0,r=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(A++,i==="%c"&&(r=A))}),t.splice(r,0,e)}si.log=console.debug||console.log||(()=>{});function xX(t){try{t?si.storage.setItem("debug",t):si.storage.removeItem("debug")}catch{}}function LX(){let t;try{t=si.storage.getItem("debug")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function UX(){try{return localStorage}catch{}}iB.exports=Iw()(si);var{formatters:GX}=iB.exports;GX.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var tx=w((Xke,Ax)=>{"use strict";Ax.exports=(t,e)=>{e=e||process.argv;let A=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(A+t),i=e.indexOf("--");return r!==-1&&(i===-1?!0:r<i)}});var ix=w((Zke,rx)=>{"use strict";var PX=Y("os"),En=tx(),ir=process.env,au;En("no-color")||En("no-colors")||En("color=false")?au=!1:(En("color")||En("colors")||En("color=true")||En("color=always"))&&(au=!0);"FORCE_COLOR"in ir&&(au=ir.FORCE_COLOR.length===0||parseInt(ir.FORCE_COLOR,10)!==0);function KX(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function TX(t){if(au===!1)return 0;if(En("color=16m")||En("color=full")||En("color=truecolor"))return 3;if(En("color=256"))return 2;if(t&&!t.isTTY&&au!==!0)return 0;let e=au?1:0;if(process.platform==="win32"){let A=PX.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(A[0])>=10&&Number(A[2])>=10586?Number(A[2])>=14931?3:2:1}if("CI"in ir)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(A=>A in ir)||ir.CI_NAME==="codeship"?1:e;if("TEAMCITY_VERSION"in ir)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ir.TEAMCITY_VERSION)?1:0;if(ir.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ir){let A=parseInt((ir.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ir.TERM_PROGRAM){case"iTerm.app":return A>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ir.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ir.TERM)||"COLORTERM"in ir?1:(ir.TERM==="dumb",e)}function Cw(t){let e=TX(t);return KX(e)}rx.exports={supportsColor:Cw,stdout:Cw(process.stdout),stderr:Cw(process.stderr)}});var sx=w((_t,sB)=>{var OX=Y("tty"),nB=Y("util");_t.init=VX;_t.log=jX;_t.formatArgs=JX;_t.save=qX;_t.load=WX;_t.useColors=HX;_t.destroy=nB.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");_t.colors=[6,2,3,4,5,1];try{let t=ix();t&&(t.stderr||t).level>=2&&(_t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}_t.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let A=e.substring(6).toLowerCase().replace(/_([a-z])/g,(i,n)=>n.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[A]=r,t},{});function HX(){return"colors"in _t.inspectOpts?!!_t.inspectOpts.colors:OX.isatty(process.stderr.fd)}function JX(t){let{namespace:e,useColors:A}=this;if(A){let r=this.color,i="\x1B[3"+(r<8?r:"8;5;"+r),n=` ${i};1m${e} \x1B[0m`;t[0]=n+t[0].split(`
|
|
5
5
|
`).join(`
|
|
6
6
|
`+n),t.push(i+"m+"+sB.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=YX()+e+" "+t[0]}function YX(){return _t.inspectOpts.hideDate?"":new Date().toISOString()+" "}function jX(...t){return process.stderr.write(nB.formatWithOptions(_t.inspectOpts,...t)+`
|
|
7
7
|
`)}function qX(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function WX(){return process.env.DEBUG}function VX(t){t.inspectOpts={};let e=Object.keys(_t.inspectOpts);for(let A=0;A<e.length;A++)t.inspectOpts[e[A]]=_t.inspectOpts[e[A]]}sB.exports=Iw()(_t);var{formatters:nx}=sB.exports;nx.o=function(t){return this.inspectOpts.colors=this.useColors,nB.inspect(t,this.inspectOpts).split(`
|