ilml-plugin-linkedin 1.14.4 → 1.15.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 +6 -0
- package/dist/applyQueue.mjs +34 -34
- package/dist/connect.mjs +70 -70
- package/dist/daily.mjs +29 -29
- package/dist/enrichProfile.mjs +1 -1
- package/dist/enrichProfiles.mjs +48 -48
- package/dist/funnelRunner.mjs +58 -58
- package/dist/messageBot.mjs +68 -68
- package/dist/migrationCli.mjs +25 -25
- package/dist/profileHistory.mjs +5 -5
- package/dist/quota.mjs +45 -5
- package/dist/run.mjs +60 -60
- package/dist/scout.mjs +35 -35
- package/dist/syncAll.mjs +103 -103
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +37 -37
- package/dist/visit.mjs +47 -47
- package/dist/warmScan.mjs +2 -2
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/enrichProfiles.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var zt=Object.defineProperty;var st=(e,t)=>()=>(e&&(t=e(e=0)),t);var le=(e,t)=>{for(var n in t)zt(e,n,{get:t[n],enumerable:!0})};async function k(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function rt(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let s=o.innerText||"",r=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"),i=s.includes("Get hired faster")||s.includes("Get hired 2x");if(r||l||i){let a=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(a)return a.click(),{dismissed:!0,matched:s.substring(0,80)};let f=o.querySelectorAll("button");for(let c of f){let m=c.innerText?.trim().toLowerCase()||"",d=c.getAttribute("aria-label")?.toLowerCase()||"";if(m==="not now"||m==="no thanks"||m==="dismiss"||d.includes("dismiss"))return c.click(),{dismissed:!0,matched:s.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var ae=st(()=>{});var gt={};le(gt,{extractCertificationsFromDetails:()=>In,extractEducationFromDetails:()=>An,extractExperienceFromDetails:()=>$n,extractFeaturedFromDetails:()=>En,extractRecommendationsFromDetails:()=>Tn,extractSkillsFromDetails:()=>_n});async function $n(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let r=0;r<5;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(900);await k(1e3);let s=0;for(;s<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)s++,await k(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);return await e.evaluate(()=>{let r=document.querySelector("main");if(!r)return[];function l(c){let m=[];for(let d of c.querySelectorAll("div")){let p=Array.from(d.children).filter(b=>b.tagName==="DIV");if(p.length<3)continue;let v=p.filter(b=>(b.textContent||"").trim().length>50);v.length<3||(d.textContent||"").length<500||m.push({el:d,count:v.length,totalText:(d.textContent||"").length})}return m.sort((d,p)=>p.count-d.count||d.totalText-p.totalText),m[0]?.el}let i=l(r);if(!i)return[];let a=Array.from(i.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function f(c){let m=c[0]||null,d=null,p=null;if(c[1]){let y=c[1].split("\xB7").map(A=>A.trim());d=y[0]||null,y[1]&&(p=y[1])}let v=c.findIndex(y=>/(\d{4}|present)/i.test(y)&&/(-|–|—)/i.test(y)&&y.length<80),b=null,E=null;if(v>=0){let y=c[v].split("\xB7").map(A=>A.trim());b=y[0]||null,y[1]&&(E=y[1])}let G=null,be=-1;if(v>=0&&c[v+1]){let y=c[v+1],A=/^[>*\-•]|^>/.test(y),oe=/https?:\/\//.test(y),T=/\d{4}/.test(y),me=/,/.test(y)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(y);!A&&!oe&&!T&&y.length<100&&me&&(G=y,be=v+1)}let $=null,ne=-1,q=c[c.length-1];if(q&&/and\s+\+\d+\s+skills?$/i.test(q)){ne=c.length-1;let y=q.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);y&&($={listed:y[1].split(",").map(A=>A.trim()),additional:parseInt(y[2],10)})}let Y=new Set([0,1,v,be,ne].filter(y=>y>=0)),I=c.filter((y,A)=>!Y.has(A)),Se=I.length>0?I.join(`
|
|
2
2
|
|
|
3
|
-
`):null;return{title:m,company:d,employmentType:p,dates:b,duration:E,location:
|
|
4
|
-
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return f(d)}).filter(c=>c.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function
|
|
5
|
-
${
|
|
3
|
+
`):null;return{title:m,company:d,employmentType:p,dates:b,duration:E,location:G,description:Se,skills:$,_raw:c}}return a.map(c=>{let d=(c.innerText||"").trim().split(`
|
|
4
|
+
`).map(p=>p.trim()).filter(p=>p&&p.length<5e3);return f(d)}).filter(c=>c.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function ce(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let s=e.url();if(/\/(login|authwall|checkpoint)/i.test(s))throw new Error(`Session expired \u2014 bounced to ${s} when fetching /details/${n}/`);if(!s.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${s})`);for(let l=0;l<4;l++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(700);await k(800);let r=0;for(;r<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)r++,await k(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await k(600)}async function de(e,t,n,o){try{return await o()}catch(s){let r=s.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(r))throw s;return/not available on profile/i.test(r)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${r.slice(0,120)}`),[])}}async function En(e,t){return de(t,"featured","extractFeaturedFromDetails",async()=>(await ce(e,t,"featured"),await e.evaluate(`(() => {
|
|
5
|
+
${ue}
|
|
6
6
|
|
|
7
7
|
const main = document.querySelector('main');
|
|
8
8
|
if (!main) return [];
|
|
@@ -42,8 +42,8 @@ var Gt=Object.defineProperty;var nt=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{
|
|
|
42
42
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
43
43
|
return true;
|
|
44
44
|
});
|
|
45
|
-
})()`)))}async function
|
|
46
|
-
${
|
|
45
|
+
})()`)))}async function An(e,t){return de(t,"education","extractEducationFromDetails",async()=>(await ce(e,t,"education"),await e.evaluate(`(() => {
|
|
46
|
+
${ue}
|
|
47
47
|
|
|
48
48
|
const main = document.querySelector('main');
|
|
49
49
|
if (!main) return [];
|
|
@@ -79,8 +79,8 @@ var Gt=Object.defineProperty;var nt=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{
|
|
|
79
79
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
80
80
|
return true;
|
|
81
81
|
});
|
|
82
|
-
})()`)))}async function
|
|
83
|
-
${
|
|
82
|
+
})()`)))}async function _n(e,t){return de(t,"skills","extractSkillsFromDetails",async()=>(await ce(e,t,"skills"),await e.evaluate(`(() => {
|
|
83
|
+
${ue}
|
|
84
84
|
|
|
85
85
|
const main = document.querySelector('main');
|
|
86
86
|
if (!main) return [];
|
|
@@ -111,8 +111,8 @@ var Gt=Object.defineProperty;var nt=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{
|
|
|
111
111
|
skills.push({ name, endorsements, _raw: lines });
|
|
112
112
|
}
|
|
113
113
|
return skills;
|
|
114
|
-
})()`)))}async function
|
|
115
|
-
${
|
|
114
|
+
})()`)))}async function In(e,t){return de(t,"certifications","extractCertificationsFromDetails",async()=>(await ce(e,t,"certifications"),await e.evaluate(`(() => {
|
|
115
|
+
${ue}
|
|
116
116
|
|
|
117
117
|
const main = document.querySelector('main');
|
|
118
118
|
if (!main) return [];
|
|
@@ -136,8 +136,8 @@ var Gt=Object.defineProperty;var nt=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{
|
|
|
136
136
|
|
|
137
137
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
138
138
|
}).filter(e => e.name);
|
|
139
|
-
})()`)))}async function
|
|
140
|
-
${
|
|
139
|
+
})()`)))}async function Tn(e,t){return de(t,"recommendations","extractRecommendationsFromDetails",async()=>(await ce(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
140
|
+
${ue}
|
|
141
141
|
|
|
142
142
|
const main = document.querySelector('main');
|
|
143
143
|
if (!main) return [];
|
|
@@ -172,7 +172,7 @@ var Gt=Object.defineProperty;var nt=(e,t)=>()=>(e&&(t=e(e=0)),t);var pe=(e,t)=>{
|
|
|
172
172
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
173
173
|
return true;
|
|
174
174
|
});
|
|
175
|
-
})()`)))}var
|
|
175
|
+
})()`)))}var ue,yt=st(()=>{ae();ue=`
|
|
176
176
|
function findEntryContainer(root) {
|
|
177
177
|
const candidates = [];
|
|
178
178
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -235,57 +235,57 @@ function findEntryContainer(root) {
|
|
|
235
235
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
236
236
|
return candidates[0]?.el;
|
|
237
237
|
}
|
|
238
|
-
`});import
|
|
239
|
-
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=
|
|
238
|
+
`});import sn from"puppeteer";import{addExtra as rn}from"puppeteer-extra";import ln from"puppeteer-extra-plugin-stealth";ae();import{getPluginConfig as Qt}from"@ilivemylife/graph-sdk";var Xt=await Qt();for(let[e,t]of Object.entries(Xt))process.env[e]===void 0&&(process.env[e]=t);var Zt=process.env.LINKEDIN_NAME,K=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Qo=Object.freeze(new Set([K.DRAFT,K.CONFIRMED,K.NEEDS_REVIEW])),en=Object.freeze(new Set([K.DRAFT,K.CONFIRMED,K.REJECTED,K.NEEDS_REVIEW]));import it from"fs";import tn from"path";var nn="cookies.json";function on(){let e=process.env.ILML_SCOPE_DIR;return e?tn.join(e,"plugins-state","linkedin","cookies.json"):nn}function lt(){let e=on();if(!it.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=it.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}var at=rn(sn);at.use(ln());async function ct(){let e=await at.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
|
|
239
|
+
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=lt();await n.setCookie(...o),console.log(" Browser launched, cookies loaded.")}catch(o){console.error(`
|
|
240
240
|
[!] ${o.message}
|
|
241
|
-
`),await e.close(),process.exit(1)}return{browser:e,page:n}}ie();import"dotenv/config";import*as C from"fs";import*as x from"path";import{fileURLToPath as sn}from"url";var rn=sn(import.meta.url),ln=x.dirname(x.dirname(rn)),q=process.env.DATA_DIR?x.resolve(process.env.DATA_DIR,"collected-profiles"):x.join(ln,"collected-profiles"),ke=x.join(q,"people.json"),is=x.join(q,"jobs.json"),ls=x.join(q,"quota.json"),ut=x.join(q,"conversations.json"),as=x.join(q,"sync-state.json"),cs=x.join(q,"application-questions.json"),Ce=x.join(q,"profile-history"),dt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},us=dt(process.env.CONNECT_MAX_DAILY,20),ds=dt(process.env.CONNECT_MAX_WEEKLY,100),se=null,an=null,cn=null,oe=null,un=null,dn=null;function ft(){se=null,an=null,cn=null,oe=null,un=null,dn=null}function xe(){C.existsSync(q)||C.mkdirSync(q,{recursive:!0})}function $e(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";C.writeFileSync(o,n);for(let s=0;s<3;s++)try{C.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function Ee(e,t){if(!C.existsSync(e))return null;try{let n=JSON.parse(C.readFileSync(e,"utf-8"));try{C.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${x.resolve(e)}`);let o=e+".backup";if(C.existsSync(o))try{let s=JSON.parse(C.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{C.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{C.copyFileSync(e,e+".corrupted")}catch{}return null}}function fn(){return new Date().toISOString().split("T")[0]}var mn=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],pn=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function Ae(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function hn(){C.existsSync(Ce)||C.mkdirSync(Ce,{recursive:!0})}function mt(e){let t=Ae(e);return t?x.join(Ce,`${t}.json`):null}function gn(e){let t=mt(e);return t?Ee(t,`profile-history/${Ae(e)}.json`)||[]:[]}function yn(e,t){let n=mt(e);if(!n)return;hn();let o=gn(e);o.unshift(t);try{$e(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${Ae(e)}: ${s.message}`)}}function at(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function ct(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function wn(e,t){if(!e)return[];let n=[];for(let o of pn){let s=e[o],r=t[o];at(s)||at(r)||ct(s)!==ct(r)&&n.push(o)}return n}function bn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function K(){return se||(xe(),se=Ee(ke,"people.json")||{},se)}function Sn(e){xe(),se=e;try{$e(ke,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${x.resolve(ke)}`)}}function _e(){return oe||(xe(),oe=Ee(ut,"conversations.json")||{},vn(oe),oe)}function vn(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(r=>r.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{$e(ut,e)}catch{}}}function Ie(e,t={}){if(!e)return null;let n=K(),o=fn(),s=new Date().toISOString(),r=n[e];if(r){let l=wn(r,t);l.length>0&&(yn(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:l,snapshot:bn(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let i of mn)if(t[i]!=null){if(Array.isArray(t[i])&&t[i].length===0&&Array.isArray(r[i])&&r[i].length>0)continue;r[i]=t[i]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Sn(n),n[e]}async function _n(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function gt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:r=!1,extractSkills:l=!1,extractRecommendations:i=!1,extractCertifications:a=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await ot(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await _n(e,t));let c=0;for(let $=0;$<2;$++){let te=await e.evaluate(()=>document.body.scrollHeight);for(let G=1;G<=6;G++)await e.evaluate(I=>window.scrollTo(0,I),te*G/6),await k(900);let P=await e.evaluate(()=>document.body.scrollHeight);if(P===c)break;c=P}await k(800);let m=await e.evaluate(()=>{let $=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),te=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),P=h=>{let g=(h||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(g)},G={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},I=document.querySelector("main");if(!I)return G;let be=[...Array.from(I.querySelectorAll("h1")),...Array.from(I.querySelectorAll("h2"))],y=Array.from(I.querySelectorAll("h2")),A=be.find(h=>{let g=h.textContent&&h.textContent.trim(),w=(g||"").replace(/\s*\(\d+\)$/,"").trim();return g&&g.length>1&&g.length<100&&!$.has(w)&&!te.has(w)}),ne=A?A.textContent.trim():null,T=A?A.parentElement:null;for(;T&&T!==I&&!Array.from(T.children).filter(g=>g.tagName==="P").some(g=>{let w=g.textContent&&g.textContent.trim();return w&&w.length>5&&!P(w)});)T=T.parentElement;let de=null,Ve=null,He=null,Se=null;if(T&&T!==I){let h=Array.from(T.children).filter(w=>w.tagName==="P").filter(w=>{let B=w.textContent&&w.textContent.trim();return B&&B.length>5&&!P(B)});if(h[0]&&(de=h[0].textContent.trim()),h[1]){let w=h[1].textContent.trim().split(/\s*[·•]\s*/);Ve=w[0]||null,w.length>1&&(He=w.slice(1).join(" \xB7 "))}let g=Array.from(T.children).filter(w=>w.tagName==="DIV");for(let w=g.length-1;w>=0;w--){let B=g[w].textContent&&g[w].textContent.trim();if(B&&!(ne&&B.startsWith(ne))&&(Se=B.split(/[·•]/)[0].trim(),Se))break}}let We=null;if(T){let h=T.querySelectorAll("p, span, div");for(let g of h){let w=(g.textContent||"").trim().replace(/^[·•]\s*/,"");if(w==="1st"||w==="2nd"||w==="3rd"){We=w;break}}}let qt=!!I.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),Je=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ut=Je&&Je.src||null,fe=I.textContent||"",Ge=null,Ye=fe.match(/(\d+\+?)\s+connections\b/i);Ye&&(Ge=Ye[1]+" connections");let me=null,Ke=fe.match(/(\d+)\s+mutual connection/i),ze=fe.match(/and\s+(\d+)\s+other mutual/i),Bt=fe.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Ke?me=parseInt(Ke[1],10):ze?me=2+parseInt(ze[1],10):Bt&&(me=2);let Qe=null,Xe=null,Ze=y.find(h=>h.textContent&&h.textContent.trim()==="About");if(Ze){let h=Ze.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").trim();g=g.replace(/^About\s*/,"").trim();let w=g.match(/Top skills\s*(.+?)$/i);if(w){let ve=w[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Jt=>Jt.trim()).filter(Boolean);ve.length>0&&ve.length<10&&(Xe=ve)}g=g.split(/\n?…\s*more/i)[0].trim(),g=g.split(/\n?\.\.\.\s*more/i)[0].trim(),g=g.split(/\bTop skills\b/i)[0].trim(),g=g.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Qe=g||null}}let et=null,tt=y.find(h=>h.textContent&&h.textContent.trim()==="Activity");if(tt){let h=tt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);g&&(et=parseInt(g[1].replace(/,/g,""),10))}}let Vt=[...new Set(y.map(h=>(h.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(h=>h&&h.length>1&&h.length<60&&h!==ne).filter(h=>$.has(h)))],re=document.body.textContent||"",Ht=/#OpenToWork\b/i.test(re)||/\bOpen to work\b/.test(re),Wt=/#Hiring\b/i.test(re)||/\bI'?m hiring\b/i.test(re)||/\bWe are hiring\b/i.test(re);return{name:ne,title:de,location:Se,currentCompany:Ve,currentSchool:He,connectionDegree:We,hasVerifiedBadge:qt,photoUrl:Ut,connectionsLevel:Ge,mutualConnectionsCount:me,followers:et,openToWork:Ht,hiring:Wt,about:Qe,topSkills:Xe,availableSections:Vt}});console.log(`Viewed: ${m.name} - ${m.title}`);let d=null,p=null,v=null,b=null,E=null,J=null;if(o||s||r||l||i||a){let $=await Promise.resolve().then(()=>(ht(),pt));o&&(d=await $.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),s&&(p=await $.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),r&&(v=await $.extractEducationFromDetails(e,t),console.log(` + Education: ${v.length} entries`)),l&&(b=await $.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),i&&(E=await $.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${E.length} entries`)),a&&(J=await $.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${J.length} entries`))}return{...m,profileUrl:t,...d!==null&&{experience:d},...p!==null&&{featured:p},...v!==null&&{education:v},...b!==null&&{skillsFull:b},...E!==null&&{recommendations:E},...J!==null&&{certifications:J}}}catch(f){console.error(`Error viewing profile ${t}:`,f.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(f.message||""))throw f;return null}}import"dotenv/config";import*as O from"fs";import*as D from"path";import{fileURLToPath as In}from"url";var Tn=In(import.meta.url),Rn=D.dirname(D.dirname(Tn)),Q=process.env.DATA_DIR?D.resolve(process.env.DATA_DIR,"market-research"):D.join(Rn,"market-research"),$s=D.join(Q,"scouted-jobs.json"),Es=D.join(Q,"discovered-people.json"),yt=D.join(Q,"visit-log.json"),As=D.join(Q,"companies.json"),_s=D.join(Q,"job-decisions.json");function Dn(){O.existsSync(Q)||O.mkdirSync(Q,{recursive:!0})}function On(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let s=0;s<3;s++)try{O.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function jn(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function wt(){Nn=null,Ln=null,Fn=null,Mn=null,z=null}var Nn=null;var Ln=null;var Fn=null;var Mn=null;var z=null;function Te(){return z||(z=jn(yt)||{visits:[]},Array.isArray(z.visits)||(z.visits=[]),z)}function bt(e,t={}){if(!e)return;Dn();let n=Te();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(s=>new Date(s.date).getTime()>o);try{On(yt,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function St(e){let t=Te();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}ie();async function vt(e,t,n={}){let{maxVisits:o=50,delayBetween:s=4e3,skipRecentDays:r=7,verbose:l=!1,extractExperience:i=!1}=n,a={visited:0,skipped:0,errors:0},f=Date.now()-r*24*60*60*1e3;for(let c of t){if(a.visited>=o)break;if(!c.profileUrl)continue;let m=St(c.profileUrl);if(m&&new Date(m).getTime()>f){a.skipped++;continue}try{let d=await gt(e,c.profileUrl,{extractExperience:i}),p=c.source||"visit";if(d){let b={...d,source:p};i&&Array.isArray(d.experience)&&d.experience.length>0&&(b._lastEnrichedAt=new Date().toISOString()),Ie(c.profileUrl,b)}bt(c.profileUrl,{name:d?.name||c.name||null,source:p}),a.visited++,l?console.log(` [${a.visited}] ${d?.name||c.profileUrl} \u2014 ${d?.title?.slice(0,40)||"?"}`):a.visited%10===0&&console.log(` Visited: ${a.visited}`);let v=Math.random()*4e3;await k(s+v)}catch(d){a.errors++,l&&console.error(` Error visiting ${c.name||c.profileUrl}: ${d.message?.slice(0,60)}`);let p=(d.message||"").toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("session expired")||p.includes("bounced to")||p.includes("authwall")||p.includes("checkpoint")||p.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return a}import"dotenv/config";import*as j from"fs";import*as V from"path";import{fileURLToPath as Hn}from"url";import"dotenv/config";import{createGraphClient as Pn,resolveToken as qn}from"@ilivemylife/graph-sdk";import{config as Un}from"dotenv";Un();var kt=qn()||process.env.TOKEN;kt||(console.error(`
|
|
241
|
+
`),await e.close(),process.exit(1)}return{browser:e,page:n}}ae();import"dotenv/config";import*as C from"fs";import*as x from"path";import{fileURLToPath as an}from"url";var cn=an(import.meta.url),un=x.dirname(x.dirname(cn)),U=process.env.DATA_DIR?x.resolve(process.env.DATA_DIR,"collected-profiles"):x.join(un,"collected-profiles"),Ce=x.join(U,"people.json"),hs=x.join(U,"jobs.json"),gs=x.join(U,"quota.json"),ft=x.join(U,"conversations.json"),ys=x.join(U,"sync-state.json"),ws=x.join(U,"application-questions.json"),xe=x.join(U,"profile-history"),mt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},bs=mt(process.env.CONNECT_MAX_DAILY,20),Ss=mt(process.env.CONNECT_MAX_WEEKLY,100),re=null,dn=null,fn=null,se=null,mn=null,pn=null;function pt(){re=null,dn=null,fn=null,se=null,mn=null,pn=null}function $e(){C.existsSync(U)||C.mkdirSync(U,{recursive:!0})}function Ee(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";C.writeFileSync(o,n);for(let s=0;s<3;s++)try{C.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function Ae(e,t){if(!C.existsSync(e))return null;try{let n=JSON.parse(C.readFileSync(e,"utf-8"));try{C.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${x.resolve(e)}`);let o=e+".backup";if(C.existsSync(o))try{let s=JSON.parse(C.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{C.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{C.copyFileSync(e,e+".corrupted")}catch{}return null}}function hn(){return new Date().toISOString().split("T")[0]}var gn=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],yn=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function _e(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function wn(){C.existsSync(xe)||C.mkdirSync(xe,{recursive:!0})}function ht(e){let t=_e(e);return t?x.join(xe,`${t}.json`):null}function bn(e){let t=ht(e);return t?Ae(t,`profile-history/${_e(e)}.json`)||[]:[]}function Sn(e,t){let n=ht(e);if(!n)return;wn();let o=bn(e);o.unshift(t);try{Ee(n,o)}catch(s){console.error(`[!] Failed to append profile-history for ${_e(e)}: ${s.message}`)}}function ut(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function dt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function vn(e,t){if(!e)return[];let n=[];for(let o of yn){let s=e[o],r=t[o];ut(s)||ut(r)||dt(s)!==dt(r)&&n.push(o)}return n}function kn(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,s]of Object.entries(e))t.has(o)||(n[o]=s);return n}function z(){return re||($e(),re=Ae(Ce,"people.json")||{},re)}function Cn(e){$e(),re=e;try{Ee(Ce,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${x.resolve(Ce)}`)}}function Ie(){return se||($e(),se=Ae(ft,"conversations.json")||{},xn(se),se)}function xn(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(r=>r.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Ee(ft,e)}catch{}}}function Te(e,t={}){if(!e)return null;let n=z(),o=hn(),s=new Date().toISOString(),r=n[e];if(r){let l=vn(r,t);l.length>0&&(Sn(e,{capturedAt:s,previousLastUpdated:r.lastUpdated||null,changedFields:l,snapshot:kn(r)}),r.lastSnapshotAt=s),r.seenCount=(r.seenCount||1)+1,r.lastSeen=o,r.lastUpdated=s,t.source&&!r.sources?.includes(t.source)&&(r.sources=r.sources||[],r.sources.push(t.source));for(let i of gn)if(t[i]!=null){if(Array.isArray(t[i])&&t[i].length===0&&Array.isArray(r[i])&&r[i].length>0)continue;r[i]=t[i]}Array.isArray(t.availableSections)&&(r.lastFullVisitAt=s)}else n[e]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:s,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?s:null};return Cn(n),n[e]}async function Rn(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function wt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:s=!1,extractEducation:r=!1,extractSkills:l=!1,extractRecommendations:i=!1,extractCertifications:a=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await k(3e3),await rt(e)&&(console.log(" Dismissed Premium overlay"),await k(1500),await Rn(e,t));let c=0;for(let $=0;$<2;$++){let ne=await e.evaluate(()=>document.body.scrollHeight);for(let Y=1;Y<=6;Y++)await e.evaluate(I=>window.scrollTo(0,I),ne*Y/6),await k(900);let q=await e.evaluate(()=>document.body.scrollHeight);if(q===c)break;c=q}await k(800);let m=await e.evaluate(()=>{let $=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),ne=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),q=h=>{let g=(h||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(g)},Y={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},I=document.querySelector("main");if(!I)return Y;let Se=[...Array.from(I.querySelectorAll("h1")),...Array.from(I.querySelectorAll("h2"))],y=Array.from(I.querySelectorAll("h2")),A=Se.find(h=>{let g=h.textContent&&h.textContent.trim(),w=(g||"").replace(/\s*\(\d+\)$/,"").trim();return g&&g.length>1&&g.length<100&&!$.has(w)&&!ne.has(w)}),oe=A?A.textContent.trim():null,T=A?A.parentElement:null;for(;T&&T!==I&&!Array.from(T.children).filter(g=>g.tagName==="P").some(g=>{let w=g.textContent&&g.textContent.trim();return w&&w.length>5&&!q(w)});)T=T.parentElement;let me=null,Je=null,We=null,ve=null;if(T&&T!==I){let h=Array.from(T.children).filter(w=>w.tagName==="P").filter(w=>{let V=w.textContent&&w.textContent.trim();return V&&V.length>5&&!q(V)});if(h[0]&&(me=h[0].textContent.trim()),h[1]){let w=h[1].textContent.trim().split(/\s*[·•]\s*/);Je=w[0]||null,w.length>1&&(We=w.slice(1).join(" \xB7 "))}let g=Array.from(T.children).filter(w=>w.tagName==="DIV");for(let w=g.length-1;w>=0;w--){let V=g[w].textContent&&g[w].textContent.trim();if(V&&!(oe&&V.startsWith(oe))&&(ve=V.split(/[·•]/)[0].trim(),ve))break}}let Ge=null;if(T){let h=T.querySelectorAll("p, span, div");for(let g of h){let w=(g.textContent||"").trim().replace(/^[·•]\s*/,"");if(w==="1st"||w==="2nd"||w==="3rd"){Ge=w;break}}}let Vt=!!I.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),Ye=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ht=Ye&&Ye.src||null,pe=I.textContent||"",Ke=null,ze=pe.match(/(\d+\+?)\s+connections\b/i);ze&&(Ke=ze[1]+" connections");let he=null,Qe=pe.match(/(\d+)\s+mutual connection/i),Xe=pe.match(/and\s+(\d+)\s+other mutual/i),Jt=pe.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Qe?he=parseInt(Qe[1],10):Xe?he=2+parseInt(Xe[1],10):Jt&&(he=2);let Ze=null,et=null,tt=y.find(h=>h.textContent&&h.textContent.trim()==="About");if(tt){let h=tt.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").trim();g=g.replace(/^About\s*/,"").trim();let w=g.match(/Top skills\s*(.+?)$/i);if(w){let ke=w[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Kt=>Kt.trim()).filter(Boolean);ke.length>0&&ke.length<10&&(et=ke)}g=g.split(/\n?…\s*more/i)[0].trim(),g=g.split(/\n?\.\.\.\s*more/i)[0].trim(),g=g.split(/\bTop skills\b/i)[0].trim(),g=g.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ze=g||null}}let nt=null,ot=y.find(h=>h.textContent&&h.textContent.trim()==="Activity");if(ot){let h=ot.parentElement;for(;h&&h.tagName!=="SECTION";)h=h.parentElement;if(h){let g=(h.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);g&&(nt=parseInt(g[1].replace(/,/g,""),10))}}let Wt=[...new Set(y.map(h=>(h.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(h=>h&&h.length>1&&h.length<60&&h!==oe).filter(h=>$.has(h)))],ie=document.body.textContent||"",Gt=/#OpenToWork\b/i.test(ie)||/\bOpen to work\b/.test(ie),Yt=/#Hiring\b/i.test(ie)||/\bI'?m hiring\b/i.test(ie)||/\bWe are hiring\b/i.test(ie);return{name:oe,title:me,location:ve,currentCompany:Je,currentSchool:We,connectionDegree:Ge,hasVerifiedBadge:Vt,photoUrl:Ht,connectionsLevel:Ke,mutualConnectionsCount:he,followers:nt,openToWork:Gt,hiring:Yt,about:Ze,topSkills:et,availableSections:Wt}});console.log(`Viewed: ${m.name} - ${m.title}`);let d=null,p=null,v=null,b=null,E=null,G=null;if(o||s||r||l||i||a){let $=await Promise.resolve().then(()=>(yt(),gt));o&&(d=await $.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),s&&(p=await $.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${p.length} entries`)),r&&(v=await $.extractEducationFromDetails(e,t),console.log(` + Education: ${v.length} entries`)),l&&(b=await $.extractSkillsFromDetails(e,t),console.log(` + Skills: ${b.length} entries`)),i&&(E=await $.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${E.length} entries`)),a&&(G=await $.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${G.length} entries`))}return{...m,profileUrl:t,...d!==null&&{experience:d},...p!==null&&{featured:p},...v!==null&&{education:v},...b!==null&&{skillsFull:b},...E!==null&&{recommendations:E},...G!==null&&{certifications:G}}}catch(f){console.error(`Error viewing profile ${t}:`,f.message);try{await e.goto("about:blank",{timeout:1e4}),await k(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(f.message||""))throw f;return null}}import"dotenv/config";import*as O from"fs";import*as D from"path";import{fileURLToPath as Dn}from"url";var On=Dn(import.meta.url),jn=D.dirname(D.dirname(On)),X=process.env.DATA_DIR?D.resolve(process.env.DATA_DIR,"market-research"):D.join(jn,"market-research"),js=D.join(X,"scouted-jobs.json"),Ns=D.join(X,"discovered-people.json"),bt=D.join(X,"visit-log.json"),Fs=D.join(X,"companies.json"),Ls=D.join(X,"job-decisions.json");function Nn(){O.existsSync(X)||O.mkdirSync(X,{recursive:!0})}function Fn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let s=0;s<3;s++)try{O.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function Ln(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function St(){Mn=null,Pn=null,qn=null,Un=null,Q=null}var Mn=null;var Pn=null;var qn=null;var Un=null;var Q=null;function Re(){return Q||(Q=Ln(bt)||{visits:[]},Array.isArray(Q.visits)||(Q.visits=[]),Q)}function vt(e,t={}){if(!e)return;Nn();let n=Re();n.visits.push({date:new Date().toISOString(),profileUrl:e,name:t.name||null,source:t.source||"manual"});let o=Date.now()-90*24*60*60*1e3;n.visits=n.visits.filter(s=>new Date(s.date).getTime()>o);try{Fn(bt,n)}catch(s){console.error(`[!] Failed to save visit-log.json: ${s.message}`)}}function kt(e){let t=Re();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}ae();async function Ct(e,t,n={}){let{maxVisits:o=50,delayBetween:s=4e3,skipRecentDays:r=7,verbose:l=!1,extractExperience:i=!1}=n,a={visited:0,skipped:0,errors:0},f=Date.now()-r*24*60*60*1e3;for(let c of t){if(a.visited>=o)break;if(!c.profileUrl)continue;let m=kt(c.profileUrl);if(m&&new Date(m).getTime()>f){a.skipped++;continue}try{let d=await wt(e,c.profileUrl,{extractExperience:i}),p=c.source||"visit";if(d){let b={...d,source:p};i&&Array.isArray(d.experience)&&d.experience.length>0&&(b._lastEnrichedAt=new Date().toISOString()),Te(c.profileUrl,b)}vt(c.profileUrl,{name:d?.name||c.name||null,source:p}),a.visited++,l?console.log(` [${a.visited}] ${d?.name||c.profileUrl} \u2014 ${d?.title?.slice(0,40)||"?"}`):a.visited%10===0&&console.log(` Visited: ${a.visited}`);let v=Math.random()*4e3;await k(s+v)}catch(d){a.errors++,l&&console.error(` Error visiting ${c.name||c.profileUrl}: ${d.message?.slice(0,60)}`);let p=(d.message||"").toLowerCase();if(p.includes("detached")||p.includes("session closed")||p.includes("target closed")||p.includes("session expired")||p.includes("bounced to")||p.includes("authwall")||p.includes("checkpoint")||p.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return a}import"dotenv/config";import*as j from"fs";import*as H from"path";import{fileURLToPath as Gn}from"url";import"dotenv/config";import{createGraphClient as Bn,resolveToken as Vn}from"@ilivemylife/graph-sdk";import{config as Hn}from"dotenv";Hn();var xt=Vn()||process.env.TOKEN;xt||(console.error(`
|
|
242
242
|
[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.
|
|
243
243
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
244
244
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
245
|
-
`),process.exit(1));var
|
|
245
|
+
`),process.exit(1));var $t=Bn({token:xt});function Jn(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Wn({scriptName:e,mode:t,status:n,error:o,duration:s}){let r=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",l=new Date().toISOString().slice(0,16).replace("T"," "),i=s?` ${Jn(s)}`:"",a=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",f=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${f} \u2014 ${a} \u2014 ${l}${i}`}async function Et({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:r}){let l=process.env.NODE_RUN_REPORTS;if(!l||!Array.isArray(o)||o.length===0)return;let a=`**${Wn({scriptName:e,mode:t,status:n,error:s,duration:r})}**
|
|
246
246
|
|
|
247
247
|
${o.join(`
|
|
248
|
-
`)}`;try{await Ct.addMessage(l,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Wn=Hn(import.meta.url),Jn=V.dirname(V.dirname(Wn)),Re=process.env.DATA_DIR?V.resolve(process.env.DATA_DIR,"collected-profiles"):V.join(Jn,"collected-profiles"),De=V.join(Re,"run-log.json");function Gn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let s=0;s<3;s++)try{j.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function $t(){try{if(!j.existsSync(De))return{runs:[]};let e=JSON.parse(j.readFileSync(De,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Et(e){j.existsSync(Re)||j.mkdirSync(Re,{recursive:!0});try{Gn(De,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function At(e,t="default"){let n=$t();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>r),Et(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Oe(e,t,n=null,o=null){if(!e)return;let s=null;try{let l=$t(),i=l.runs[e.runIndex];if(i&&i.status==="running"&&i.script===e.script)i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=n,i.error=o,s=i.duration;else{let a=l.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration)}Et(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let r=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";xt({scriptName:e.script,mode:e.mode,status:l,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(i=>console.error(`[runLog] postRunReport failed: ${i.message}`))}}import"dotenv/config";import*as u from"fs";import*as qe from"os";import*as S from"path";import{fileURLToPath as fo}from"url";var Le={};pe(Le,{NAME:()=>Kn,VERSION:()=>Yn,up:()=>Xn});import*as N from"fs";import*as he from"path";var Yn=1,Kn="normalize-jobs-and-questions",zn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Qn=50;function je(e){return N.existsSync(e)?JSON.parse(N.readFileSync(e,"utf-8")):null}function Ne(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{N.writeFileSync(o,n)}catch(s){try{N.unlinkSync(o)}catch{}throw s}try{N.renameSync(o,e)}catch(s){try{N.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Xn(e,t){let n=he.join(e,"jobs.json"),o=he.join(t,"scouted-jobs.json"),s=he.join(e,"application-questions.json"),r=je(n)||{},l=je(o)||{},i=0,a=[];for(let c of Object.keys(r)){if(!l[c])continue;let m=l[c],d=r[c];for(let p of zn)m[p]!=null&&d[p]==null&&(d[p]=m[p]);a.push(c),i++}i>0?(Ne(n,r),console.log(` Phase 1: Merged ${i} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=je(s);if(f&&Array.isArray(f.applications)){let c={},m=0;for(let d of f.applications){let p=d.jobId||"unknown";c[p]||(c[p]={applications:[]});let v=(d.questions||[]).map(b=>{let E={type:b.type||"input",question:b.question||"",answer:b.answer||""};return b.options&&(b.options.length<=Qn?E.options=b.options:(E.optionsOmitted=!0,m++)),b.page&&(E.page=b.page),b.wasPreFilled&&(E.wasPreFilled=!0),b.wasRetry&&(E.wasRetry=!0),E});c[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||v.length,questions:v})}Ne(s,c),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let c of a)delete l[c];Ne(o,l),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Fe={};pe(Fe,{NAME:()=>eo,VERSION:()=>Zn,up:()=>oo});import*as L from"fs";import*as _t from"path";var Zn=2,eo="reset-unread-flags";function to(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function no(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(s){try{L.unlinkSync(o)}catch{}throw s}try{L.renameSync(o,e)}catch(s){try{L.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function oo(e){let t=_t.join(e,"conversations.json"),n=to(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}no(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Me={};pe(Me,{NAME:()=>ro,VERSION:()=>so,up:()=>uo});import*as F from"fs";import*as It from"path";var so=3,ro="recompute-last-message-by",io=new Set(["draft","confirmed","rejected","needs_review"]);function lo(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function ao(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(s){try{F.unlinkSync(o)}catch{}throw s}try{F.renameSync(o,e)}catch(s){try{F.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function co(e,t){if(!e||e.length===0)return"them";let n=e.filter(r=>!io.has(r.status));if(n.length===0)return"them";let o=n.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,l)=>l.t-r.t).map(r=>r.m),s=o.length>0?o:[...n].reverse();for(let r of s){let l=r.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function uo(e){let t=It.join(e,"conversations.json"),n=lo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,l=0;for(let i of Object.keys(n)){let a=n[i];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let f=Array.isArray(a.messages)?a.messages:[],c=co(f,o),m=c==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==c&&l++,a.lastMessageBy=c,a.conversationStatus=m,s++}if(s===0){console.log(" No conversations to recompute.");return}ao(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var mo=fo(import.meta.url),po=S.dirname(mo),ho=S.dirname(S.dirname(po));function go(e){return e&&(e==="~"?qe.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(qe.homedir(),e.slice(2)):e)}var M=process.env.DATA_DIR?S.resolve(go(process.env.DATA_DIR)):ho,Z=S.join(M,"collected-profiles"),ee=S.join(M,"market-research"),R=S.join(M,".schema-version"),Tt=[S.join(Z,".schema-version"),S.join(ee,".schema-version")],H=3,U=[{version:1,module:Le},{version:2,module:Fe},{version:3,module:Me}];(function(){U.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of U){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=U.length?U[U.length-1].version:0;if(n!==H)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${H}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<U.length;o++){let s=o+1;if(U[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${U[o].version}`)}})();function jt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
248
|
+
`)}`;try{await $t.addMessage(l,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Yn=Gn(import.meta.url),Kn=H.dirname(H.dirname(Yn)),De=process.env.DATA_DIR?H.resolve(process.env.DATA_DIR,"collected-profiles"):H.join(Kn,"collected-profiles"),Oe=H.join(De,"run-log.json");function zn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";j.writeFileSync(o,n);for(let s=0;s<3;s++)try{j.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let l=Date.now();for(;Date.now()-l<200;);continue}throw r}}function At(){try{if(!j.existsSync(Oe))return{runs:[]};let e=JSON.parse(j.readFileSync(Oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function _t(e){j.existsSync(De)||j.mkdirSync(De,{recursive:!0});try{zn(Oe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function It(e,t="default"){let n=At();for(let l of n.runs)l.status==="running"&&(l.status="interrupted",l.result="interrupted",l.timestamp&&(l.duration=Date.now()-new Date(l.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(l=>new Date(l.timestamp).getTime()>r),_t(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function je(e,t,n=null,o=null){if(!e)return;let s=null;try{let l=At(),i=l.runs[e.runIndex];if(i&&i.status==="running"&&i.script===e.script)i.status=t,i.result=t,i.duration=Date.now()-e.startTime,i.stats=n,i.error=o,s=i.duration;else{let a=l.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration)}_t(l)}catch(l){console.error(`[runLog] Failed to end run: ${l.message}`)}let r=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let l=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Et({scriptName:e.script,mode:e.mode,status:l,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(i=>console.error(`[runLog] postRunReport failed: ${i.message}`))}}import"dotenv/config";import*as u from"fs";import*as Be from"os";import*as S from"path";import{fileURLToPath as vo}from"url";var Le={};le(Le,{NAME:()=>Xn,VERSION:()=>Qn,up:()=>to});import*as N from"fs";import*as ge from"path";var Qn=1,Xn="normalize-jobs-and-questions",Zn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],eo=50;function Ne(e){return N.existsSync(e)?JSON.parse(N.readFileSync(e,"utf-8")):null}function Fe(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{N.writeFileSync(o,n)}catch(s){try{N.unlinkSync(o)}catch{}throw s}try{N.renameSync(o,e)}catch(s){try{N.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function to(e,t){let n=ge.join(e,"jobs.json"),o=ge.join(t,"scouted-jobs.json"),s=ge.join(e,"application-questions.json"),r=Ne(n)||{},l=Ne(o)||{},i=0,a=[];for(let c of Object.keys(r)){if(!l[c])continue;let m=l[c],d=r[c];for(let p of Zn)m[p]!=null&&d[p]==null&&(d[p]=m[p]);a.push(c),i++}i>0?(Fe(n,r),console.log(` Phase 1: Merged ${i} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Ne(s);if(f&&Array.isArray(f.applications)){let c={},m=0;for(let d of f.applications){let p=d.jobId||"unknown";c[p]||(c[p]={applications:[]});let v=(d.questions||[]).map(b=>{let E={type:b.type||"input",question:b.question||"",answer:b.answer||""};return b.options&&(b.options.length<=eo?E.options=b.options:(E.optionsOmitted=!0,m++)),b.page&&(E.page=b.page),b.wasPreFilled&&(E.wasPreFilled=!0),b.wasRetry&&(E.wasRetry=!0),E});c[p].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||v.length,questions:v})}Fe(s,c),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let c of a)delete l[c];Fe(o,l),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(l).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Me={};le(Me,{NAME:()=>oo,VERSION:()=>no,up:()=>io});import*as F from"fs";import*as Tt from"path";var no=2,oo="reset-unread-flags";function so(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function ro(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(s){try{F.unlinkSync(o)}catch{}throw s}try{F.renameSync(o,e)}catch(s){try{F.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function io(e){let t=Tt.join(e,"conversations.json"),n=so(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}ro(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Pe={};le(Pe,{NAME:()=>ao,VERSION:()=>lo,up:()=>po});import*as L from"fs";import*as Rt from"path";var lo=3,ao="recompute-last-message-by",co=new Set(["draft","confirmed","rejected","needs_review"]);function uo(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function fo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(s){try{L.unlinkSync(o)}catch{}throw s}try{L.renameSync(o,e)}catch(s){try{L.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function mo(e,t){if(!e||e.length===0)return"them";let n=e.filter(r=>!co.has(r.status));if(n.length===0)return"them";let o=n.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,l)=>l.t-r.t).map(r=>r.m),s=o.length>0?o:[...n].reverse();for(let r of s){let l=r.sender;if(l===t)return"me";if(l!=="Unknown"&&l!=="")return"them"}return"them"}async function po(e){let t=Rt.join(e,"conversations.json"),n=uo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,l=0;for(let i of Object.keys(n)){let a=n[i];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let f=Array.isArray(a.messages)?a.messages:[],c=mo(f,o),m=c==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==c&&l++,a.lastMessageBy=c,a.conversationStatus=m,s++}if(s===0){console.log(" No conversations to recompute.");return}fo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${l} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var qe={};le(qe,{NAME:()=>go,VERSION:()=>ho,up:()=>So});import*as M from"fs";import*as Dt from"path";var ho=4,go="split-connection-timestamps",yo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function wo(e){if(!M.existsSync(e))return null;let t=M.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function bo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{M.writeFileSync(o,n)}catch(s){try{M.unlinkSync(o)}catch{}throw s}try{M.renameSync(o,e)}catch(s){try{M.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function So(e){let t=Dt.join(e,"people.json"),n=wo(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,s=0;for(let r of Object.keys(n)){let l=n[r];!l||typeof l!="object"||(s++,yo.has(l.connectionStatus)&&l.connectionDate&&!l.requestedConnectionAt&&(l.requestedConnectionAt=l.connectionDate,l.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}bo(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var ko=vo(import.meta.url),Co=S.dirname(ko),xo=S.dirname(S.dirname(Co));function $o(e){return e&&(e==="~"?Be.homedir():e.startsWith("~/")||e.startsWith("~\\")?S.join(Be.homedir(),e.slice(2)):e)}var P=process.env.DATA_DIR?S.resolve($o(process.env.DATA_DIR)):xo,ee=S.join(P,"collected-profiles"),te=S.join(P,"market-research"),R=S.join(P,".schema-version"),Ot=[S.join(ee,".schema-version"),S.join(te,".schema-version")],J=4,B=[{version:1,module:Le},{version:2,module:Me},{version:3,module:Pe},{version:4,module:qe}];(function(){B.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of B){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=B.length?B[B.length-1].version:0;if(n!==J)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${J}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<B.length;o++){let s=o+1;if(B[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${B[o].version}`)}})();function Lt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
249
249
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
250
|
-
`),process.exit(1));try{u.mkdirSync(
|
|
251
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
252
|
-
`),process.exit(1))}let e;try{e=u.statSync(
|
|
253
|
-
[FATAL] DATA_DIR (${
|
|
250
|
+
`),process.exit(1));try{u.mkdirSync(P,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
251
|
+
[FATAL] Cannot create DATA_DIR (${P}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
252
|
+
`),process.exit(1))}let e;try{e=u.statSync(P)}catch(t){console.error(`
|
|
253
|
+
[FATAL] DATA_DIR (${P}) is not accessible: ${t.message}
|
|
254
254
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
255
|
-
[FATAL] DATA_DIR (${
|
|
256
|
-
`),process.exit(1));for(let t of[
|
|
255
|
+
[FATAL] DATA_DIR (${P}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
256
|
+
`),process.exit(1));for(let t of[ee,te]){let n;try{n=u.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
257
257
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
258
|
-
`),process.exit(1))}}var
|
|
259
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
258
|
+
`),process.exit(1))}}var Z=S.join(P,".migration-lock");function Eo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return u.writeFileSync(Z,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(u.readFileSync(Z,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(l){l.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let l=Date.parse(t.startedAt);Number.isNaN(l)||(r=Date.now()-l)}o&&r<s&&(console.error(`
|
|
259
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Z}
|
|
260
260
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
261
|
-
`),process.exit(1)),o&&r>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=
|
|
261
|
+
`),process.exit(1)),o&&r>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=Z+".tmp";try{return u.writeFileSync(n,e),u.renameSync(n,Z),!0}catch(o){try{u.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Ve(){try{if(JSON.parse(u.readFileSync(Z,"utf-8")).pid!==process.pid)return;u.unlinkSync(Z)}catch{}}var jt=!1;function Ao(){if(jt)return;jt=!0;let e=()=>{try{Ve()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function _o(){if(u.existsSync(R))return;let e=[],t=[];for(let r of Ot)if(u.existsSync(r))try{e.push({file:r,schema:ye(r)})}catch(l){t.push({file:r,err:l.message})}if(t.length>0){console.error(`
|
|
262
262
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
|
|
263
263
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
264
264
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(r=>r.schema.version);if(new Set(n).size>1){console.error(`
|
|
265
265
|
[FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
266
|
-
`),process.exit(1)}let o=e[0].schema,s=R+".tmp";try{u.writeFileSync(s,JSON.stringify(o,null,2)),u.renameSync(s,R)}catch(r){try{u.unlinkSync(s)}catch{}throw r}for(let r of
|
|
266
|
+
`),process.exit(1)}let o=e[0].schema,s=R+".tmp";try{u.writeFileSync(s,JSON.stringify(o,null,2)),u.renameSync(s,R)}catch(r){try{u.unlinkSync(s)}catch{}throw r}for(let r of Ot)if(u.existsSync(r))try{u.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${R}`)}function Io(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function ye(e){let t=u.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Nt(){if(_o(),!u.existsSync(R))return{version:0,migrations:[]};let e;try{e=ye(R)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
267
267
|
[FATAL] ${R} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
268
|
-
`),process.exit(1)}let t=
|
|
268
|
+
`),process.exit(1)}let t=Io(e);return t===null&&(console.error(`
|
|
269
269
|
[FATAL] ${R} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
270
|
-
`),process.exit(1)),t}function
|
|
271
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
272
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
270
|
+
`),process.exit(1)),t}function Mt(e){try{u.chmodSync(e,384)}catch{}}function To(e){if(Lt(),u.existsSync(R))try{if(u.lstatSync(R).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${R}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=R+".tmp";try{u.writeFileSync(t,JSON.stringify(e,null,2)),Mt(t),u.renameSync(t,R)}catch(n){try{u.unlinkSync(t)}catch{}throw n}}function Ft(e,t){if(!u.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=u.readdirSync(e).filter(i=>{let a=i.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return u.statSync(S.join(e,i)).isFile()}catch{return!1}}),s=0,r=0,l=[];for(let i of o){let a=S.join(e,i),f=S.join(e,i+n);if(u.existsSync(f)){r++;continue}try{qt(a,f),s++}catch(c){l.push({file:i,err:c.message})}}if(l.length>0){let i=new Error(`Failed to back up ${l.length} file(s) in ${S.basename(e)}/: `+l.map(a=>`${a.file} (${a.err})`).join(", "));throw i.code="BACKUP_INCOMPLETE",i}if(s>0||r>0){let i=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${S.basename(e)}/ (${n})${i}`)}}var Ue=!1;async function Pt(){if(Ue)return;Lt(),No();let t=Nt().version;if(t===J){Ue=!0;return}Ao(),Eo(),process.on("exit",Ve),t>J&&(console.error(`
|
|
271
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${J}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
272
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${J}.
|
|
273
273
|
`),process.exit(1)),console.log(`
|
|
274
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
274
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${J}`);let n=Fo();if(!n.ok){console.error(`
|
|
275
275
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
276
276
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
277
|
-
`),process.exit(1)}let o=
|
|
278
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,l=`.pre-${r}.backup`;try{
|
|
277
|
+
`),process.exit(1)}let o=B.filter(s=>s.version>t);for(let s of o){console.log(`
|
|
278
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,l=`.pre-${r}.backup`;try{Ft(ee,s.version),Ft(te,s.version)}catch(a){console.error(`
|
|
279
279
|
[FATAL] Pre-migration backup failed for ${r}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
280
|
-
`),process.exit(1)}let i=s.module;try{await i.up(
|
|
281
|
-
[FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let f=
|
|
280
|
+
`),process.exit(1)}let i=s.module;try{await i.up(ee,te)}catch(a){console.error(`
|
|
281
|
+
[FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${l} files...`);try{let f=Lo(l);f.ok?(console.error(` \u2713 Auto-rollback restored ${f.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
282
282
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${f.error}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
283
283
|
`))}catch(f){console.error(` [!] Auto-rollback CRASHED while restoring: ${f.message}`),console.error(` Manual recovery: copy *${l} files back over the originals.
|
|
284
|
-
`)}process.exit(1)}try{let a=new Date().toISOString(),f={version:s.version,name:i.NAME||r,appliedAt:a},c=
|
|
284
|
+
`)}process.exit(1)}try{let a=new Date().toISOString(),f={version:s.version,name:i.NAME||r,appliedAt:a},c=Nt();c.version=s.version,c.migratedAt=a,c.migrations=c.migrations||[],c.migrations.push(f),To(c)}catch(a){console.error(`
|
|
285
285
|
[FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
286
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{
|
|
287
|
-
\u2713 Schema is now at v${
|
|
288
|
-
`)}var
|
|
286
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{pt()}catch{}try{St()}catch{}Ue=!0,Ve(),console.log(`
|
|
287
|
+
\u2713 Schema is now at v${J}
|
|
288
|
+
`)}var Ro=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Do(e){let t=e.toLowerCase();return Ro.some(n=>n.test(t))}var Oo=6e4;function jo(){let e=Date.now(),t=[];for(let n of[P,ee,te]){if(!u.existsSync(n))continue;let o;try{o=u.readdirSync(n)}catch{continue}for(let s of o){if(!Do(s))continue;let r=S.join(n,s);try{let l=u.statSync(r);if(!l.isFile()||e-l.mtimeMs<Oo)continue;t.push({dir:n,file:s,fullPath:r})}catch{}}}return t}function No({verbose:e=!1}={}){let t=jo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{u.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${S.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Fo(){let e=[];for(let t of[ee,te]){if(!u.existsSync(t))continue;let n=u.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=S.join(t,o);try{ye(s)}catch(r){e.push({dir:S.basename(t),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Lo(e){let t=[],n=[];for(let r of[ee,te]){if(!u.existsSync(r))continue;let l=u.readdirSync(r).filter(i=>i.endsWith(e));for(let i of l){let a=S.join(r,i),f=i.slice(0,-e.length),c=S.join(r,f);try{f.toLowerCase().endsWith(".json")?ye(a):u.accessSync(a,u.constants.R_OK),t.push({backupPath:a,originalPath:c,fileName:i,dir:r})}catch(m){n.push(`${S.basename(r)}/${i}: ${m.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:r,originalPath:l,fileName:i,dir:a}of t)try{qt(r,l),o++}catch(f){s.push(`${S.basename(a)}/${i}: ${f.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function qt(e,t){let n=t+".tmp";try{u.copyFileSync(e,n),Mt(n)}catch(o){try{u.unlinkSync(n)}catch{}throw o}try{u.renameSync(n,t)}catch(o){try{u.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}await Pt();var W=process.argv.slice(2),we=parseInt(W.find(e=>e.startsWith("--max="))?.split("=")[1]||"10"),fe=W.includes("--connections"),Ut=W.find(e=>e.startsWith("--match-title="))?.split("=").slice(1).join("=")||null,_=Ut?Uo(Ut):null,Mo=W.includes("--list"),Po=W.includes("--verbose"),He=W.includes("--with-experience"),qo=W.includes("--help")||W.includes("-h");qo&&(console.log(`
|
|
289
289
|
enrich-profiles \u2014 batch-visit contacts in people.json missing About text
|
|
290
290
|
|
|
291
291
|
USAGE
|
|
@@ -328,12 +328,12 @@ WHEN TO USE
|
|
|
328
328
|
- You want to backfill in a controlled batch (\u2264 10 per day) before reaching
|
|
329
329
|
out, so AI drafting has full context.
|
|
330
330
|
- Use --connections to keep ban risk low.
|
|
331
|
-
`),process.exit(0));function
|
|
332
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE ENRICHMENT QUEUE"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Total people: ${t}`),console.log(` With "about": ${n} (${(n/t*100).toFixed(1)}%)`),console.log(` Missing "about": ${o}`),console.log(` Skipped (needs reply): ${f}`),console.log(` Visitable (queue): ${s.length}`),console.log(` Never fully visited: ${c} (gone first)`),_&&console.log(` Title-match filter: /${_.source}/i`),
|
|
333
|
-
`)}function
|
|
331
|
+
`),process.exit(0));function Uo(e){try{return new RegExp(e,"i")}catch(t){console.error(`Invalid regex for --match-title: ${t.message}`),process.exit(1)}}var Bo=new Set(["pending","sent_with_note","sent_without_note"]);function Vo(e){return!e.about||!e.about.trim()}function Ho(e){return!Bo.has(e.connectionStatus)}function Bt(){let e=z(),t=Ie(),n=new Set,o=new Set;for(let i of Object.values(t))i.profileUrl&&n.add(i.profileUrl),(i.unread===!0||i.actionNeeded==="reply"||i.situation==="needs_our_reply"||i.conversationStatus==="unanswered_by_us")&&i.profileUrl&&o.add(i.profileUrl);let r=Object.entries(e).filter(([i,a])=>i&&i.startsWith("http")).filter(([,i])=>Vo(i)).filter(([,i])=>Ho(i)).filter(([i])=>!o.has(i)).map(([i,a])=>({profileUrl:i,name:a.name,person:a,hasConversation:n.has(i)}));fe&&(r=r.filter(i=>i.person.connectionStatus==="connected")),_&&(r=r.filter(i=>_.test(i.person.title||"")));function l(i){let a=i.person.connectionStatus==="connected";return a&&i.hasConversation?1:a?2:_&&_.test(i.person.title||"")?3:i.hasConversation?4:5}return r.sort((i,a)=>{let f=l(i),c=l(a);if(f!==c)return f-c;let m=i.person.lastFullVisitAt||"",d=a.person.lastFullVisitAt||"";return m.localeCompare(d)}),r.map(i=>({profileUrl:i.profileUrl,name:i.name,source:"enrich-profile"}))}function Jo(){let e=z(),t=Object.keys(e).length,n=Object.values(e).filter(m=>m.about&&m.about.trim()).length,o=t-n,s=Bt(),r={connWithConv:0,conn:0,titleMatch:0,withConv:0,other:0},l=e,i=Ie(),a=new Set(Object.values(i).map(m=>m.profileUrl).filter(Boolean)),f=Object.values(i).filter(m=>m.profileUrl&&(m.unread===!0||m.actionNeeded==="reply"||m.situation==="needs_our_reply"||m.conversationStatus==="unanswered_by_us")).length,c=0;for(let m of s){let d=l[m.profileUrl],p=d.connectionStatus==="connected",v=_&&_.test(d.title||""),b=a.has(m.profileUrl);d.lastFullVisitAt||c++,p&&b?r.connWithConv++:p?r.conn++:v?r.titleMatch++:b?r.withConv++:r.other++}console.log(`
|
|
332
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE ENRICHMENT QUEUE"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Total people: ${t}`),console.log(` With "about": ${n} (${(n/t*100).toFixed(1)}%)`),console.log(` Missing "about": ${o}`),console.log(` Skipped (needs reply): ${f}`),console.log(` Visitable (queue): ${s.length}`),console.log(` Never fully visited: ${c} (gone first)`),_&&console.log(` Title-match filter: /${_.source}/i`),fe&&console.log(" Connections-only: yes"),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Tier 1 (conn+conv): ${r.connWithConv}`),console.log(` Tier 2 (connection): ${r.conn}`),console.log(` Tier 3 (title match): ${r.titleMatch}${_?"":" (no --match-title set)"}`),console.log(` Tier 4 (conversation): ${r.withConv}`),console.log(` Tier 5 (other): ${r.other}`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` At ${we}/day \u2192 ~${Math.ceil(s.length/we)} days to clear queue
|
|
333
|
+
`)}function Wo(){console.log(""),console.log(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log(" \u2551 \u26A0 BAN-RISK WARNING \u2014 please read \u2551"),console.log(" \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(" \u2551 This script visits LinkedIn profiles WITHOUT performing any \u2551"),console.log(" \u2551 follow-up action (no message, no connect request, no like). \u2551"),console.log(" \u2551 LinkedIn has previously flagged accounts for exactly this \u2551"),console.log(' \u2551 pattern with a "we noticed unusual activity" warning. \u2551'),console.log(" \u2551 \u2551"),console.log(" \u2551 Safer alternative: let data accumulate organically through \u2551"),console.log(" \u2551 apply / outreach / funnel / visit \u2014 those visits HAVE a \u2551"),console.log(" \u2551 purpose and don't trip the same heuristic. \u2551"),console.log(" \u2551 \u2551"),console.log(" \u2551 If you proceed, keep --max small (\u226410) and run at most once \u2551"),console.log(" \u2551 per day. Your account, your call. \u2551"),console.log(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log("")}async function Go(){if(console.log(`
|
|
334
334
|
LinkedIn Profile Enricher
|
|
335
|
-
`),
|
|
336
|
-
`);return}let t=
|
|
335
|
+
`),Mo){Jo();return}Wo(),He&&(console.log(""),console.log(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log(" \u2551 \u26A0 --with-experience: extra ban-risk warning \u2551"),console.log(" \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(" \u2551 Each visit now does TWO page loads (main + /details/ \u2551"),console.log(" \u2551 experience/). That doubles LinkedIn's view-counter signal \u2551"),console.log(" \u2551 per profile. Keep --max low (\u226410) and run rarely. \u2551"),console.log(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""));let e=Bt();if(console.log(` Queue size: ${e.length}`),console.log(` Max visits this session: ${we}`),_&&console.log(` Title filter: /${_.source}/i`),fe&&console.log(" Connections only: yes"),He&&console.log(" With experience: yes (2\xD7 page loads per profile)"),console.log(""),e.length===0){console.log(` Nothing to enrich \u2014 every visitable profile already has "about".
|
|
336
|
+
`);return}let t=fe&&_?"connections+title":fe?"connections":_?`title=${_.source}`:"all",n=It("enrich-profiles",t),{browser:o,page:s}=await ct();try{let r=await Ct(s,e,{maxVisits:we,verbose:Po,skipRecentDays:7,extractExperience:He}),l=z(),i=0;for(let a of e.slice(0,r.visited+r.skipped))l[a.profileUrl]?.about?.trim()&&i++;console.log(`
|
|
337
337
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" Enrichment Complete"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Visited: ${r.visited}`),console.log(` Skipped (recent): ${r.skipped}`),console.log(` Errors: ${r.errors}`),console.log(` Have "about" now: ${i} / ${r.visited+r.skipped}`),console.log(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
338
|
-
`),
|
|
339
|
-
Error:`,r.message),
|
|
338
|
+
`),je(n,"success",r)}catch(r){console.error(`
|
|
339
|
+
Error:`,r.message),je(n,"error",null,r.message)}finally{await o.close().catch(()=>{})}}Go().catch(e=>{console.error("Enrich-profiles failed:",e),process.exit(1)});
|