ilml-plugin-linkedin 1.20.3 → 1.20.4

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.
@@ -5,7 +5,7 @@ var ln=Object.defineProperty;var V=(e,n)=>{for(var t in n)ln(e,t,{get:n[t],enume
5
5
  `),process.exit(1));var Pe=Fn({token:Le});function Mn(e){if(!e||e<1e3)return`${e||0}ms`;let n=Math.round(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60),o=n%60;return o?`${t}m ${o}s`:`${t}m`}function Un({scriptName:e,mode:n,status:t,error:o,duration:r}){let s=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=r?` ${Mn(r)}`:"",c=t==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:t==="quota-reached"?"daily quota reached":"done",a=n&&n!=="default"?` (${n})`:"";return`${s} ${e}${a} \u2014 ${c} \u2014 ${i}${l}`}async function Me({scriptName:e,mode:n,status:t,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let c=`**${Un({scriptName:e,mode:n,status:t,error:r,duration:s})}**
6
6
 
7
7
  ${o.join(`
8
- `)}`;try{await Pe.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Bn=qn(import.meta.url),Jn=O.dirname(O.dirname(Bn)),te=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"collected-profiles"):O.join(Jn,"collected-profiles"),oe=O.join(te,"run-log.json");function Hn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";A.writeFileSync(o,t);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ue(){try{if(!A.existsSync(oe))return{runs:[]};let e=JSON.parse(A.readFileSync(oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function qe(e){A.existsSync(te)||A.mkdirSync(te,{recursive:!0});try{Hn(oe,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function Be(e,n="default"){let t=Ue();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),qe(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function re(e,n,t=null,o=null){if(!e)return;let r=null;try{let i=Ue(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,r=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=n,c.result=n,c.duration=Date.now()-e.startTime,c.stats=t,c.error=o,r=c.duration)}qe(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";Me({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as p from"fs";import*as pe from"os";import*as h from"path";import{fileURLToPath as kt}from"url";var ce={};V(ce,{NAME:()=>Vn,VERSION:()=>Wn,up:()=>Kn});import*as C from"fs";import*as z from"path";var Wn=1,Vn="normalize-jobs-and-questions",Gn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Yn=50;function se(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function ie(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{C.writeFileSync(o,t)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,e)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Kn(e,n){let t=z.join(e,"jobs.json"),o=z.join(n,"scouted-jobs.json"),r=z.join(e,"application-questions.json"),s=se(t)||{},i=se(o)||{},l=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let u=i[f],m=s[f];for(let g of Gn)u[g]!=null&&m[g]==null&&(m[g]=u[g]);c.push(f),l++}l>0?(ie(t,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=se(r);if(a&&Array.isArray(a.applications)){let f={},u=0;for(let m of a.applications){let g=m.jobId||"unknown";f[g]||(f[g]={applications:[]});let v=(m.questions||[]).map(d=>{let w={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=Yn?w.options=d.options:(w.optionsOmitted=!0,u++)),d.page&&(w.page=d.page),d.wasPreFilled&&(w.wasPreFilled=!0),d.wasRetry&&(w.wasRetry=!0),w});f[g].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||v.length,questions:v})}ie(r,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),u>0&&console.log(` Phase 2: Stripped bloated options from ${u} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];ie(o,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var le={};V(le,{NAME:()=>Qn,VERSION:()=>zn,up:()=>et});import*as $ from"fs";import*as Je from"path";var zn=2,Qn="reset-unread-flags";function Xn(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Zn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,e)}catch(r){try{$.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function et(e){let n=Je.join(e,"conversations.json"),t=Xn(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Zn(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var ae={};V(ae,{NAME:()=>tt,VERSION:()=>nt,up:()=>ct});import*as E from"fs";import*as He from"path";var nt=3,tt="recompute-last-message-by",ot=new Set(["draft","confirmed","rejected","needs_review"]);function rt(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function st(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{E.writeFileSync(o,t)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function it(e,n){if(!e||e.length===0)return"them";let t=e.filter(s=>!ot.has(s.status));if(t.length===0)return"them";let o=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...t].reverse();for(let s of r){let i=s.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function ct(e){let n=He.join(e,"conversations.json"),t=rt(n);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let l of Object.keys(t)){let c=t[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let a=Array.isArray(c.messages)?c.messages:[],f=it(a,o),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,r++}if(r===0){console.log(" No conversations to recompute.");return}st(n,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var ue={};V(ue,{NAME:()=>at,VERSION:()=>lt,up:()=>dt});import*as x from"fs";import*as We from"path";var lt=4,at="split-connection-timestamps",ut=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ft(e){if(!x.existsSync(e))return null;let n=x.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function pt(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{x.writeFileSync(o,t)}catch(r){try{x.unlinkSync(o)}catch{}throw r}try{x.renameSync(o,e)}catch(r){try{x.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function dt(e){let n=We.join(e,"people.json"),t=ft(n);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,ut.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}pt(n,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as k from"path";import{fileURLToPath as mt}from"url";var ht=mt(import.meta.url),gt=k.dirname(k.dirname(ht)),W=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"market-research"):k.join(gt,"market-research"),Vo=k.join(W,"scouted-jobs.json"),Go=k.join(W,"discovered-people.json"),Yo=k.join(W,"visit-log.json"),Ko=k.join(W,"companies.json"),zo=k.join(W,"job-decisions.json");function Ve(){yt=null,St=null,wt=null,bt=null,vt=null}var yt=null;var St=null;var wt=null;var bt=null;var vt=null;var At=kt(import.meta.url),Ct=h.dirname(At),$t=h.dirname(h.dirname(Ct));function Et(e){return e&&(e==="~"?pe.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(pe.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?h.resolve(Et(process.env.DATA_DIR)):$t,L=h.join(T,"collected-profiles"),P=h.join(T,"market-research"),b=h.join(T,".schema-version"),Ge=[h.join(L,".schema-version"),h.join(P,".schema-version")],j=4,D=[{version:1,module:ce},{version:2,module:le},{version:3,module:ae},{version:4,module:ue}];(function(){D.sort((o,r)=>o.version-r.version);let n=new Set;for(let o of D){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(n.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);n.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=D.length?D[D.length-1].version:0;if(t!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<D.length;o++){let r=o+1;if(D[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${D[o].version}`)}})();function Qe(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
8
+ `)}`;try{await Pe.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Bn=qn(import.meta.url),Jn=O.dirname(O.dirname(Bn)),te=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"collected-profiles"):O.join(Jn,"collected-profiles"),oe=O.join(te,"run-log.json");function Hn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";A.writeFileSync(o,t);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ue(){try{if(!A.existsSync(oe))return{runs:[]};let e=JSON.parse(A.readFileSync(oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function qe(e){A.existsSync(te)||A.mkdirSync(te,{recursive:!0});try{Hn(oe,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function Be(e,n="default"){let t=Ue();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),qe(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function re(e,n,t=null,o=null){if(!e)return;let r=null;try{let i=Ue(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,r=l.duration;else{let c=i.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());c&&(c.status=n,c.result=n,c.duration=Date.now()-e.startTime,c.stats=t,c.error=o,r=c.duration)}qe(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";Me({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as p from"fs";import*as pe from"os";import*as h from"path";import{fileURLToPath as kt}from"url";var ce={};V(ce,{NAME:()=>Vn,VERSION:()=>Wn,up:()=>Kn});import*as C from"fs";import*as z from"path";var Wn=1,Vn="normalize-jobs-and-questions",Gn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Yn=50;function se(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function ie(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{C.writeFileSync(o,t)}catch(r){try{C.unlinkSync(o)}catch{}throw r}try{C.renameSync(o,e)}catch(r){try{C.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Kn(e,n){let t=z.join(e,"jobs.json"),o=z.join(n,"scouted-jobs.json"),r=z.join(e,"application-questions.json"),s=se(t)||{},i=se(o)||{},l=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let u=i[f],m=s[f];for(let g of Gn)u[g]!=null&&m[g]==null&&(m[g]=u[g]);c.push(f),l++}l>0?(ie(t,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=se(r);if(a&&Array.isArray(a.applications)){let f={},u=0;for(let m of a.applications){let g=m.jobId||"unknown";f[g]||(f[g]={applications:[]});let v=(m.questions||[]).map(d=>{let w={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=Yn?w.options=d.options:(w.optionsOmitted=!0,u++)),d.page&&(w.page=d.page),d.wasPreFilled&&(w.wasPreFilled=!0),d.wasRetry&&(w.wasRetry=!0),w});f[g].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||v.length,questions:v})}ie(r,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),u>0&&console.log(` Phase 2: Stripped bloated options from ${u} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];ie(o,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var le={};V(le,{NAME:()=>Qn,VERSION:()=>zn,up:()=>et});import*as $ from"fs";import*as Je from"path";var zn=2,Qn="reset-unread-flags";function Xn(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Zn(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,e)}catch(r){try{$.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function et(e){let n=Je.join(e,"conversations.json"),t=Xn(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Zn(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var ae={};V(ae,{NAME:()=>tt,VERSION:()=>nt,up:()=>ct});import*as E from"fs";import*as He from"path";var nt=3,tt="recompute-last-message-by",ot=new Set(["draft","confirmed","rejected","needs_review"]);function rt(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function st(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{E.writeFileSync(o,t)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function it(e,n){if(!e||e.length===0)return"them";let t=e.filter(s=>!ot.has(s.status));if(t.length===0)return"them";let o=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...t].reverse();for(let s of r){let i=s.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function ct(e){let n=He.join(e,"conversations.json"),t=rt(n);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let l of Object.keys(t)){let c=t[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let a=Array.isArray(c.messages)?c.messages:[],f=it(a,o),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,r++}if(r===0){console.log(" No conversations to recompute.");return}st(n,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var ue={};V(ue,{NAME:()=>at,VERSION:()=>lt,up:()=>dt});import*as x from"fs";import*as We from"path";var lt=4,at="split-connection-timestamps",ut=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ft(e){if(!x.existsSync(e))return null;let n=x.readFileSync(e,"utf-8");return n.charCodeAt(0)===65279&&(n=n.slice(1)),JSON.parse(n)}function pt(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{x.writeFileSync(o,t)}catch(r){try{x.unlinkSync(o)}catch{}throw r}try{x.renameSync(o,e)}catch(r){try{x.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function dt(e){let n=We.join(e,"people.json"),t=ft(n);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,ut.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}pt(n,t),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as k from"path";import{fileURLToPath as mt}from"url";var ht=mt(import.meta.url),gt=k.dirname(k.dirname(ht)),W=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"market-research"):k.join(gt,"market-research"),Go=k.join(W,"scouted-jobs.json"),Yo=k.join(W,"discovered-people.json"),Ko=k.join(W,"visit-log.json"),zo=k.join(W,"companies.json"),Qo=k.join(W,"job-decisions.json");function Ve(){yt=null,St=null,wt=null,bt=null,vt=null}var yt=null;var St=null;var wt=null;var bt=null;var vt=null;var At=kt(import.meta.url),Ct=h.dirname(At),$t=h.dirname(h.dirname(Ct));function Et(e){return e&&(e==="~"?pe.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(pe.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?h.resolve(Et(process.env.DATA_DIR)):$t,L=h.join(T,"collected-profiles"),P=h.join(T,"market-research"),b=h.join(T,".schema-version"),Ge=[h.join(L,".schema-version"),h.join(P,".schema-version")],j=4,D=[{version:1,module:ce},{version:2,module:le},{version:3,module:ae},{version:4,module:ue}];(function(){D.sort((o,r)=>o.version-r.version);let n=new Set;for(let o of D){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(n.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);n.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=D.length?D[D.length-1].version:0;if(t!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<D.length;o++){let r=o+1;if(D[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${D[o].version}`)}})();function Qe(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
9
9
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
10
10
  `),process.exit(1));try{p.mkdirSync(T,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
11
11
  [FATAL] Cannot create DATA_DIR (${T}): ${n.message}`),console.error(` Fix the path or permissions and try again.
@@ -1,4 +1,4 @@
1
- var tt=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{for(var n in t)tt(e,n,{get:t[n],enumerable:!0})};async function f(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Ce(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let i=o.innerText||"",a=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),r=i.includes("Try for")||i.includes("free trial")||i.includes("/month")||i.includes("per month")||i.includes("Start my")||i.includes("Subscribe"),m=i.includes("Get hired faster")||i.includes("Get hired 2x");if(a||r||m){let _=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(_)return _.click(),{dismissed:!0,matched:i.substring(0,80)};let $=o.querySelectorAll("button");for(let c of $){let S=c.innerText?.trim().toLowerCase()||"",h=c.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||h.includes("dismiss"))return c.click(),{dismissed:!0,matched:i.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 H=z(()=>{});import{getPluginConfig as ot}from"@ilivemylife/graph-sdk";var it,rt,j,Nt,st,ne=z(async()=>{it=await ot();for(let[e,t]of Object.entries(it))process.env[e]===void 0&&(process.env[e]=t);rt=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Nt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),st=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]))});import"dotenv/config";import*as g from"fs";import*as b from"path";import{fileURLToPath as bt}from"url";function kt(){g.existsSync(I)||g.mkdirSync(I,{recursive:!0})}function xt(e,t){if(!g.existsSync(e))return null;try{let n=JSON.parse(g.readFileSync(e,"utf-8"));try{g.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${b.resolve(e)}`);let o=e+".backup";if(g.existsSync(o))try{let i=JSON.parse(g.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{g.copyFileSync(o,e)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{g.copyFileSync(e,e+".corrupted")}catch{}return null}}function re(){return Z||(kt(),Z=xt(Ct,"people.json")||{},Z)}var St,vt,I,Ct,un,dn,fn,mn,pn,hn,He,wn,gn,Z,se=z(async()=>{await ne();St=bt(import.meta.url),vt=b.dirname(b.dirname(St)),I=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"collected-profiles"):b.join(vt,"collected-profiles"),Ct=b.join(I,"people.json"),un=b.join(I,"jobs.json"),dn=b.join(I,"quota.json"),fn=b.join(I,"conversations.json"),mn=b.join(I,"sync-state.json"),pn=b.join(I,"application-questions.json"),hn=b.join(I,"profile-history"),He=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},wn=He(process.env.CONNECT_MAX_DAILY,20),gn=He(process.env.CONNECT_MAX_WEEKLY,100),Z=null});var Ue={};nt(Ue,{extractCertificationsFromDetails:()=>$t,extractEducationFromDetails:()=>At,extractExperienceFromDetails:()=>_t,extractFeaturedFromDetails:()=>Et,extractRecommendationsFromDetails:()=>Dt,extractSkillsFromDetails:()=>It});async function _t(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await f(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 a=0;a<5;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await f(900);await f(1e3);let i=0;for(;i<5&&await e.evaluate(()=>{for(let r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.click(),!0;return!1});)i++,await f(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await f(700);return await e.evaluate(()=>{let a=document.querySelector("main");if(!a)return[];function r(c){let S=[];for(let h of c.querySelectorAll("div")){let w=Array.from(h.children).filter(x=>x.tagName==="DIV");if(w.length<3)continue;let y=w.filter(x=>(x.textContent||"").trim().length>50);y.length<3||(h.textContent||"").length<500||S.push({el:h,count:y.length,totalText:(h.textContent||"").length})}return S.sort((h,w)=>w.count-h.count||h.totalText-w.totalText),S[0]?.el}let m=r(a);if(!m)return[];let _=Array.from(m.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function $(c){let S=c[0]||null,h=null,w=null;if(c[1]){let d=c[1].split("\xB7").map(v=>v.trim());h=d[0]||null,d[1]&&(w=d[1])}let y=c.findIndex(d=>/(\d{4}|present)/i.test(d)&&/(-|–|—)/i.test(d)&&d.length<80),x=null,P=null;if(y>=0){let d=c[y].split("\xB7").map(v=>v.trim());x=d[0]||null,d[1]&&(P=d[1])}let M=null,R=-1;if(y>=0&&c[y+1]){let d=c[y+1],v=/^[>*\-•]|^&gt;/.test(d),N=/https?:\/\//.test(d),O=/\d{4}/.test(d),C=/,/.test(d)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(d);!v&&!N&&!O&&d.length<100&&C&&(M=d,R=y+1)}let X=null,p=-1,F=c[c.length-1];if(F&&/and\s+\+\d+\s+skills?$/i.test(F)){p=c.length-1;let d=F.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);d&&(X={listed:d[1].split(",").map(v=>v.trim()),additional:parseInt(d[2],10)})}let q=new Set([0,1,y,R,p].filter(d=>d>=0)),D=c.filter((d,v)=>!q.has(v)),k=D.length>0?D.join(`
1
+ var tt=Object.defineProperty;var z=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{for(var n in t)tt(e,n,{get:t[n],enumerable:!0})};async function f(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Ce(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let i=o.innerText||"",a=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),r=i.includes("Try for")||i.includes("free trial")||i.includes("/month")||i.includes("per month")||i.includes("Start my")||i.includes("Subscribe"),m=i.includes("Get hired faster")||i.includes("Get hired 2x");if(a||r||m){let _=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(_)return _.click(),{dismissed:!0,matched:i.substring(0,80)};let $=o.querySelectorAll("button");for(let c of $){let S=c.innerText?.trim().toLowerCase()||"",h=c.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||h.includes("dismiss"))return c.click(),{dismissed:!0,matched:i.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 H=z(()=>{});import{getPluginConfig as ot}from"@ilivemylife/graph-sdk";var it,rt,j,Nt,st,ne=z(async()=>{it=await ot();for(let[e,t]of Object.entries(it))process.env[e]===void 0&&(process.env[e]=t);rt=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Nt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),st=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]))});import"dotenv/config";import*as g from"fs";import*as b from"path";import{fileURLToPath as bt}from"url";function kt(){g.existsSync(I)||g.mkdirSync(I,{recursive:!0})}function xt(e,t){if(!g.existsSync(e))return null;try{let n=JSON.parse(g.readFileSync(e,"utf-8"));try{g.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${b.resolve(e)}`);let o=e+".backup";if(g.existsSync(o))try{let i=JSON.parse(g.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{g.copyFileSync(o,e)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{g.copyFileSync(e,e+".corrupted")}catch{}return null}}function re(){return Z||(kt(),Z=xt(Ct,"people.json")||{},Z)}var St,vt,I,Ct,dn,fn,mn,pn,hn,wn,He,gn,yn,Z,se=z(async()=>{await ne();St=bt(import.meta.url),vt=b.dirname(b.dirname(St)),I=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"collected-profiles"):b.join(vt,"collected-profiles"),Ct=b.join(I,"people.json"),dn=b.join(I,"jobs.json"),fn=b.join(I,"quota.json"),mn=b.join(I,"conversations.json"),pn=b.join(I,"sync-state.json"),hn=b.join(I,"application-questions.json"),wn=b.join(I,"profile-history"),He=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},gn=He(process.env.CONNECT_MAX_DAILY,20),yn=He(process.env.CONNECT_MAX_WEEKLY,100),Z=null});var Ue={};nt(Ue,{extractCertificationsFromDetails:()=>$t,extractEducationFromDetails:()=>At,extractExperienceFromDetails:()=>_t,extractFeaturedFromDetails:()=>Et,extractRecommendationsFromDetails:()=>Dt,extractSkillsFromDetails:()=>It});async function _t(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await f(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 a=0;a<5;a++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await f(900);await f(1e3);let i=0;for(;i<5&&await e.evaluate(()=>{for(let r of document.querySelectorAll("button"))if(/^Load more$/i.test((r.textContent||"").trim()))return r.click(),!0;return!1});)i++,await f(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await f(700);return await e.evaluate(()=>{let a=document.querySelector("main");if(!a)return[];function r(c){let S=[];for(let h of c.querySelectorAll("div")){let w=Array.from(h.children).filter(x=>x.tagName==="DIV");if(w.length<3)continue;let y=w.filter(x=>(x.textContent||"").trim().length>50);y.length<3||(h.textContent||"").length<500||S.push({el:h,count:y.length,totalText:(h.textContent||"").length})}return S.sort((h,w)=>w.count-h.count||h.totalText-w.totalText),S[0]?.el}let m=r(a);if(!m)return[];let _=Array.from(m.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function $(c){let S=c[0]||null,h=null,w=null;if(c[1]){let d=c[1].split("\xB7").map(v=>v.trim());h=d[0]||null,d[1]&&(w=d[1])}let y=c.findIndex(d=>/(\d{4}|present)/i.test(d)&&/(-|–|—)/i.test(d)&&d.length<80),x=null,P=null;if(y>=0){let d=c[y].split("\xB7").map(v=>v.trim());x=d[0]||null,d[1]&&(P=d[1])}let M=null,R=-1;if(y>=0&&c[y+1]){let d=c[y+1],v=/^[>*\-•]|^&gt;/.test(d),N=/https?:\/\//.test(d),O=/\d{4}/.test(d),C=/,/.test(d)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(d);!v&&!N&&!O&&d.length<100&&C&&(M=d,R=y+1)}let X=null,p=-1,F=c[c.length-1];if(F&&/and\s+\+\d+\s+skills?$/i.test(F)){p=c.length-1;let d=F.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);d&&(X={listed:d[1].split(",").map(v=>v.trim()),additional:parseInt(d[2],10)})}let q=new Set([0,1,y,R,p].filter(d=>d>=0)),D=c.filter((d,v)=>!q.has(v)),k=D.length>0?D.join(`
2
2
 
3
3
  `):null;return{title:S,company:h,employmentType:w,dates:x,duration:P,location:M,description:k,skills:X,_raw:c}}return _.map(c=>{let h=(c.innerText||"").trim().split(`
4
4
  `).map(w=>w.trim()).filter(w=>w&&w.length<5e3);return $(h)}).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 W(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await f(3e3);let i=e.url();if(/\/(login|authwall|checkpoint)/i.test(i))throw new Error(`Session expired \u2014 bounced to ${i} when fetching /details/${n}/`);if(!i.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${i})`);for(let r=0;r<4;r++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await f(700);await f(800);let a=0;for(;a<5&&await e.evaluate(()=>{for(let m of document.querySelectorAll("button"))if(/^Load more$/i.test((m.textContent||"").trim()))return m.click(),!0;return!1});)a++,await f(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await f(600)}async function Y(e,t,n,o){try{return await o()}catch(i){let a=i.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(a))throw i;return/not available on profile/i.test(a)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${a.slice(0,120)}`),[])}}async function Et(e,t){return Y(t,"featured","extractFeaturedFromDetails",async()=>(await W(e,t,"featured"),await e.evaluate(`(() => {
package/dist/version.mjs CHANGED
@@ -1 +1 @@
1
- import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.3";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
1
+ import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.4";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
package/dist/viewers.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var lt=Object.defineProperty;var K=(e,t)=>{for(var n in t)lt(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Uo}from"url";import kt from"puppeteer";import{addExtra as At}from"puppeteer-extra";import Et from"puppeteer-extra-plugin-stealth";async function z(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as at}from"@ilivemylife/graph-sdk";var ut=await at();for(let[e,t]of Object.entries(ut))process.env[e]===void 0&&(process.env[e]=t);var ft=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ko=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),pt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import I from"fs";import D from"path";var dt="cookies.json";function he(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin","cookies.json"):dt}function ge(){let e=he();if(!I.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=I.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function ye(){return I.existsSync(he())}function mt(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin"):"."}function Se(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ht(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Se(t[1]):"default"}function we(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),D.resolve(t);let n=Se(e||ht()),o=D.join(mt(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),D.resolve(o)}var ve=".ilml-seeded";function be(e){return!I.existsSync(D.join(e,ve))}function ke(e){try{I.writeFileSync(D.join(e,ve),new Date().toISOString())}catch{}}function Ae(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(D.join(e,n),{force:!0}),t++}catch{}return t}import ee from"fs";import gt from"path";var yt={headless:!1,defaultViewport:null,protocolTimeout:3e5},H=new Set,Ee=!1;async function Q(){let e=[...H].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});H.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function St(){if(Ee)return;Ee=!0;let e=t=>async()=>{await Q(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Q(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Q(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Q(),process.exit(0))}),process.on("exit",()=>{for(let t of H)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function te(e){return gt.join(e,".ilml-browser-session.json")}function xe(e,t={}){try{ee.writeFileSync(te(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function wt(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();xe(e,n?{wsEndpoint:n}:{})}catch{}}function vt(e){let t=_e(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{ee.rmSync(te(e),{force:!0})}catch{}}function _e(e){try{return JSON.parse(ee.readFileSync(te(e),"utf-8"))}catch{return null}}function Ce(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function $e(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function Ie(e,t,{probeTimeoutMs:n=4e3}={}){let o=_e(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ce(o.ownerPid)?"live":(V(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await $e(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return V(t),"free";if(Ce(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await $e(s.close().then(()=>!0).catch(()=>!1),n,!1))return V(t),"free";try{s.disconnect()}catch{}return"live"}function bt(e,t){e&&(St(),H.add(e),e.on("disconnected",()=>{H.delete(e),t&&V(t)}))}async function Te(e,t={}){let n=we(),o={...yt,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ie(e,n)==="live")throw new Error(r);xe(n);let i;try{i=await e.launch(o)}catch{if(await Ie(e,n)==="live")throw new Error(r);Ae(n);try{i=await e.launch(o)}catch(c){throw vt(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return bt(i,n),wt(n,i),{browser:i,profileDir:n,needsSeed:be(n)}}async function De(e,t){if(!t||!t.needsSeed)return!1;if(!ye())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...ge()),ke(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Re=At(kt);Re.use(Et());async function Oe(){let{browser:e,profileDir:t,needsSeed:n}=await Te(Re),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await De(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Ct}from"url";var $t=Ct(import.meta.url),It=g.dirname(g.dirname($t)),_=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(It,"collected-profiles"),xt=g.join(_,"people.json"),vn=g.join(_,"jobs.json"),bn=g.join(_,"quota.json"),kn=g.join(_,"conversations.json"),An=g.join(_,"sync-state.json"),En=g.join(_,"application-questions.json"),Cn=g.join(_,"profile-history"),je=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},$n=je(process.env.CONNECT_MAX_DAILY,20),In=je(process.env.CONNECT_MAX_WEEKLY,100),W=null,_t=null,Tt=null,Dt=null,Rt=null,Ot=null;function Ne(){W=null,_t=null,Tt=null,Dt=null,Rt=null,Ot=null}function jt(){h.existsSync(_)||h.mkdirSync(_,{recursive:!0})}function Nt(e,t){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let r=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function Fe(){return W||(jt(),W=Nt(xt,"people.json")||{},W)}import"dotenv/config";import*as F from"fs";import*as S from"path";import{fileURLToPath as Ft}from"url";var Lt=Ft(import.meta.url),Pt=S.dirname(S.dirname(Lt)),Y=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(Pt,"market-research"),Nn=S.join(Y,"scouted-jobs.json"),Mt=S.join(Y,"discovered-people.json"),Ut=S.join(Y,"visit-log.json"),Fn=S.join(Y,"companies.json"),Ln=S.join(Y,"job-decisions.json");function Le(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Pe(){qt=null,Bt=null,G=null,Jt=null,N=null}var qt=null;var Bt=null;var G=null;function Me(){return G||(G=Le(Mt)||{},G)}var Jt=null;var N=null;function Ue(){return N||(N=Le(Ut)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function qe(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await z(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await z(1e3);return await e.evaluate(()=>{let n=[],o=document.querySelectorAll('a[href*="/in/"]'),r=new Set;for(let i of o){let s=i.getAttribute("href")?.split("?")[0];if(!s||r.has(s))continue;r.add(s);let c=i;for(let p=0;p<8&&!(!c.parentElement||(c=c.parentElement,c.tagName==="LI"||c.classList?.contains("pvs-list__paged-list-wrapper")));p++);let l=c?.innerText?.trim()||"",u=l.split(`
1
+ var lt=Object.defineProperty;var K=(e,t)=>{for(var n in t)lt(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as U from"path";import{fileURLToPath as Uo}from"url";import kt from"puppeteer";import{addExtra as At}from"puppeteer-extra";import Et from"puppeteer-extra-plugin-stealth";async function z(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as at}from"@ilivemylife/graph-sdk";var ut=await at();for(let[e,t]of Object.entries(ut))process.env[e]===void 0&&(process.env[e]=t);var ft=process.env.LINKEDIN_NAME,j=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Ko=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.NEEDS_REVIEW])),pt=Object.freeze(new Set([j.DRAFT,j.CONFIRMED,j.REJECTED,j.NEEDS_REVIEW]));import I from"fs";import D from"path";var dt="cookies.json";function he(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin","cookies.json"):dt}function ge(){let e=he();if(!I.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=I.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function ye(){return I.existsSync(he())}function mt(){let e=process.env.ILML_SCOPE_DIR;return e?D.join(e,"plugins-state","linkedin"):"."}function Se(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ht(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Se(t[1]):"default"}function we(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),D.resolve(t);let n=Se(e||ht()),o=D.join(mt(),"chrome-profile",n);return I.existsSync(o)||I.mkdirSync(o,{recursive:!0}),D.resolve(o)}var ve=".ilml-seeded";function be(e){return!I.existsSync(D.join(e,ve))}function ke(e){try{I.writeFileSync(D.join(e,ve),new Date().toISOString())}catch{}}function Ae(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{I.rmSync(D.join(e,n),{force:!0}),t++}catch{}return t}import ee from"fs";import gt from"path";var yt={headless:!1,defaultViewport:null,protocolTimeout:3e5},H=new Set,Ee=!1;async function Q(){let e=[...H].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});H.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function St(){if(Ee)return;Ee=!0;let e=t=>async()=>{await Q(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Q(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Q(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Q(),process.exit(0))}),process.on("exit",()=>{for(let t of H)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function te(e){return gt.join(e,".ilml-browser-session.json")}function xe(e,t={}){try{ee.writeFileSync(te(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function wt(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();xe(e,n?{wsEndpoint:n}:{})}catch{}}function vt(e){let t=_e(e);t&&t.ownerPid===process.pid&&V(e)}function V(e){try{ee.rmSync(te(e),{force:!0})}catch{}}function _e(e){try{return JSON.parse(ee.readFileSync(te(e),"utf-8"))}catch{return null}}function Ce(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function $e(e,t,n){let o,r=new Promise(s=>{o=setTimeout(()=>s(n),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(o),s),s=>{throw clearTimeout(o),s});return Promise.race([i,r])}async function Ie(e,t,{probeTimeoutMs:n=4e3}={}){let o=_e(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ce(o.ownerPid)?"live":(V(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await $e(i,n,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return V(t),"free";if(Ce(o.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await $e(s.close().then(()=>!0).catch(()=>!1),n,!1))return V(t),"free";try{s.disconnect()}catch{}return"live"}function bt(e,t){e&&(St(),H.add(e),e.on("disconnected",()=>{H.delete(e),t&&V(t)}))}async function Te(e,t={}){let n=we(),o={...yt,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ie(e,n)==="live")throw new Error(r);xe(n);let i;try{i=await e.launch(o)}catch{if(await Ie(e,n)==="live")throw new Error(r);Ae(n);try{i=await e.launch(o)}catch(c){throw vt(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return bt(i,n),wt(n,i),{browser:i,profileDir:n,needsSeed:be(n)}}async function De(e,t){if(!t||!t.needsSeed)return!1;if(!ye())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...ge()),ke(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Re=At(kt);Re.use(Et());async function Oe(){let{browser:e,profileDir:t,needsSeed:n}=await Te(Re),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await De(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Ct}from"url";var $t=Ct(import.meta.url),It=g.dirname(g.dirname($t)),_=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(It,"collected-profiles"),xt=g.join(_,"people.json"),bn=g.join(_,"jobs.json"),kn=g.join(_,"quota.json"),An=g.join(_,"conversations.json"),En=g.join(_,"sync-state.json"),Cn=g.join(_,"application-questions.json"),$n=g.join(_,"profile-history"),je=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},In=je(process.env.CONNECT_MAX_DAILY,20),xn=je(process.env.CONNECT_MAX_WEEKLY,100),W=null,_t=null,Tt=null,Dt=null,Rt=null,Ot=null;function Ne(){W=null,_t=null,Tt=null,Dt=null,Rt=null,Ot=null}function jt(){h.existsSync(_)||h.mkdirSync(_,{recursive:!0})}function Nt(e,t){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let o=e+".backup";if(h.existsSync(o))try{let r=JSON.parse(h.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{h.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function Fe(){return W||(jt(),W=Nt(xt,"people.json")||{},W)}import"dotenv/config";import*as F from"fs";import*as S from"path";import{fileURLToPath as Ft}from"url";var Lt=Ft(import.meta.url),Pt=S.dirname(S.dirname(Lt)),Y=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(Pt,"market-research"),Fn=S.join(Y,"scouted-jobs.json"),Mt=S.join(Y,"discovered-people.json"),Ut=S.join(Y,"visit-log.json"),Ln=S.join(Y,"companies.json"),Pn=S.join(Y,"job-decisions.json");function Le(e){try{if(F.existsSync(e))return JSON.parse(F.readFileSync(e,"utf-8"))}catch{}return null}function Pe(){qt=null,Bt=null,G=null,Jt=null,N=null}var qt=null;var Bt=null;var G=null;function Me(){return G||(G=Le(Mt)||{},G)}var Jt=null;var N=null;function Ue(){return N||(N=Le(Ut)||{visits:[]},Array.isArray(N.visits)||(N.visits=[]),N)}async function qe(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await z(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await z(1e3);return await e.evaluate(()=>{let n=[],o=document.querySelectorAll('a[href*="/in/"]'),r=new Set;for(let i of o){let s=i.getAttribute("href")?.split("?")[0];if(!s||r.has(s))continue;r.add(s);let c=i;for(let p=0;p<8&&!(!c.parentElement||(c=c.parentElement,c.tagName==="LI"||c.classList?.contains("pvs-list__paged-list-wrapper")));p++);let l=c?.innerText?.trim()||"",u=l.split(`
2
2
  `).map(p=>p.trim()).filter(Boolean),f="";for(let p of u)if(p.length>2&&p.length<60&&!p.includes("View")&&!p.includes("profile")&&!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&!p.startsWith("3rd")){f=p;break}f||(f=i.textContent?.trim()?.split(`
3
3
  `)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",q=u.indexOf(f);if(q>=0&&q+1<u.length){let p=u[q+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(v=p)}f&&f.length>1&&n.push({profileUrl:s.startsWith("/")?"https://www.linkedin.com"+s:s,name:f,title:v||null,connectionDegree:m})}return n})}function Be(e){let t=Fe(),n=Ue(),o=Me(),r=new Map;for(let i of n.visits||[]){let s=r.get(i.profileUrl);(!s||i.date>s)&&r.set(i.profileUrl,i.date)}return e.map(i=>{let s=t[i.profileUrl],c=o[i.profileUrl],l=r.get(i.profileUrl);return{...i,isConnected:s?.connectionStatus==="connected",isPending:s?.connectionStatus==="pending"||s?.connectionStatus==="sent_without_note",isInPeopleDb:!!s,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:s?.category||c?.role||null}})}import"dotenv/config";import*as b from"fs";import*as R from"path";import{fileURLToPath as Kt}from"url";import"dotenv/config";import{createGraphClient as Vt,resolveToken as Ht}from"@ilivemylife/graph-sdk";import{config as Wt}from"dotenv";Wt();var Je=Ht()||process.env.TOKEN;Je||(console.error(`
4
4
  [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.
package/dist/visit.mjs CHANGED
@@ -1,6 +1,6 @@
1
- var Rn=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{for(var n in t)Rn(e,n,{get:t[n],enumerable:!0})};async function x(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function yt(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),a=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||i||a){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:r.substring(0,80)};let m=o.querySelectorAll("button");for(let c of m){let w=c.innerText?.trim().toLowerCase()||"",u=c.getAttribute("aria-label")?.toLowerCase()||"";if(w==="not now"||w==="no thanks"||w==="dismiss"||u.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var pe=ce(()=>{});import{getPluginConfig as Dn}from"@ilivemylife/graph-sdk";var jn,On,Z,Tr,Nn,Oe=ce(async()=>{jn=await Dn();for(let[e,t]of Object.entries(jn))process.env[e]===void 0&&(process.env[e]=t);On=process.env.LINKEDIN_NAME,Z=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Tr=Object.freeze(new Set([Z.DRAFT,Z.CONFIRMED,Z.NEEDS_REVIEW])),Nn=Object.freeze(new Set([Z.DRAFT,Z.CONFIRMED,Z.REJECTED,Z.NEEDS_REVIEW]))});import"dotenv/config";import*as A from"fs";import*as E from"path";import{fileURLToPath as Yn}from"url";function Ut(){ae=null,Qn=null,Zn=null,Xn=null,eo=null,to=null}function Bt(){A.existsSync(V)||A.mkdirSync(V,{recursive:!0})}function Vt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";A.writeFileSync(o,n);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ht(e,t){if(!A.existsSync(e))return null;try{let n=JSON.parse(A.readFileSync(e,"utf-8"));try{A.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${E.resolve(e)}`);let o=e+".backup";if(A.existsSync(o))try{let r=JSON.parse(A.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{A.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{A.copyFileSync(e,e+".corrupted")}catch{}return null}}function no(){return new Date().toISOString().split("T")[0]}function X(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Ft(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Jt(e,t,n=null){if(!t||e[t])return t;let o=X(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(X(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Ft(n),i=Ft(e[r].name);if(s&&i&&s===i)return r}return t}function so(){A.existsSync(Pe)||A.mkdirSync(Pe,{recursive:!0})}function Wt(e){let t=X(e);return t?E.join(Pe,`${t}.json`):null}function io(e){let t=Wt(e);return t?Ht(t,`profile-history/${X(e)}.json`)||[]:[]}function lo(e,t){let n=Wt(e);if(!n)return;so();let o=io(e);o.unshift(t);try{Vt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${X(e)}: ${r.message}`)}}function Pt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Mt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function co(e,t){if(!e)return[];let n=[];for(let o of ro){let r=e[o],s=t[o];Pt(r)||Pt(s)||Mt(r)!==Mt(s)&&n.push(o)}return n}function ao(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function ue(){return ae||(Bt(),ae=Ht(Fe,"people.json")||{},ae)}function Gt(e){Bt(),ae=e;try{Vt(Fe,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${E.resolve(Fe)}`)}}function Me(e,t={}){if(!e)return null;let n=ue(),o=no(),r=new Date().toISOString(),s=Jt(n,e,t.name),i=n[s];if(i){let a=co(i,t);a.length>0&&(lo(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:ao(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of oo)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(i[l])&&i[l].length>0)continue;i[l]=t[l]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Gt(n),n[s]}function qe(e,t,n={}){if(n.dryRun||!e||!t)return;let o=X(t);if(!o)return;let r=ue(),s=Jt(r,e),i=r[s];if(!i)return;let a=X(i.profileUrl||s);o!==a&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),Gt(r)))}var Kn,zn,V,Fe,es,ts,ns,os,rs,Pe,qt,ss,is,ae,Qn,Zn,Xn,eo,to,oo,ro,$e=ce(async()=>{await Oe();Kn=Yn(import.meta.url),zn=E.dirname(E.dirname(Kn)),V=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"collected-profiles"):E.join(zn,"collected-profiles"),Fe=E.join(V,"people.json"),es=E.join(V,"jobs.json"),ts=E.join(V,"quota.json"),ns=E.join(V,"conversations.json"),os=E.join(V,"sync-state.json"),rs=E.join(V,"application-questions.json"),Pe=E.join(V,"profile-history"),qt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},ss=qt(process.env.CONNECT_MAX_DAILY,20),is=qt(process.env.CONNECT_MAX_WEEKLY,100),ae=null,Qn=null,Zn=null,Xn=null,eo=null,to=null;oo=["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"],ro=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Yt={};me(Yt,{extractCertificationsFromDetails:()=>ho,extractEducationFromDetails:()=>mo,extractExperienceFromDetails:()=>uo,extractFeaturedFromDetails:()=>fo,extractRecommendationsFromDetails:()=>go,extractSkillsFromDetails:()=>po});async function uo(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await x(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 s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await x(900);await x(1e3);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 x(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await x(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(c){let w=[];for(let u of c.querySelectorAll("div")){let d=Array.from(u.children).filter(S=>S.tagName==="DIV");if(d.length<3)continue;let C=d.filter(S=>(S.textContent||"").trim().length>50);C.length<3||(u.textContent||"").length<500||w.push({el:u,count:C.length,totalText:(u.textContent||"").length})}return w.sort((u,d)=>d.count-u.count||u.totalText-d.totalText),w[0]?.el}let a=i(s);if(!a)return[];let l=Array.from(a.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function m(c){let w=c[0]||null,u=null,d=null;if(c[1]){let v=c[1].split("\xB7").map(I=>I.trim());u=v[0]||null,v[1]&&(d=v[1])}let C=c.findIndex(v=>/(\d{4}|present)/i.test(v)&&/(-|–|—)/i.test(v)&&v.length<80),S=null,_=null;if(C>=0){let v=c[C].split("\xB7").map(I=>I.trim());S=v[0]||null,v[1]&&(_=v[1])}let g=null,h=-1;if(C>=0&&c[C+1]){let v=c[C+1],I=/^[>*\-•]|^&gt;/.test(v),ie=/https?:\/\//.test(v),le=/\d{4}/.test(v),T=/,/.test(v)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(v);!I&&!ie&&!le&&v.length<100&&T&&(g=v,h=C+1)}let B=null,$=-1,z=c[c.length-1];if(z&&/and\s+\+\d+\s+skills?$/i.test(z)){$=c.length-1;let v=z.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);v&&(B={listed:v[1].split(",").map(I=>I.trim()),additional:parseInt(v[2],10)})}let Q=new Set([0,1,C,h,$].filter(v=>v>=0)),J=c.filter((v,I)=>!Q.has(I)),D=J.length>0?J.join(`
1
+ var Dn=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>{for(var n in t)Dn(e,n,{get:t[n],enumerable:!0})};async function x(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function yt(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),a=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||i||a){let l=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(l)return l.click(),{dismissed:!0,matched:r.substring(0,80)};let m=o.querySelectorAll("button");for(let c of m){let w=c.innerText?.trim().toLowerCase()||"",u=c.getAttribute("aria-label")?.toLowerCase()||"";if(w==="not now"||w==="no thanks"||w==="dismiss"||u.includes("dismiss"))return c.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var pe=ce(()=>{});import{getPluginConfig as Tn}from"@ilivemylife/graph-sdk";var jn,On,Z,Rr,Nn,Oe=ce(async()=>{jn=await Tn();for(let[e,t]of Object.entries(jn))process.env[e]===void 0&&(process.env[e]=t);On=process.env.LINKEDIN_NAME,Z=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Rr=Object.freeze(new Set([Z.DRAFT,Z.CONFIRMED,Z.NEEDS_REVIEW])),Nn=Object.freeze(new Set([Z.DRAFT,Z.CONFIRMED,Z.REJECTED,Z.NEEDS_REVIEW]))});import"dotenv/config";import*as A from"fs";import*as E from"path";import{fileURLToPath as Yn}from"url";function Ut(){ae=null,Qn=null,Zn=null,Xn=null,eo=null,to=null}function Bt(){A.existsSync(V)||A.mkdirSync(V,{recursive:!0})}function Vt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";A.writeFileSync(o,n);for(let r=0;r<3;r++)try{A.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ht(e,t){if(!A.existsSync(e))return null;try{let n=JSON.parse(A.readFileSync(e,"utf-8"));try{A.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${E.resolve(e)}`);let o=e+".backup";if(A.existsSync(o))try{let r=JSON.parse(A.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{A.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{A.copyFileSync(e,e+".corrupted")}catch{}return null}}function no(){return new Date().toISOString().split("T")[0]}function X(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function Ft(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Jt(e,t,n=null){if(!t||e[t])return t;let o=X(t);if(!o)return t;let r=null;for(let[s,i]of Object.entries(e)){if(X(i.profileUrl||s)===o)return s;!r&&Array.isArray(i.aliases)&&i.aliases.includes(o)&&(r=s)}if(r){let s=Ft(n),i=Ft(e[r].name);if(s&&i&&s===i)return r}return t}function so(){A.existsSync(Pe)||A.mkdirSync(Pe,{recursive:!0})}function Wt(e){let t=X(e);return t?E.join(Pe,`${t}.json`):null}function io(e){let t=Wt(e);return t?Ht(t,`profile-history/${X(e)}.json`)||[]:[]}function lo(e,t){let n=Wt(e);if(!n)return;so();let o=io(e);o.unshift(t);try{Vt(n,o)}catch(r){console.error(`[!] Failed to append profile-history for ${X(e)}: ${r.message}`)}}function Pt(e){return!!(e==null||Array.isArray(e)&&e.length===0||typeof e=="string"&&!e.trim())}function Mt(e){return Array.isArray(e)?[...e].map(t=>String(t).trim()).sort().join("||"):typeof e=="string"?e.replace(/\s+/g," ").trim():e}function co(e,t){if(!e)return[];let n=[];for(let o of ro){let r=e[o],s=t[o];Pt(r)||Pt(s)||Mt(r)!==Mt(s)&&n.push(o)}return n}function ao(e){let t=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,r]of Object.entries(e))t.has(o)||(n[o]=r);return n}function ue(){return ae||(Bt(),ae=Ht(Fe,"people.json")||{},ae)}function Gt(e){Bt(),ae=e;try{Vt(Fe,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${E.resolve(Fe)}`)}}function Me(e,t={}){if(!e)return null;let n=ue(),o=no(),r=new Date().toISOString(),s=Jt(n,e,t.name),i=n[s];if(i){let a=co(i,t);a.length>0&&(lo(s,{capturedAt:r,previousLastUpdated:i.lastUpdated||null,changedFields:a,snapshot:ao(i)}),i.lastSnapshotAt=r),i.seenCount=(i.seenCount||1)+1,i.lastSeen=o,i.lastUpdated=r,t.source&&!i.sources?.includes(t.source)&&(i.sources=i.sources||[],i.sources.push(t.source));for(let l of oo)if(t[l]!=null){if(Array.isArray(t[l])&&t[l].length===0&&Array.isArray(i[l])&&i[l].length>0)continue;i[l]=t[l]}Array.isArray(t.availableSections)&&(i.lastFullVisitAt=r)}else n[s]={name:t.name||null,title:t.title||null,location:t.location||null,company:t.company||null,about:t.about||null,connectionDegree:t.connectionDegree||null,connectionsCount:t.connectionsCount||null,mutualConnections:t.mutualConnections||null,photoUrl:t.photoUrl||null,hasVerifiedBadge:t.hasVerifiedBadge||!1,currentCompany:t.currentCompany||null,currentSchool:t.currentSchool||null,connectionsLevel:t.connectionsLevel||null,mutualConnectionsCount:t.mutualConnectionsCount||null,followers:t.followers||null,openToWork:t.openToWork||!1,hiring:t.hiring||!1,topSkills:t.topSkills||null,availableSections:t.availableSections||null,experience:t.experience||null,featuredLinks:t.featuredLinks||null,_lastEnrichedAt:t._lastEnrichedAt||null,featured:t.featured||null,education:t.education||null,skillsFull:t.skillsFull||null,recommendations:t.recommendations||null,certifications:t.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:t.source?[t.source]:[],connectionStatus:null,requestedConnectionAt:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:r,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(t.availableSections)?r:null};return Gt(n),n[s]}function qe(e,t,n={}){if(n.dryRun||!e||!t)return;let o=X(t);if(!o)return;let r=ue(),s=Jt(r,e),i=r[s];if(!i)return;let a=X(i.profileUrl||s);o!==a&&(Array.isArray(i.aliases)||(i.aliases=[]),i.aliases.includes(o)||(i.aliases.push(o),i.lastUpdated=new Date().toISOString(),Gt(r)))}var Kn,zn,V,Fe,ts,ns,os,rs,ss,Pe,qt,is,ls,ae,Qn,Zn,Xn,eo,to,oo,ro,$e=ce(async()=>{await Oe();Kn=Yn(import.meta.url),zn=E.dirname(E.dirname(Kn)),V=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"collected-profiles"):E.join(zn,"collected-profiles"),Fe=E.join(V,"people.json"),ts=E.join(V,"jobs.json"),ns=E.join(V,"quota.json"),os=E.join(V,"conversations.json"),rs=E.join(V,"sync-state.json"),ss=E.join(V,"application-questions.json"),Pe=E.join(V,"profile-history"),qt=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},is=qt(process.env.CONNECT_MAX_DAILY,20),ls=qt(process.env.CONNECT_MAX_WEEKLY,100),ae=null,Qn=null,Zn=null,Xn=null,eo=null,to=null;oo=["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"],ro=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"]});var Yt={};me(Yt,{extractCertificationsFromDetails:()=>ho,extractEducationFromDetails:()=>mo,extractExperienceFromDetails:()=>uo,extractFeaturedFromDetails:()=>fo,extractRecommendationsFromDetails:()=>go,extractSkillsFromDetails:()=>po});async function uo(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await e.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await x(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 s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await x(900);await x(1e3);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 x(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await x(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(c){let w=[];for(let u of c.querySelectorAll("div")){let d=Array.from(u.children).filter(S=>S.tagName==="DIV");if(d.length<3)continue;let C=d.filter(S=>(S.textContent||"").trim().length>50);C.length<3||(u.textContent||"").length<500||w.push({el:u,count:C.length,totalText:(u.textContent||"").length})}return w.sort((u,d)=>d.count-u.count||u.totalText-d.totalText),w[0]?.el}let a=i(s);if(!a)return[];let l=Array.from(a.children).filter(c=>c.tagName==="DIV").filter(c=>(c.textContent||"").trim().length>50);function m(c){let w=c[0]||null,u=null,d=null;if(c[1]){let v=c[1].split("\xB7").map(I=>I.trim());u=v[0]||null,v[1]&&(d=v[1])}let C=c.findIndex(v=>/(\d{4}|present)/i.test(v)&&/(-|–|—)/i.test(v)&&v.length<80),S=null,_=null;if(C>=0){let v=c[C].split("\xB7").map(I=>I.trim());S=v[0]||null,v[1]&&(_=v[1])}let g=null,h=-1;if(C>=0&&c[C+1]){let v=c[C+1],I=/^[>*\-•]|^&gt;/.test(v),ie=/https?:\/\//.test(v),le=/\d{4}/.test(v),R=/,/.test(v)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(v);!I&&!ie&&!le&&v.length<100&&R&&(g=v,h=C+1)}let B=null,$=-1,z=c[c.length-1];if(z&&/and\s+\+\d+\s+skills?$/i.test(z)){$=c.length-1;let v=z.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);v&&(B={listed:v[1].split(",").map(I=>I.trim()),additional:parseInt(v[2],10)})}let Q=new Set([0,1,C,h,$].filter(v=>v>=0)),J=c.filter((v,I)=>!Q.has(I)),T=J.length>0?J.join(`
2
2
 
3
- `):null;return{title:w,company:u,employmentType:d,dates:S,duration:_,location:g,description:D,skills:B,_raw:c}}return l.map(c=>{let u=(c.innerText||"").trim().split(`
3
+ `):null;return{title:w,company:u,employmentType:d,dates:S,duration:_,location:g,description:T,skills:B,_raw:c}}return l.map(c=>{let u=(c.innerText||"").trim().split(`
4
4
  `).map(d=>d.trim()).filter(d=>d&&d.length<5e3);return m(u)}).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 ye(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await e.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await x(3e3);let r=e.url();if(/\/(login|authwall|checkpoint)/i.test(r))throw new Error(`Session expired \u2014 bounced to ${r} when fetching /details/${n}/`);if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await x(700);await x(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let a of document.querySelectorAll("button"))if(/^Load more$/i.test((a.textContent||"").trim()))return a.click(),!0;return!1});)s++,await x(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await x(600)}async function be(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function fo(e,t){return be(t,"featured","extractFeaturedFromDetails",async()=>(await ye(e,t,"featured"),await e.evaluate(`(() => {
5
5
  ${we}
6
6
 
@@ -235,14 +235,14 @@ function findEntryContainer(root) {
235
235
  candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
236
236
  return candidates[0]?.el;
237
237
  }
238
- `});var Qt=ce(()=>{});import"dotenv/config";import*as O from"fs";import*as j from"path";import{fileURLToPath as wo}from"url";function Co(){O.existsSync(te)||O.mkdirSync(te,{recursive:!0})}function xo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ue(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function Xt(){Se=null,$o=null,ve=null,Eo=null,ee=null}function Ao(){return Se||(Se=Ue(vo)||{},Se)}function Ee(){return ve||(ve=Ue(ko)||{},ve)}function fe(){return ee||(ee=Ue(Zt)||{visits:[]},Array.isArray(ee.visits)||(ee.visits=[]),ee)}function en(e,t={}){if(!e)return;Co();let n=fe();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(r=>new Date(r.date).getTime()>o);try{xo(Zt,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function tn(e){let t=fe();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function nn(){let e=Ao(),t=Ee(),n=Object.values(e),o=Object.values(t),r={};for(let u of n)u.company&&(r[u.company]=(r[u.company]||0)+1);let s=Object.entries(r).sort((u,d)=>d[1]-u[1]).slice(0,5).map(([u,d])=>`${u} (${d})`),i={};for(let u of n)for(let d of u.techStack||[])i[d]=(i[d]||0)+1;let a=Object.entries(i).sort((u,d)=>d[1]-u[1]).slice(0,8).map(([u,d])=>`${u} (${d})`),l=fe(),m=new Date().toISOString().slice(0,10),c=l.visits.filter(u=>u.date.startsWith(m)).length,w=new Set(l.visits.map(u=>u.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:a,totalVisited:w,todayVisited:c,lastScoutDate:n.length>0?n.sort((u,d)=>(d.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}var bo,So,te,vo,ko,Zt,xs,As,Se,$o,ve,Eo,ee,_e=ce(()=>{Qt();bo=wo(import.meta.url),So=j.dirname(j.dirname(bo)),te=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"market-research"):j.join(So,"market-research"),vo=j.join(te,"scouted-jobs.json"),ko=j.join(te,"discovered-people.json"),Zt=j.join(te,"visit-log.json"),xs=j.join(te,"companies.json"),As=j.join(te,"job-decisions.json");Se=null;$o=null,ve=null;Eo=null,ee=null});import Jn from"puppeteer";import{addExtra as Wn}from"puppeteer-extra";import Gn from"puppeteer-extra-plugin-stealth";pe();await Oe();import q from"fs";import G from"path";var Ln="cookies.json";function wt(){let e=process.env.ILML_SCOPE_DIR;return e?G.join(e,"plugins-state","linkedin","cookies.json"):Ln}function bt(){let e=wt();if(!q.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=q.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function St(){return q.existsSync(wt())}function Fn(){let e=process.env.ILML_SCOPE_DIR;return e?G.join(e,"plugins-state","linkedin"):"."}function vt(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Pn(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?vt(t[1]):"default"}function kt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return q.existsSync(t)||q.mkdirSync(t,{recursive:!0}),G.resolve(t);let n=vt(e||Pn()),o=G.join(Fn(),"chrome-profile",n);return q.existsSync(o)||q.mkdirSync(o,{recursive:!0}),G.resolve(o)}var Ct=".ilml-seeded";function xt(e){return!q.existsSync(G.join(e,Ct))}function At(e){try{q.writeFileSync(G.join(e,Ct),new Date().toISOString())}catch{}}function $t(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{q.rmSync(G.join(e,n),{force:!0}),t++}catch{}return t}import Ne from"fs";import Mn from"path";var qn={headless:!1,defaultViewport:null,protocolTimeout:3e5},ge=new Set,Et=!1;async function Ae(){let e=[...ge].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ge.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Un(){if(Et)return;Et=!0;let e=t=>async()=>{await Ae(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ae(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ae(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ae(),process.exit(0))}),process.on("exit",()=>{for(let t of ge)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Le(e){return Mn.join(e,".ilml-browser-session.json")}function Rt(e,t={}){try{Ne.writeFileSync(Le(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Bn(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Rt(e,n?{wsEndpoint:n}:{})}catch{}}function Vn(e){let t=Dt(e);t&&t.ownerPid===process.pid&&he(e)}function he(e){try{Ne.rmSync(Le(e),{force:!0})}catch{}}function Dt(e){try{return JSON.parse(Ne.readFileSync(Le(e),"utf-8"))}catch{return null}}function _t(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function It(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Tt(e,t,{probeTimeoutMs:n=4e3}={}){let o=Dt(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&_t(o.ownerPid)?"live":(he(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await It(s,n,r);if(i===r)return s.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!i)return he(t),"free";if(_t(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await It(i.close().then(()=>!0).catch(()=>!1),n,!1))return he(t),"free";try{i.disconnect()}catch{}return"live"}function Hn(e,t){e&&(Un(),ge.add(e),e.on("disconnected",()=>{ge.delete(e),t&&he(t)}))}async function jt(e,t={}){let n=kt(),o={...qn,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Tt(e,n)==="live")throw new Error(r);Rt(n);let s;try{s=await e.launch(o)}catch{if(await Tt(e,n)==="live")throw new Error(r);$t(n);try{s=await e.launch(o)}catch(a){throw Vn(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return Hn(s,n),Bn(n,s),{browser:s,profileDir:n,needsSeed:xt(n)}}async function Ot(e,t){if(!t||!t.needsSeed)return!1;if(!St())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...bt()),At(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Nt=Wn(Jn);Nt.use(Gn());async function Lt(){let{browser:e,profileDir:t,needsSeed:n}=await jt(Nt),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ot(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}pe();await $e();async function yo(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: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await x(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function zt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await x(3e3),await yt(e)&&(console.log(" Dismissed Premium overlay"),await x(1500),await yo(e,t));let c=0;for(let $=0;$<2;$++){let z=await e.evaluate(()=>document.body.scrollHeight);for(let J=1;J<=6;J++)await e.evaluate(D=>window.scrollTo(0,D),z*J/6),await x(900);let Q=await e.evaluate(()=>document.body.scrollHeight);if(Q===c)break;c=Q}await x(800);let w=null;try{let $=e.url();$&&/\/in\/[^/?#]/.test($)&&(w=$.split("?")[0].replace(/\/+$/,""))}catch{}let u=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"]),z=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=p=>{let y=(p||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(y)},J={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},D=document.querySelector("main");if(!D)return J;let v=[...Array.from(D.querySelectorAll("h1")),...Array.from(D.querySelectorAll("h2"))],I=Array.from(D.querySelectorAll("h2")),ie=v.find(p=>{let y=p.textContent&&p.textContent.trim(),b=(y||"").replace(/\s*\(\d+\)$/,"").trim();return y&&y.length>1&&y.length<100&&!$.has(b)&&!z.has(b)}),le=ie?ie.textContent.trim():null,T=ie?ie.parentElement:null;for(;T&&T!==D&&!Array.from(T.children).filter(y=>y.tagName==="P").some(y=>{let b=y.textContent&&y.textContent.trim();return b&&b.length>5&&!Q(b)});)T=T.parentElement;let ot=null,rt=null,st=null,De=null;if(T&&T!==D){let p=Array.from(T.children).filter(b=>b.tagName==="P").filter(b=>{let W=b.textContent&&b.textContent.trim();return W&&W.length>5&&!Q(W)});if(p[0]&&(ot=p[0].textContent.trim()),p[1]){let b=p[1].textContent.trim().split(/\s*[·•]\s*/);rt=b[0]||null,b.length>1&&(st=b.slice(1).join(" \xB7 "))}let y=Array.from(T.children).filter(b=>b.tagName==="DIV");for(let b=y.length-1;b>=0;b--){let W=y[b].textContent&&y[b].textContent.trim();if(W&&!(le&&W.startsWith(le))&&(De=W.split(/[·•]/)[0].trim(),De))break}}let it=null;if(T){let p=T.querySelectorAll("p, span, div");for(let y of p){let b=(y.textContent||"").trim().replace(/^[·•]\s*/,"");if(b==="1st"||b==="2nd"||b==="3rd"){it=b;break}}}let xn=!!D.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),lt=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),An=lt&&lt.src||null,Ce=D.textContent||"",ct=null,at=Ce.match(/(\d+\+?)\s+connections\b/i);at&&(ct=at[1]+" connections");let xe=null,ut=Ce.match(/(\d+)\s+mutual connection/i),ft=Ce.match(/and\s+(\d+)\s+other mutual/i),$n=Ce.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ut?xe=parseInt(ut[1],10):ft?xe=2+parseInt(ft[1],10):$n&&(xe=2);let dt=null,mt=null,pt=I.find(p=>p.textContent&&p.textContent.trim()==="About");if(pt){let p=pt.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let y=(p.textContent||"").trim();y=y.replace(/^About\s*/,"").trim();let b=y.match(/Top skills\s*(.+?)$/i);if(b){let je=b[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Tn=>Tn.trim()).filter(Boolean);je.length>0&&je.length<10&&(mt=je)}y=y.split(/\n?…\s*more/i)[0].trim(),y=y.split(/\n?\.\.\.\s*more/i)[0].trim(),y=y.split(/\bTop skills\b/i)[0].trim(),y=y.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),dt=y||null}}let ht=null,gt=I.find(p=>p.textContent&&p.textContent.trim()==="Activity");if(gt){let p=gt.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let y=(p.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);y&&(ht=parseInt(y[1].replace(/,/g,""),10))}}let En=[...new Set(I.map(p=>(p.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(p=>p&&p.length>1&&p.length<60&&p!==le).filter(p=>$.has(p)))],de=document.body.textContent||"",_n=/#OpenToWork\b/i.test(de)||/\bOpen to work\b/.test(de),In=/#Hiring\b/i.test(de)||/\bI'?m hiring\b/i.test(de)||/\bWe are hiring\b/i.test(de);return{name:le,title:ot,location:De,currentCompany:rt,currentSchool:st,connectionDegree:it,hasVerifiedBadge:xn,photoUrl:An,connectionsLevel:ct,mutualConnectionsCount:xe,followers:ht,openToWork:_n,hiring:In,about:dt,topSkills:mt,availableSections:En}});console.log(`Viewed: ${u.name} - ${u.title}`);let d=null,C=null,S=null,_=null,g=null,h=null;if(o||r||s||i||a||l){let $=await Promise.resolve().then(()=>(Kt(),Yt));o&&(d=await $.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),r&&(C=await $.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${C.length} entries`)),s&&(S=await $.extractEducationFromDetails(e,t),console.log(` + Education: ${S.length} entries`)),i&&(_=await $.extractSkillsFromDetails(e,t),console.log(` + Skills: ${_.length} entries`)),a&&(g=await $.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${g.length} entries`)),l&&(h=await $.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${h.length} entries`))}return{...u,profileUrl:t,resolvedUrl:w,...d!==null&&{experience:d},...C!==null&&{featured:C},...S!==null&&{education:S},..._!==null&&{skillsFull:_},...g!==null&&{recommendations:g},...h!==null&&{certifications:h}}}catch(m){console.error(`Error viewing profile ${t}:`,m.message);try{await e.goto("about:blank",{timeout:1e4}),await x(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(m.message||""))throw m;return null}}_e();await $e();pe();async function on(e,t,n={}){let{maxVisits:o=50,delayBetween:r=4e3,skipRecentDays:s=7,verbose:i=!1,extractExperience:a=!1}=n,l={visited:0,skipped:0,errors:0},m=Date.now()-s*24*60*60*1e3;for(let c of t){if(l.visited>=o)break;if(!c.profileUrl)continue;let w=tn(c.profileUrl);if(w&&new Date(w).getTime()>m){l.skipped++;continue}try{let u=await zt(e,c.profileUrl,{extractExperience:a}),d=c.source||"visit";if(u){let S={...u,source:d};a&&Array.isArray(u.experience)&&u.experience.length>0&&(S._lastEnrichedAt=new Date().toISOString()),Me(c.profileUrl,S),u.resolvedUrl&&qe(c.profileUrl,u.resolvedUrl)}en(c.profileUrl,{name:u?.name||c.name||null,source:d}),l.visited++,i?console.log(` [${l.visited}] ${u?.name||c.profileUrl} \u2014 ${u?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let C=Math.random()*4e3;await x(r+C)}catch(u){l.errors++,i&&console.error(` Error visiting ${c.name||c.profileUrl}: ${u.message?.slice(0,60)}`);let d=(u.message||"").toLowerCase();if(d.includes("detached")||d.includes("session closed")||d.includes("target closed")||d.includes("session expired")||d.includes("bounced to")||d.includes("authwall")||d.includes("checkpoint")||d.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return l}function rn(e={}){let{limit:t=150,revisitDays:n=14}=e,o=fe(),r=new Set(o.visits?.map(g=>g.profileUrl)||[]),s=new Map;for(let g of o.visits||[]){let h=s.get(g.profileUrl);(!h||g.date>h)&&s.set(g.profileUrl,g.date)}let i=Date.now()-7*24*60*60*1e3,a=Date.now()-n*24*60*60*1e3;function l(g){let h=s.get(g);return h&&new Date(h).getTime()>i}let m=Ee(),c=Object.entries(m).filter(([g])=>!r.has(g)).map(([g,h])=>({profileUrl:g,name:h.name,source:"new-discovered",priority:1,jobCount:h.jobIds?.length||0})),w=ue(),u=Object.entries(w).filter(([g,h])=>h.connectionStatus==="connected"||l(g)?!1:(h.jobCount||h.jobIds?.length||0)>=2).map(([g,h])=>({profileUrl:g,name:h.name,source:"active-recruiter",priority:2,jobCount:h.jobCount||h.jobIds?.length||0})),d=Object.entries(w).filter(([g,h])=>{let B=h.connectionStatus;return!(!B||B==="connected"||B==="pending"||B==="sent_without_note"||B==="sent_with_note"||l(g)||(h.jobCount||h.jobIds?.length||0)>=2)}).map(([g,h])=>({profileUrl:g,name:h.name,source:"unconnected",priority:3,jobCount:h.jobCount||h.jobIds?.length||0})),C=[...s.entries()].filter(([g,h])=>new Date(h).getTime()<a).map(([g,h])=>({profileUrl:g,name:null,source:"revisit",priority:4,lastVisit:h})),S=g=>g.sort(()=>Math.random()-.5);return c.sort((g,h)=>h.jobCount-g.jobCount),u.sort((g,h)=>h.jobCount-g.jobCount),S(d),S(C),[...c,...u,...d,...C].slice(0,t)}function sn(){let e=Ee();return Object.entries(e).map(([t,n])=>({profileUrl:t,name:n.name,source:"discovered"}))}function Be(){let e=ue();return Object.entries(e).filter(([,t])=>{let n=t.connectionStatus;return n&&n!=="connected"&&n!=="pending"&&n!=="sent_without_note"&&n!=="sent_with_note"}).map(([t,n])=>({profileUrl:t,name:n.name,source:"unconnected"}))}function Ve(e=14){let t=fe(),n=Date.now()-e*24*60*60*1e3,o=new Map;for(let r of t.visits){let s=o.get(r.profileUrl);(!s||r.date>s.date)&&o.set(r.profileUrl,r)}return[...o.entries()].filter(([,r])=>new Date(r.date).getTime()<n).map(([r,s])=>({profileUrl:r,name:s.name,source:"revisit"}))}_e();import"dotenv/config";import*as N from"fs";import*as Y from"path";import{fileURLToPath as jo}from"url";import"dotenv/config";import{createGraphClient as _o,resolveToken as Io}from"@ilivemylife/graph-sdk";import{config as To}from"dotenv";To();var ln=Io()||process.env.TOKEN;ln||(console.error(`
238
+ `});var Qt=ce(()=>{});import"dotenv/config";import*as O from"fs";import*as j from"path";import{fileURLToPath as wo}from"url";function Co(){O.existsSync(te)||O.mkdirSync(te,{recursive:!0})}function xo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let r=0;r<3;r++)try{O.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ue(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function Xt(){Se=null,$o=null,ve=null,Eo=null,ee=null}function Ao(){return Se||(Se=Ue(vo)||{},Se)}function Ee(){return ve||(ve=Ue(ko)||{},ve)}function fe(){return ee||(ee=Ue(Zt)||{visits:[]},Array.isArray(ee.visits)||(ee.visits=[]),ee)}function en(e,t={}){if(!e)return;Co();let n=fe();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(r=>new Date(r.date).getTime()>o);try{xo(Zt,n)}catch(r){console.error(`[!] Failed to save visit-log.json: ${r.message}`)}}function tn(e){let t=fe();for(let n=t.visits.length-1;n>=0;n--)if(t.visits[n].profileUrl===e)return t.visits[n].date;return null}function nn(){let e=Ao(),t=Ee(),n=Object.values(e),o=Object.values(t),r={};for(let u of n)u.company&&(r[u.company]=(r[u.company]||0)+1);let s=Object.entries(r).sort((u,d)=>d[1]-u[1]).slice(0,5).map(([u,d])=>`${u} (${d})`),i={};for(let u of n)for(let d of u.techStack||[])i[d]=(i[d]||0)+1;let a=Object.entries(i).sort((u,d)=>d[1]-u[1]).slice(0,8).map(([u,d])=>`${u} (${d})`),l=fe(),m=new Date().toISOString().slice(0,10),c=l.visits.filter(u=>u.date.startsWith(m)).length,w=new Set(l.visits.map(u=>u.profileUrl)).size;return{totalJobs:n.length,totalRecruiters:o.length,topCompanies:s,topTech:a,totalVisited:w,todayVisited:c,lastScoutDate:n.length>0?n.sort((u,d)=>(d.scoutedAt||"").localeCompare(u.scoutedAt||""))[0]?.scoutedAt:null}}var bo,So,te,vo,ko,Zt,As,$s,Se,$o,ve,Eo,ee,_e=ce(()=>{Qt();bo=wo(import.meta.url),So=j.dirname(j.dirname(bo)),te=process.env.DATA_DIR?j.resolve(process.env.DATA_DIR,"market-research"):j.join(So,"market-research"),vo=j.join(te,"scouted-jobs.json"),ko=j.join(te,"discovered-people.json"),Zt=j.join(te,"visit-log.json"),As=j.join(te,"companies.json"),$s=j.join(te,"job-decisions.json");Se=null;$o=null,ve=null;Eo=null,ee=null});import Jn from"puppeteer";import{addExtra as Wn}from"puppeteer-extra";import Gn from"puppeteer-extra-plugin-stealth";pe();await Oe();import q from"fs";import G from"path";var Ln="cookies.json";function wt(){let e=process.env.ILML_SCOPE_DIR;return e?G.join(e,"plugins-state","linkedin","cookies.json"):Ln}function bt(){let e=wt();if(!q.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=q.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function St(){return q.existsSync(wt())}function Fn(){let e=process.env.ILML_SCOPE_DIR;return e?G.join(e,"plugins-state","linkedin"):"."}function vt(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Pn(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?vt(t[1]):"default"}function kt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return q.existsSync(t)||q.mkdirSync(t,{recursive:!0}),G.resolve(t);let n=vt(e||Pn()),o=G.join(Fn(),"chrome-profile",n);return q.existsSync(o)||q.mkdirSync(o,{recursive:!0}),G.resolve(o)}var Ct=".ilml-seeded";function xt(e){return!q.existsSync(G.join(e,Ct))}function At(e){try{q.writeFileSync(G.join(e,Ct),new Date().toISOString())}catch{}}function $t(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{q.rmSync(G.join(e,n),{force:!0}),t++}catch{}return t}import Ne from"fs";import Mn from"path";var qn={headless:!1,defaultViewport:null,protocolTimeout:3e5},ge=new Set,Et=!1;async function Ae(){let e=[...ge].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ge.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Un(){if(Et)return;Et=!0;let e=t=>async()=>{await Ae(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Ae(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Ae(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Ae(),process.exit(0))}),process.on("exit",()=>{for(let t of ge)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function Le(e){return Mn.join(e,".ilml-browser-session.json")}function Dt(e,t={}){try{Ne.writeFileSync(Le(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Bn(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Dt(e,n?{wsEndpoint:n}:{})}catch{}}function Vn(e){let t=Tt(e);t&&t.ownerPid===process.pid&&he(e)}function he(e){try{Ne.rmSync(Le(e),{force:!0})}catch{}}function Tt(e){try{return JSON.parse(Ne.readFileSync(Le(e),"utf-8"))}catch{return null}}function _t(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function It(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Rt(e,t,{probeTimeoutMs:n=4e3}={}){let o=Tt(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&_t(o.ownerPid)?"live":(he(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await It(s,n,r);if(i===r)return s.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!i)return he(t),"free";if(_t(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await It(i.close().then(()=>!0).catch(()=>!1),n,!1))return he(t),"free";try{i.disconnect()}catch{}return"live"}function Hn(e,t){e&&(Un(),ge.add(e),e.on("disconnected",()=>{ge.delete(e),t&&he(t)}))}async function jt(e,t={}){let n=kt(),o={...qn,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Rt(e,n)==="live")throw new Error(r);Dt(n);let s;try{s=await e.launch(o)}catch{if(await Rt(e,n)==="live")throw new Error(r);$t(n);try{s=await e.launch(o)}catch(a){throw Vn(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${a.message})`)}}return Hn(s,n),Bn(n,s),{browser:s,profileDir:n,needsSeed:xt(n)}}async function Ot(e,t){if(!t||!t.needsSeed)return!1;if(!St())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...bt()),At(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Nt=Wn(Jn);Nt.use(Gn());async function Lt(){let{browser:e,profileDir:t,needsSeed:n}=await jt(Nt),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ot(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}pe();await $e();async function yo(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: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await x(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function zt(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:a=!1,extractCertifications:l=!1}=n;try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await x(3e3),await yt(e)&&(console.log(" Dismissed Premium overlay"),await x(1500),await yo(e,t));let c=0;for(let $=0;$<2;$++){let z=await e.evaluate(()=>document.body.scrollHeight);for(let J=1;J<=6;J++)await e.evaluate(T=>window.scrollTo(0,T),z*J/6),await x(900);let Q=await e.evaluate(()=>document.body.scrollHeight);if(Q===c)break;c=Q}await x(800);let w=null;try{let $=e.url();$&&/\/in\/[^/?#]/.test($)&&(w=$.split("?")[0].replace(/\/+$/,""))}catch{}let u=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"]),z=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=p=>{let y=(p||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(y)},J={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:[]},T=document.querySelector("main");if(!T)return J;let v=[...Array.from(T.querySelectorAll("h1")),...Array.from(T.querySelectorAll("h2"))],I=Array.from(T.querySelectorAll("h2")),ie=v.find(p=>{let y=p.textContent&&p.textContent.trim(),b=(y||"").replace(/\s*\(\d+\)$/,"").trim();return y&&y.length>1&&y.length<100&&!$.has(b)&&!z.has(b)}),le=ie?ie.textContent.trim():null,R=ie?ie.parentElement:null;for(;R&&R!==T&&!Array.from(R.children).filter(y=>y.tagName==="P").some(y=>{let b=y.textContent&&y.textContent.trim();return b&&b.length>5&&!Q(b)});)R=R.parentElement;let ot=null,rt=null,st=null,Te=null;if(R&&R!==T){let p=Array.from(R.children).filter(b=>b.tagName==="P").filter(b=>{let W=b.textContent&&b.textContent.trim();return W&&W.length>5&&!Q(W)});if(p[0]&&(ot=p[0].textContent.trim()),p[1]){let b=p[1].textContent.trim().split(/\s*[·•]\s*/);rt=b[0]||null,b.length>1&&(st=b.slice(1).join(" \xB7 "))}let y=Array.from(R.children).filter(b=>b.tagName==="DIV");for(let b=y.length-1;b>=0;b--){let W=y[b].textContent&&y[b].textContent.trim();if(W&&!(le&&W.startsWith(le))&&(Te=W.split(/[·•]/)[0].trim(),Te))break}}let it=null;if(R){let p=R.querySelectorAll("p, span, div");for(let y of p){let b=(y.textContent||"").trim().replace(/^[·•]\s*/,"");if(b==="1st"||b==="2nd"||b==="3rd"){it=b;break}}}let xn=!!T.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),lt=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),An=lt&&lt.src||null,Ce=T.textContent||"",ct=null,at=Ce.match(/(\d+\+?)\s+connections\b/i);at&&(ct=at[1]+" connections");let xe=null,ut=Ce.match(/(\d+)\s+mutual connection/i),ft=Ce.match(/and\s+(\d+)\s+other mutual/i),$n=Ce.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ut?xe=parseInt(ut[1],10):ft?xe=2+parseInt(ft[1],10):$n&&(xe=2);let dt=null,mt=null,pt=I.find(p=>p.textContent&&p.textContent.trim()==="About");if(pt){let p=pt.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let y=(p.textContent||"").trim();y=y.replace(/^About\s*/,"").trim();let b=y.match(/Top skills\s*(.+?)$/i);if(b){let je=b[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Rn=>Rn.trim()).filter(Boolean);je.length>0&&je.length<10&&(mt=je)}y=y.split(/\n?…\s*more/i)[0].trim(),y=y.split(/\n?\.\.\.\s*more/i)[0].trim(),y=y.split(/\bTop skills\b/i)[0].trim(),y=y.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),dt=y||null}}let ht=null,gt=I.find(p=>p.textContent&&p.textContent.trim()==="Activity");if(gt){let p=gt.parentElement;for(;p&&p.tagName!=="SECTION";)p=p.parentElement;if(p){let y=(p.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);y&&(ht=parseInt(y[1].replace(/,/g,""),10))}}let En=[...new Set(I.map(p=>(p.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(p=>p&&p.length>1&&p.length<60&&p!==le).filter(p=>$.has(p)))],de=document.body.textContent||"",_n=/#OpenToWork\b/i.test(de)||/\bOpen to work\b/.test(de),In=/#Hiring\b/i.test(de)||/\bI'?m hiring\b/i.test(de)||/\bWe are hiring\b/i.test(de);return{name:le,title:ot,location:Te,currentCompany:rt,currentSchool:st,connectionDegree:it,hasVerifiedBadge:xn,photoUrl:An,connectionsLevel:ct,mutualConnectionsCount:xe,followers:ht,openToWork:_n,hiring:In,about:dt,topSkills:mt,availableSections:En}});console.log(`Viewed: ${u.name} - ${u.title}`);let d=null,C=null,S=null,_=null,g=null,h=null;if(o||r||s||i||a||l){let $=await Promise.resolve().then(()=>(Kt(),Yt));o&&(d=await $.extractExperienceFromDetails(e,t),console.log(` + Experience: ${d.length} entries`)),r&&(C=await $.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${C.length} entries`)),s&&(S=await $.extractEducationFromDetails(e,t),console.log(` + Education: ${S.length} entries`)),i&&(_=await $.extractSkillsFromDetails(e,t),console.log(` + Skills: ${_.length} entries`)),a&&(g=await $.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${g.length} entries`)),l&&(h=await $.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${h.length} entries`))}return{...u,profileUrl:t,resolvedUrl:w,...d!==null&&{experience:d},...C!==null&&{featured:C},...S!==null&&{education:S},..._!==null&&{skillsFull:_},...g!==null&&{recommendations:g},...h!==null&&{certifications:h}}}catch(m){console.error(`Error viewing profile ${t}:`,m.message);try{await e.goto("about:blank",{timeout:1e4}),await x(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(m.message||""))throw m;return null}}_e();await $e();pe();async function on(e,t,n={}){let{maxVisits:o=50,delayBetween:r=4e3,skipRecentDays:s=7,verbose:i=!1,extractExperience:a=!1}=n,l={visited:0,skipped:0,errors:0},m=Date.now()-s*24*60*60*1e3;for(let c of t){if(l.visited>=o)break;if(!c.profileUrl)continue;let w=tn(c.profileUrl);if(w&&new Date(w).getTime()>m){l.skipped++;continue}try{let u=await zt(e,c.profileUrl,{extractExperience:a}),d=c.source||"visit";if(u){let S={...u,source:d};a&&Array.isArray(u.experience)&&u.experience.length>0&&(S._lastEnrichedAt=new Date().toISOString()),Me(c.profileUrl,S),u.resolvedUrl&&qe(c.profileUrl,u.resolvedUrl)}en(c.profileUrl,{name:u?.name||c.name||null,source:d}),l.visited++,i?console.log(` [${l.visited}] ${u?.name||c.profileUrl} \u2014 ${u?.title?.slice(0,40)||"?"}`):l.visited%10===0&&console.log(` Visited: ${l.visited}`);let C=Math.random()*4e3;await x(r+C)}catch(u){l.errors++,i&&console.error(` Error visiting ${c.name||c.profileUrl}: ${u.message?.slice(0,60)}`);let d=(u.message||"").toLowerCase();if(d.includes("detached")||d.includes("session closed")||d.includes("target closed")||d.includes("session expired")||d.includes("bounced to")||d.includes("authwall")||d.includes("checkpoint")||d.includes("redirected to login")){console.log(" Fatal browser/session error \u2014 stopping visits");break}}}return l}function rn(e={}){let{limit:t=150,revisitDays:n=14}=e,o=fe(),r=new Set(o.visits?.map(g=>g.profileUrl)||[]),s=new Map;for(let g of o.visits||[]){let h=s.get(g.profileUrl);(!h||g.date>h)&&s.set(g.profileUrl,g.date)}let i=Date.now()-7*24*60*60*1e3,a=Date.now()-n*24*60*60*1e3;function l(g){let h=s.get(g);return h&&new Date(h).getTime()>i}let m=Ee(),c=Object.entries(m).filter(([g])=>!r.has(g)).map(([g,h])=>({profileUrl:g,name:h.name,source:"new-discovered",priority:1,jobCount:h.jobIds?.length||0})),w=ue(),u=Object.entries(w).filter(([g,h])=>h.connectionStatus==="connected"||l(g)?!1:(h.jobCount||h.jobIds?.length||0)>=2).map(([g,h])=>({profileUrl:g,name:h.name,source:"active-recruiter",priority:2,jobCount:h.jobCount||h.jobIds?.length||0})),d=Object.entries(w).filter(([g,h])=>{let B=h.connectionStatus;return!(!B||B==="connected"||B==="pending"||B==="sent_without_note"||B==="sent_with_note"||l(g)||(h.jobCount||h.jobIds?.length||0)>=2)}).map(([g,h])=>({profileUrl:g,name:h.name,source:"unconnected",priority:3,jobCount:h.jobCount||h.jobIds?.length||0})),C=[...s.entries()].filter(([g,h])=>new Date(h).getTime()<a).map(([g,h])=>({profileUrl:g,name:null,source:"revisit",priority:4,lastVisit:h})),S=g=>g.sort(()=>Math.random()-.5);return c.sort((g,h)=>h.jobCount-g.jobCount),u.sort((g,h)=>h.jobCount-g.jobCount),S(d),S(C),[...c,...u,...d,...C].slice(0,t)}function sn(){let e=Ee();return Object.entries(e).map(([t,n])=>({profileUrl:t,name:n.name,source:"discovered"}))}function Be(){let e=ue();return Object.entries(e).filter(([,t])=>{let n=t.connectionStatus;return n&&n!=="connected"&&n!=="pending"&&n!=="sent_without_note"&&n!=="sent_with_note"}).map(([t,n])=>({profileUrl:t,name:n.name,source:"unconnected"}))}function Ve(e=14){let t=fe(),n=Date.now()-e*24*60*60*1e3,o=new Map;for(let r of t.visits){let s=o.get(r.profileUrl);(!s||r.date>s.date)&&o.set(r.profileUrl,r)}return[...o.entries()].filter(([,r])=>new Date(r.date).getTime()<n).map(([r,s])=>({profileUrl:r,name:s.name,source:"revisit"}))}_e();import"dotenv/config";import*as N from"fs";import*as Y from"path";import{fileURLToPath as jo}from"url";import"dotenv/config";import{createGraphClient as _o,resolveToken as Io}from"@ilivemylife/graph-sdk";import{config as Ro}from"dotenv";Ro();var ln=Io()||process.env.TOKEN;ln||(console.error(`
239
239
  [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.
240
240
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
241
241
  `),console.error(` Or add ILML_TOKEN=... to .env
242
- `),process.exit(1));var cn=_o({token:ln});function Ro(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 Do({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),a=r?` ${Ro(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",m=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${m} \u2014 ${l} \u2014 ${i}${a}`}async function an({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=`**${Do({scriptName:e,mode:t,status:n,error:r,duration:s})}**
242
+ `),process.exit(1));var cn=_o({token:ln});function Do(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 To({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),a=r?` ${Do(r)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",m=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${m} \u2014 ${l} \u2014 ${i}${a}`}async function an({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=`**${To({scriptName:e,mode:t,status:n,error:r,duration:s})}**
243
243
 
244
244
  ${o.join(`
245
- `)}`;try{await cn.addMessage(i,l)}catch(m){console.error(`[runReport] Failed to post end-of-session message: ${m.message}`)}}var Oo=jo(import.meta.url),No=Y.dirname(Y.dirname(Oo)),He=process.env.DATA_DIR?Y.resolve(process.env.DATA_DIR,"collected-profiles"):Y.join(No,"collected-profiles"),Je=Y.join(He,"run-log.json");function Lo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";N.writeFileSync(o,n);for(let r=0;r<3;r++)try{N.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function un(){try{if(!N.existsSync(Je))return{runs:[]};let e=JSON.parse(N.readFileSync(Je,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function fn(e){N.existsSync(He)||N.mkdirSync(He,{recursive:!0});try{Lo(Je,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function dn(e,t="default"){let n=un();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),fn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function We(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=un(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration;else{let l=i.runs.find(m=>m.script===e.script&&m.status==="running"&&m.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}fn(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";an({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import"dotenv/config";import*as f from"fs";import*as et from"os";import*as k from"path";import{fileURLToPath as ir}from"url";var Ke={};me(Ke,{NAME:()=>Po,VERSION:()=>Fo,up:()=>Uo});import*as L from"fs";import*as Ie from"path";var Fo=1,Po="normalize-jobs-and-questions",Mo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],qo=50;function Ge(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function Ye(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(r){try{L.unlinkSync(o)}catch{}throw r}try{L.renameSync(o,e)}catch(r){try{L.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Uo(e,t){let n=Ie.join(e,"jobs.json"),o=Ie.join(t,"scouted-jobs.json"),r=Ie.join(e,"application-questions.json"),s=Ge(n)||{},i=Ge(o)||{},a=0,l=[];for(let c of Object.keys(s)){if(!i[c])continue;let w=i[c],u=s[c];for(let d of Mo)w[d]!=null&&u[d]==null&&(u[d]=w[d]);l.push(c),a++}a>0?(Ye(n,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let m=Ge(r);if(m&&Array.isArray(m.applications)){let c={},w=0;for(let u of m.applications){let d=u.jobId||"unknown";c[d]||(c[d]={applications:[]});let C=(u.questions||[]).map(S=>{let _={type:S.type||"input",question:S.question||"",answer:S.answer||""};return S.options&&(S.options.length<=qo?_.options=S.options:(_.optionsOmitted=!0,w++)),S.page&&(_.page=S.page),S.wasPreFilled&&(_.wasPreFilled=!0),S.wasRetry&&(_.wasRetry=!0),_});c[d].applications.push({applicationId:u.applicationId,date:u.date,result:u.result||"submitted",formPages:u.formPages||null,duration:u.duration||null,retries:u.retries||0,failedField:u.failedField||null,questionCount:u.questionCount||C.length,questions:C})}Ye(r,c),console.log(` Phase 2: Rekeyed ${m.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else m&&!m.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let c of l)delete i[c];Ye(o,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ze={};me(ze,{NAME:()=>Vo,VERSION:()=>Bo,up:()=>Wo});import*as F from"fs";import*as mn from"path";var Bo=2,Vo="reset-unread-flags";function Ho(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function Jo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(r){try{F.unlinkSync(o)}catch{}throw r}try{F.renameSync(o,e)}catch(r){try{F.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Wo(e){let t=mn.join(e,"conversations.json"),n=Ho(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Jo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Qe={};me(Qe,{NAME:()=>Yo,VERSION:()=>Go,up:()=>Xo});import*as P from"fs";import*as pn from"path";var Go=3,Yo="recompute-last-message-by",Ko=new Set(["draft","confirmed","rejected","needs_review"]);function zo(e){return P.existsSync(e)?JSON.parse(P.readFileSync(e,"utf-8")):null}function Qo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{P.writeFileSync(o,n)}catch(r){try{P.unlinkSync(o)}catch{}throw r}try{P.renameSync(o,e)}catch(r){try{P.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function Zo(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!Ko.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Xo(e){let t=pn.join(e,"conversations.json"),n=zo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let a of Object.keys(n)){let l=n[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let m=Array.isArray(l.messages)?l.messages:[],c=Zo(m,o),w=c==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==c&&i++,l.lastMessageBy=c,l.conversationStatus=w,r++}if(r===0){console.log(" No conversations to recompute.");return}Qo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ze={};me(Ze,{NAME:()=>tr,VERSION:()=>er,up:()=>sr});import*as M from"fs";import*as hn from"path";var er=4,tr="split-connection-timestamps",nr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function or(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 rr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{M.writeFileSync(o,n)}catch(r){try{M.unlinkSync(o)}catch{}throw r}try{M.renameSync(o,e)}catch(r){try{M.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function sr(e){let t=hn.join(e,"people.json"),n=or(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,nr.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}rr(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await $e();_e();var lr=ir(import.meta.url),cr=k.dirname(lr),ar=k.dirname(k.dirname(cr));function ur(e){return e&&(e==="~"?et.homedir():e.startsWith("~/")||e.startsWith("~\\")?k.join(et.homedir(),e.slice(2)):e)}var U=process.env.DATA_DIR?k.resolve(ur(process.env.DATA_DIR)):ar,oe=k.join(U,"collected-profiles"),re=k.join(U,"market-research"),R=k.join(U,".schema-version"),gn=[k.join(oe,".schema-version"),k.join(re,".schema-version")],K=4,H=[{version:1,module:Ke},{version:2,module:ze},{version:3,module:Qe},{version:4,module:Ze}];(function(){H.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of H){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=H.length?H[H.length-1].version:0;if(n!==K)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${K}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<H.length;o++){let r=o+1;if(H[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${H[o].version}`)}})();function Sn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
245
+ `)}`;try{await cn.addMessage(i,l)}catch(m){console.error(`[runReport] Failed to post end-of-session message: ${m.message}`)}}var Oo=jo(import.meta.url),No=Y.dirname(Y.dirname(Oo)),He=process.env.DATA_DIR?Y.resolve(process.env.DATA_DIR,"collected-profiles"):Y.join(No,"collected-profiles"),Je=Y.join(He,"run-log.json");function Lo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";N.writeFileSync(o,n);for(let r=0;r<3;r++)try{N.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function un(){try{if(!N.existsSync(Je))return{runs:[]};let e=JSON.parse(N.readFileSync(Je,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function fn(e){N.existsSync(He)||N.mkdirSync(He,{recursive:!0});try{Lo(Je,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function dn(e,t="default"){let n=un();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),fn(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function We(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=un(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,r=a.duration;else{let l=i.runs.find(m=>m.script===e.script&&m.status==="running"&&m.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=l.duration)}fn(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";an({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import"dotenv/config";import*as f from"fs";import*as et from"os";import*as k from"path";import{fileURLToPath as ir}from"url";var Ke={};me(Ke,{NAME:()=>Po,VERSION:()=>Fo,up:()=>Uo});import*as L from"fs";import*as Ie from"path";var Fo=1,Po="normalize-jobs-and-questions",Mo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],qo=50;function Ge(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function Ye(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{L.writeFileSync(o,n)}catch(r){try{L.unlinkSync(o)}catch{}throw r}try{L.renameSync(o,e)}catch(r){try{L.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Uo(e,t){let n=Ie.join(e,"jobs.json"),o=Ie.join(t,"scouted-jobs.json"),r=Ie.join(e,"application-questions.json"),s=Ge(n)||{},i=Ge(o)||{},a=0,l=[];for(let c of Object.keys(s)){if(!i[c])continue;let w=i[c],u=s[c];for(let d of Mo)w[d]!=null&&u[d]==null&&(u[d]=w[d]);l.push(c),a++}a>0?(Ye(n,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let m=Ge(r);if(m&&Array.isArray(m.applications)){let c={},w=0;for(let u of m.applications){let d=u.jobId||"unknown";c[d]||(c[d]={applications:[]});let C=(u.questions||[]).map(S=>{let _={type:S.type||"input",question:S.question||"",answer:S.answer||""};return S.options&&(S.options.length<=qo?_.options=S.options:(_.optionsOmitted=!0,w++)),S.page&&(_.page=S.page),S.wasPreFilled&&(_.wasPreFilled=!0),S.wasRetry&&(_.wasRetry=!0),_});c[d].applications.push({applicationId:u.applicationId,date:u.date,result:u.result||"submitted",formPages:u.formPages||null,duration:u.duration||null,retries:u.retries||0,failedField:u.failedField||null,questionCount:u.questionCount||C.length,questions:C})}Ye(r,c),console.log(` Phase 2: Rekeyed ${m.applications.length} applications by jobId (${Object.keys(c).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else m&&!m.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let c of l)delete i[c];Ye(o,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ze={};me(ze,{NAME:()=>Vo,VERSION:()=>Bo,up:()=>Wo});import*as F from"fs";import*as mn from"path";var Bo=2,Vo="reset-unread-flags";function Ho(e){return F.existsSync(e)?JSON.parse(F.readFileSync(e,"utf-8")):null}function Jo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{F.writeFileSync(o,n)}catch(r){try{F.unlinkSync(o)}catch{}throw r}try{F.renameSync(o,e)}catch(r){try{F.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Wo(e){let t=mn.join(e,"conversations.json"),n=Ho(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Jo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Qe={};me(Qe,{NAME:()=>Yo,VERSION:()=>Go,up:()=>Xo});import*as P from"fs";import*as pn from"path";var Go=3,Yo="recompute-last-message-by",Ko=new Set(["draft","confirmed","rejected","needs_review"]);function zo(e){return P.existsSync(e)?JSON.parse(P.readFileSync(e,"utf-8")):null}function Qo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{P.writeFileSync(o,n)}catch(r){try{P.unlinkSync(o)}catch{}throw r}try{P.renameSync(o,e)}catch(r){try{P.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function Zo(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!Ko.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Xo(e){let t=pn.join(e,"conversations.json"),n=zo(t);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,s=0,i=0;for(let a of Object.keys(n)){let l=n[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,s++);let m=Array.isArray(l.messages)?l.messages:[],c=Zo(m,o),w=c==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==c&&i++,l.lastMessageBy=c,l.conversationStatus=w,r++}if(r===0){console.log(" No conversations to recompute.");return}Qo(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ze={};me(Ze,{NAME:()=>tr,VERSION:()=>er,up:()=>sr});import*as M from"fs";import*as hn from"path";var er=4,tr="split-connection-timestamps",nr=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function or(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 rr(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{M.writeFileSync(o,n)}catch(r){try{M.unlinkSync(o)}catch{}throw r}try{M.renameSync(o,e)}catch(r){try{M.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function sr(e){let t=hn.join(e,"people.json"),n=or(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,nr.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}rr(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}await $e();_e();var lr=ir(import.meta.url),cr=k.dirname(lr),ar=k.dirname(k.dirname(cr));function ur(e){return e&&(e==="~"?et.homedir():e.startsWith("~/")||e.startsWith("~\\")?k.join(et.homedir(),e.slice(2)):e)}var U=process.env.DATA_DIR?k.resolve(ur(process.env.DATA_DIR)):ar,oe=k.join(U,"collected-profiles"),re=k.join(U,"market-research"),D=k.join(U,".schema-version"),gn=[k.join(oe,".schema-version"),k.join(re,".schema-version")],K=4,H=[{version:1,module:Ke},{version:2,module:ze},{version:3,module:Qe},{version:4,module:Ze}];(function(){H.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of H){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=H.length?H[H.length-1].version:0;if(n!==K)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${K}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<H.length;o++){let r=o+1;if(H[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${H[o].version}`)}})();function Sn(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
246
246
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
247
247
  `),process.exit(1));try{f.mkdirSync(U,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
248
248
  [FATAL] Cannot create DATA_DIR (${U}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -255,16 +255,16 @@ ${o.join(`
255
255
  `),process.exit(1))}}var ne=k.join(U,".migration-lock");function fr(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return f.writeFileSync(ne,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(f.readFileSync(ne,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
256
256
  [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${ne}
257
257
  `),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.
258
- `),process.exit(1)),o&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=ne+".tmp";try{return f.writeFileSync(n,e),f.renameSync(n,ne),!0}catch(o){try{f.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function tt(){try{if(JSON.parse(f.readFileSync(ne,"utf-8")).pid!==process.pid)return;f.unlinkSync(ne)}catch{}}var yn=!1;function dr(){if(yn)return;yn=!0;let e=()=>{try{tt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function mr(){if(f.existsSync(R))return;let e=[],t=[];for(let s of gn)if(f.existsSync(s))try{e.push({file:s,schema:Te(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
258
+ `),process.exit(1)),o&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=ne+".tmp";try{return f.writeFileSync(n,e),f.renameSync(n,ne),!0}catch(o){try{f.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function tt(){try{if(JSON.parse(f.readFileSync(ne,"utf-8")).pid!==process.pid)return;f.unlinkSync(ne)}catch{}}var yn=!1;function dr(){if(yn)return;yn=!0;let e=()=>{try{tt()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function mr(){if(f.existsSync(D))return;let e=[],t=[];for(let s of gn)if(f.existsSync(s))try{e.push({file:s,schema:Re(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
259
259
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
260
260
  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.
261
261
  `),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
262
262
  [FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.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.
263
- `),process.exit(1)}let o=e[0].schema,r=R+".tmp";try{f.writeFileSync(r,JSON.stringify(o,null,2)),f.renameSync(r,R)}catch(s){try{f.unlinkSync(r)}catch{}throw s}for(let s of gn)if(f.existsSync(s))try{f.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${R}`)}function pr(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 Te(e){let t=f.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function wn(){if(mr(),!f.existsSync(R))return{version:0,migrations:[]};let e;try{e=Te(R)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
264
- [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.
263
+ `),process.exit(1)}let o=e[0].schema,r=D+".tmp";try{f.writeFileSync(r,JSON.stringify(o,null,2)),f.renameSync(r,D)}catch(s){try{f.unlinkSync(r)}catch{}throw s}for(let s of gn)if(f.existsSync(s))try{f.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${D}`)}function pr(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 Re(e){let t=f.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function wn(){if(mr(),!f.existsSync(D))return{version:0,migrations:[]};let e;try{e=Re(D)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
264
+ [FATAL] ${D} 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.
265
265
  `),process.exit(1)}let t=pr(e);return t===null&&(console.error(`
266
- [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.
267
- `),process.exit(1)),t}function vn(e){try{f.chmodSync(e,384)}catch{}}function hr(e){if(Sn(),f.existsSync(R))try{if(f.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{f.writeFileSync(t,JSON.stringify(e,null,2)),vn(t),f.renameSync(t,R)}catch(n){try{f.unlinkSync(t)}catch{}throw n}}function bn(e,t){if(!f.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=f.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return f.statSync(k.join(e,a)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let a of o){let l=k.join(e,a),m=k.join(e,a+n);if(f.existsSync(m)){s++;continue}try{Cn(l,m),r++}catch(c){i.push({file:a,err:c.message})}}if(i.length>0){let a=new Error(`Failed to back up ${i.length} file(s) in ${k.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(r>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${k.basename(e)}/ (${n})${a}`)}}var Xe=!1;async function kn(){if(Xe)return;Sn(),Sr();let t=wn().version;if(t===K){Xe=!0;return}dr(),fr(),process.on("exit",tt),t>K&&(console.error(`
266
+ [FATAL] ${D} 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.
267
+ `),process.exit(1)),t}function vn(e){try{f.chmodSync(e,384)}catch{}}function hr(e){if(Sn(),f.existsSync(D))try{if(f.lstatSync(D).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${D}. 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=D+".tmp";try{f.writeFileSync(t,JSON.stringify(e,null,2)),vn(t),f.renameSync(t,D)}catch(n){try{f.unlinkSync(t)}catch{}throw n}}function bn(e,t){if(!f.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=f.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return f.statSync(k.join(e,a)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let a of o){let l=k.join(e,a),m=k.join(e,a+n);if(f.existsSync(m)){s++;continue}try{Cn(l,m),r++}catch(c){i.push({file:a,err:c.message})}}if(i.length>0){let a=new Error(`Failed to back up ${i.length} file(s) in ${k.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(r>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${k.basename(e)}/ (${n})${a}`)}}var Xe=!1;async function kn(){if(Xe)return;Sn(),Sr();let t=wn().version;if(t===K){Xe=!0;return}dr(),fr(),process.on("exit",tt),t>K&&(console.error(`
268
268
  [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${K}.`),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.
269
269
  `),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${K}.
270
270
  `),process.exit(1)),console.log(`
@@ -282,13 +282,13 @@ ${o.join(`
282
282
  [FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
283
283
  `),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Ut()}catch{}try{Xt()}catch{}Xe=!0,tt(),console.log(`
284
284
  \u2713 Schema is now at v${K}
285
- `)}var gr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function yr(e){let t=e.toLowerCase();return gr.some(n=>n.test(t))}var wr=6e4;function br(){let e=Date.now(),t=[];for(let n of[U,oe,re]){if(!f.existsSync(n))continue;let o;try{o=f.readdirSync(n)}catch{continue}for(let r of o){if(!yr(r))continue;let s=k.join(n,r);try{let i=f.statSync(s);if(!i.isFile()||e-i.mtimeMs<wr)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function Sr({verbose:e=!1}={}){let t=br();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{f.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${k.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function vr(){let e=[];for(let t of[oe,re]){if(!f.existsSync(t))continue;let n=f.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=k.join(t,o);try{Te(r)}catch(s){e.push({dir:k.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function kr(e){let t=[],n=[];for(let s of[oe,re]){if(!f.existsSync(s))continue;let i=f.readdirSync(s).filter(a=>a.endsWith(e));for(let a of i){let l=k.join(s,a),m=a.slice(0,-e.length),c=k.join(s,m);try{m.toLowerCase().endsWith(".json")?Te(l):f.accessSync(l,f.constants.R_OK),t.push({backupPath:l,originalPath:c,fileName:a,dir:s})}catch(w){n.push(`${k.basename(s)}/${a}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:a,dir:l}of t)try{Cn(s,i),o++}catch(m){r.push(`${k.basename(l)}/${a}: ${m.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Cn(e,t){let n=t+".tmp";try{f.copyFileSync(e,n),vn(n)}catch(o){try{f.unlinkSync(n)}catch{}throw o}try{f.renameSync(n,t)}catch(o){try{f.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}await kn();var ke=process.argv.slice(2),Re=ke.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",nt=parseInt(ke.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),se=parseInt(ke.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),Cr=ke.includes("--list"),xr=ke.includes("--verbose");function Ar(){let e=nn();console.log(`
285
+ `)}var gr=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function yr(e){let t=e.toLowerCase();return gr.some(n=>n.test(t))}var wr=6e4;function br(){let e=Date.now(),t=[];for(let n of[U,oe,re]){if(!f.existsSync(n))continue;let o;try{o=f.readdirSync(n)}catch{continue}for(let r of o){if(!yr(r))continue;let s=k.join(n,r);try{let i=f.statSync(s);if(!i.isFile()||e-i.mtimeMs<wr)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function Sr({verbose:e=!1}={}){let t=br();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{f.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${k.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function vr(){let e=[];for(let t of[oe,re]){if(!f.existsSync(t))continue;let n=f.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=k.join(t,o);try{Re(r)}catch(s){e.push({dir:k.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function kr(e){let t=[],n=[];for(let s of[oe,re]){if(!f.existsSync(s))continue;let i=f.readdirSync(s).filter(a=>a.endsWith(e));for(let a of i){let l=k.join(s,a),m=a.slice(0,-e.length),c=k.join(s,m);try{m.toLowerCase().endsWith(".json")?Re(l):f.accessSync(l,f.constants.R_OK),t.push({backupPath:l,originalPath:c,fileName:a,dir:s})}catch(w){n.push(`${k.basename(s)}/${a}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:a,dir:l}of t)try{Cn(s,i),o++}catch(m){r.push(`${k.basename(l)}/${a}: ${m.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function Cn(e,t){let n=t+".tmp";try{f.copyFileSync(e,n),vn(n)}catch(o){try{f.unlinkSync(n)}catch{}throw o}try{f.renameSync(n,t)}catch(o){try{f.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=o.code,r}throw o}}await kn();var ke=process.argv.slice(2),De=ke.find(e=>e.startsWith("--source="))?.split("=")[1]||"scouted",nt=parseInt(ke.find(e=>e.startsWith("--max="))?.split("=")[1]||"50"),se=parseInt(ke.find(e=>e.startsWith("--revisit="))?.split("=")[1]||"0"),Cr=ke.includes("--list"),xr=ke.includes("--verbose");function Ar(){let e=nn();console.log(`
286
286
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 VISIT STATS"),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(` Unique profiles visited: ${e.totalVisited}`),console.log(` Today: ${e.todayVisited}`),console.log(` Discovered recruiters: ${e.totalRecruiters} (potential visits)`);let t=Be();if(console.log(` Unconnected recruiters: ${t.length}`),se>0){let n=Ve(se);console.log(` Revisit (>${se}d ago): ${n.length}`)}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
287
287
  `)}async function $r(){if(console.log(`
288
288
  LinkedIn Profile Visitor
289
- `),Cr){Ar();return}let e=[],t="";if(se>0?(e=Ve(se),t=`revisit (>${se} days)`):Re==="people"?(e=Be(),t="unconnected recruiters (people.json)"):Re==="scouted"||Re==="discovered"?(e=sn(),t="discovered recruiters (market-research)"):(e=rn({limit:nt}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${nt}
289
+ `),Cr){Ar();return}let e=[],t="";if(se>0?(e=Ve(se),t=`revisit (>${se} days)`):De==="people"?(e=Be(),t="unconnected recruiters (people.json)"):De==="scouted"||De==="discovered"?(e=sn(),t="discovered recruiters (market-research)"):(e=rn({limit:nt}),t="smart (new \u2192 active \u2192 unconnected \u2192 revisit)"),console.log(` Source: ${t}`),console.log(` Candidates: ${e.length}`),console.log(` Max visits: ${nt}
290
290
  `),e.length===0){console.log(` No profiles to visit. Run npm run scout first.
291
- `);return}let n=dn("visit",Re),{browser:o,page:r}=await Lt();try{let s=await on(r,e,{maxVisits:nt,verbose:xr,skipRecentDays:se>0?0:7});console.log(`
291
+ `);return}let n=dn("visit",De),{browser:o,page:r}=await Lt();try{let s=await on(r,e,{maxVisits:nt,verbose:xr,skipRecentDays:se>0?0:7});console.log(`
292
292
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" Visit 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: ${s.visited}`),console.log(` Skipped: ${s.skipped} (visited recently)`),console.log(` Errors: ${s.errors}`),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
293
293
  `),We(n,"success",s)}catch(s){console.error(`
294
294
  Error:`,s.message),We(n,"error",null,s.message)}finally{await o.close().catch(()=>{})}}$r().catch(e=>{console.error("Visit failed:",e),process.exit(1)});
package/ilml-plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "linkedin",
3
- "version": "1.20.3",
3
+ "version": "1.20.4",
4
4
  "description": "Reference ilml plugin: keep a local mirror of your LinkedIn data with AI-assisted workflows",
5
5
  "commands": {
6
6
  "help": { "run": "node dist/help.mjs", "description": "List all commands with descriptions; or `help <cmd>` for detailed info on one command (usage, flags, ban-risk, when-to-use). Reads ilml-plugin.json directly.", "usage": "ilml linkedin help [<cmd>]", "useWhen": "You forgot what a command does, or you're an AI agent picking the right tool." },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ilml-plugin-linkedin",
3
- "version": "1.20.3",
3
+ "version": "1.20.4",
4
4
  "description": "Reference ilml plugin: keep a local mirror of your LinkedIn data and run AI-assisted workflows under your direction.",
5
5
  "type": "module",
6
6
  "files": [