ilml-plugin-linkedin 1.11.4 → 1.11.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/viewers.mjs CHANGED
@@ -1,64 +1,64 @@
1
- var je=Object.defineProperty;var ne=(e,t)=>{for(var n in t)je(e,n,{get:t[n],enumerable:!0})};import"dotenv/config";import*as $ from"fs";import*as N from"path";import{fileURLToPath as Wt}from"url";import Ue from"puppeteer";import{addExtra as Je}from"puppeteer-extra";import Ve from"puppeteer-extra-plugin-stealth";async function V(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}import{getPluginConfig as _e}from"@ilivemylife/graph-sdk";var Fe=await _e();for(let[e,t]of Object.entries(Fe))process.env[e]===void 0&&(process.env[e]=t);var Ne=process.env.LINKEDIN_NAME,R=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),eo=Object.freeze(new Set([R.DRAFT,R.CONFIRMED,R.NEEDS_REVIEW])),Le=Object.freeze(new Set([R.DRAFT,R.CONFIRMED,R.REJECTED,R.NEEDS_REVIEW]));import se from"fs";import Pe from"path";var Me="cookies.json";function qe(){let e=process.env.ILML_SCOPE_DIR;return e?Pe.join(e,"plugins-state","linkedin","cookies.json"):Me}function re(){let e=qe();if(!se.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=se.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}var ie=Je(Ue);ie.use(Ve());async function ce(){let e=await ie.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
2
- Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=re();await n.setCookie(...o),console.log(" Browser launched, cookies loaded.")}catch(o){console.error(`
3
- [!] ${o.message}
4
- `),await e.close(),process.exit(1)}return{browser:e,page:n}}import"dotenv/config";import*as m from"fs";import*as g from"path";import{fileURLToPath as Be}from"url";var We=Be(import.meta.url),He=g.dirname(g.dirname(We)),E=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(He,"collected-profiles"),Ge=g.join(E,"people.json"),wo=g.join(E,"jobs.json"),vo=g.join(E,"quota.json"),bo=g.join(E,"conversations.json"),ko=g.join(E,"sync-state.json"),$o=g.join(E,"application-questions.json"),Ao=g.join(E,"profile-history");var q=null,Ye=null,ze=null,Ke=null,Qe=null,Xe=null;function le(){q=null,Ye=null,ze=null,Ke=null,Qe=null,Xe=null}function Ze(){m.existsSync(E)||m.mkdirSync(E,{recursive:!0})}function et(e,t){if(!m.existsSync(e))return null;try{let n=JSON.parse(m.readFileSync(e,"utf-8"));try{m.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(m.existsSync(o))try{let s=JSON.parse(m.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{m.copyFileSync(o,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{m.copyFileSync(e,e+".corrupted")}catch{}return null}}function ae(){return q||(Ze(),q=et(Ge,"people.json")||{},q)}import"dotenv/config";import*as O from"fs";import*as S from"path";import{fileURLToPath as tt}from"url";var ot=tt(import.meta.url),nt=S.dirname(S.dirname(ot)),J=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(nt,"market-research"),Do=S.join(J,"scouted-jobs.json"),st=S.join(J,"discovered-people.json"),rt=S.join(J,"visit-log.json"),Io=S.join(J,"companies.json"),Ro=S.join(J,"job-decisions.json");function ue(e){try{if(O.existsSync(e))return JSON.parse(O.readFileSync(e,"utf-8"))}catch{}return null}function fe(){it=null,ct=null,U=null,lt=null,x=null}var it=null;var ct=null;var U=null;function pe(){return U||(U=ue(st)||{},U)}var lt=null;var x=null;function de(){return x||(x=ue(rt)||{visits:[]},Array.isArray(x.visits)||(x.visits=[]),x)}async function me(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await V(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await V(1e3);return await e.evaluate(()=>{let n=[],o=document.querySelectorAll('a[href*="/in/"]'),s=new Set;for(let i of o){let r=i.getAttribute("href")?.split("?")[0];if(!r||s.has(r))continue;s.add(r);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(`
5
- `).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(`
6
- `)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let h=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,w="",L=u.indexOf(f);if(L>=0&&L+1<u.length){let p=u[L+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(w=p)}f&&f.length>1&&n.push({profileUrl:r.startsWith("/")?"https://www.linkedin.com"+r:r,name:f,title:w||null,connectionDegree:h})}return n})}function he(e){let t=ae(),n=de(),o=pe(),s=new Map;for(let i of n.visits||[]){let r=s.get(i.profileUrl);(!r||i.date>r)&&s.set(i.profileUrl,i.date)}return e.map(i=>{let r=t[i.profileUrl],c=o[i.profileUrl],l=s.get(i.profileUrl);return{...i,isConnected:r?.connectionStatus==="connected",isPending:r?.connectionStatus==="pending"||r?.connectionStatus==="sent_without_note",isInPeopleDb:!!r,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:r?.category||c?.role||null}})}import"dotenv/config";import*as v from"fs";import*as D from"path";import{fileURLToPath as mt}from"url";import"dotenv/config";import{createGraphClient as at,resolveToken as ut}from"@ilivemylife/graph-sdk";import{config as ft}from"dotenv";ft();var ge=ut()||process.env.TOKEN;ge||(console.error(`
1
+ var Ne=Object.defineProperty;var G=(e,o)=>{for(var n in o)Ne(e,n,{get:o[n],enumerable:!0})};import"dotenv/config";import*as E from"fs";import*as L from"path";import{fileURLToPath as to}from"url";import Ve from"puppeteer";import{addExtra as We}from"puppeteer-extra";import He from"puppeteer-extra-plugin-stealth";async function V(e){let o=Math.floor(Math.random()*2001),n=e+o;return new Promise(t=>setTimeout(t,n))}import{getPluginConfig as Le}from"@ilivemylife/graph-sdk";var Pe=await Le();for(let[e,o]of Object.entries(Pe))process.env[e]===void 0&&(process.env[e]=o);var Me=process.env.LINKEDIN_NAME,x=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),uo=Object.freeze(new Set([x.DRAFT,x.CONFIRMED,x.NEEDS_REVIEW])),qe=Object.freeze(new Set([x.DRAFT,x.CONFIRMED,x.REJECTED,x.NEEDS_REVIEW]));import ie from"fs";import Ue from"path";var Be="cookies.json";function Je(){let e=process.env.ILML_SCOPE_DIR;return e?Ue.join(e,"plugins-state","linkedin","cookies.json"):Be}function ce(){let e=Je();if(!ie.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let o;try{o=ie.readFileSync(e,"utf-8")}catch(t){throw new Error(`Failed to read cookies at ${e}: ${t.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(o)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}var le=We(Ve);le.use(He());async function ae(){let e=await le.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),o=async()=>{console.log(`
2
+ Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let t=ce();await n.setCookie(...t),console.log(" Browser launched, cookies loaded.")}catch(t){console.error(`
3
+ [!] ${t.message}
4
+ `),await e.close(),process.exit(1)}return{browser:e,page:n}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Ge}from"url";var Ye=Ge(import.meta.url),ze=g.dirname(g.dirname(Ye)),C=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(ze,"collected-profiles"),Ke=g.join(C,"people.json"),Io=g.join(C,"jobs.json"),Ro=g.join(C,"quota.json"),xo=g.join(C,"conversations.json"),Oo=g.join(C,"sync-state.json"),jo=g.join(C,"application-questions.json"),_o=g.join(C,"profile-history");var U=null,Qe=null,Xe=null,Ze=null,et=null,tt=null;function ue(){U=null,Qe=null,Xe=null,Ze=null,et=null,tt=null}function ot(){h.existsSync(C)||h.mkdirSync(C,{recursive:!0})}function nt(e,o){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(`[!] ${o} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let t=e+".backup";if(h.existsSync(t))try{let s=JSON.parse(h.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{h.copyFileSync(t,e)}catch{}return s}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 U||(ot(),U=nt(Ke,"people.json")||{},U)}import"dotenv/config";import*as j from"fs";import*as S from"path";import{fileURLToPath as st}from"url";var rt=st(import.meta.url),it=S.dirname(S.dirname(rt)),J=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(it,"market-research"),Po=S.join(J,"scouted-jobs.json"),ct=S.join(J,"discovered-people.json"),lt=S.join(J,"visit-log.json"),Mo=S.join(J,"companies.json"),qo=S.join(J,"job-decisions.json");function pe(e){try{if(j.existsSync(e))return JSON.parse(j.readFileSync(e,"utf-8"))}catch{}return null}function de(){at=null,ut=null,B=null,ft=null,O=null}var at=null;var ut=null;var B=null;function me(){return B||(B=pe(ct)||{},B)}var ft=null;var O=null;function he(){return O||(O=pe(lt)||{visits:[]},Array.isArray(O.visits)||(O.visits=[]),O)}async function ge(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await V(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await V(1e3);return await e.evaluate(()=>{let n=[],t=document.querySelectorAll('a[href*="/in/"]'),s=new Set;for(let r of t){let i=r.getAttribute("href")?.split("?")[0];if(!i||s.has(i))continue;s.add(i);let c=r;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(`
5
+ `).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=r.textContent?.trim()?.split(`
6
+ `)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",P=u.indexOf(f);if(P>=0&&P+1<u.length){let p=u[P+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(v=p)}f&&f.length>1&&n.push({profileUrl:i.startsWith("/")?"https://www.linkedin.com"+i:i,name:f,title:v||null,connectionDegree:m})}return n})}function ye(e){let o=fe(),n=he(),t=me(),s=new Map;for(let r of n.visits||[]){let i=s.get(r.profileUrl);(!i||r.date>i)&&s.set(r.profileUrl,r.date)}return e.map(r=>{let i=o[r.profileUrl],c=t[r.profileUrl],l=s.get(r.profileUrl);return{...r,isConnected:i?.connectionStatus==="connected",isPending:i?.connectionStatus==="pending"||i?.connectionStatus==="sent_without_note",isInPeopleDb:!!i,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:i?.category||c?.role||null}})}import"dotenv/config";import*as b from"fs";import*as I from"path";import{fileURLToPath as yt}from"url";import"dotenv/config";import{createGraphClient as pt,resolveToken as dt}from"@ilivemylife/graph-sdk";import{config as mt}from"dotenv";mt();var Se=dt()||process.env.TOKEN;Se||(console.error(`
7
7
  [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.
8
8
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
9
9
  `),console.error(` Or add ILML_TOKEN=... to .env
10
- `),process.exit(1));var ye=at({token:ge});function pt(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 dt({scriptName:e,mode:t,status:n,error:o,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${pt(s)}`:"",l=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${u} \u2014 ${l} \u2014 ${r}${c}`}async function Se({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:i}){let r=process.env.NODE_RUN_REPORTS;if(!r||!Array.isArray(o)||o.length===0)return;let l=`**${dt({scriptName:e,mode:t,status:n,error:s,duration:i})}**
10
+ `),process.exit(1));var we=pt({token:Se});function ht(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let n=Math.floor(o/60),t=o%60;return t?`${n}m ${t}s`:`${n}m`}function gt({scriptName:e,mode:o,status:n,error:t,duration:s}){let r=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${ht(s)}`:"",l=n==="error"?`error${t?`: ${String(t).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=o&&o!=="default"?` (${o})`:"";return`${r} ${e}${u} \u2014 ${l} \u2014 ${i}${c}`}async function ve({scriptName:e,mode:o,status:n,summaryLines:t,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(t)||t.length===0)return;let l=`**${gt({scriptName:e,mode:o,status:n,error:s,duration:r})}**
11
11
 
12
- ${o.join(`
13
- `)}`;try{await ye.addMessage(r,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var ht=mt(import.meta.url),gt=D.dirname(D.dirname(ht)),H=process.env.DATA_DIR?D.resolve(process.env.DATA_DIR,"collected-profiles"):D.join(gt,"collected-profiles"),G=D.join(H,"run-log.json");function yt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";v.writeFileSync(o,n);for(let s=0;s<3;s++)try{v.renameSync(o,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function we(){try{if(!v.existsSync(G))return{runs:[]};let e=JSON.parse(v.readFileSync(G,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ve(e){v.existsSync(H)||v.mkdirSync(H,{recursive:!0});try{yt(G,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function be(e,t="default"){let n=we();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let o=new Date,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),ve(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function Y(e,t,n=null,o=null){if(!e)return;let s=null;try{let r=we(),c=r.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=n,c.error=o,s=c.duration;else{let l=r.runs.find(u=>u.script===e.script&&u.status==="running"&&u.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,s=l.duration)}ve(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Se({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:o,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ee from"os";import*as d from"path";import{fileURLToPath as Dt}from"url";var Q={};ne(Q,{NAME:()=>wt,VERSION:()=>St,up:()=>kt});import*as b from"fs";import*as B from"path";var St=1,wt="normalize-jobs-and-questions",vt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],bt=50;function z(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function K(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{b.writeFileSync(o,n)}catch(s){try{b.unlinkSync(o)}catch{}throw s}try{b.renameSync(o,e)}catch(s){try{b.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function kt(e,t){let n=B.join(e,"jobs.json"),o=B.join(t,"scouted-jobs.json"),s=B.join(e,"application-questions.json"),i=z(n)||{},r=z(o)||{},c=0,l=[];for(let f of Object.keys(i)){if(!r[f])continue;let T=r[f],h=i[f];for(let w of vt)T[w]!=null&&h[w]==null&&(h[w]=T[w]);l.push(f),c++}c>0?(K(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=z(s);if(u&&Array.isArray(u.applications)){let f={},T=0;for(let h of u.applications){let w=h.jobId||"unknown";f[w]||(f[w]={applications:[]});let L=(h.questions||[]).map(p=>{let P={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=bt?P.options=p.options:(P.optionsOmitted=!0,T++)),p.page&&(P.page=p.page),p.wasPreFilled&&(P.wasPreFilled=!0),p.wasRetry&&(P.wasRetry=!0),P});f[w].applications.push({applicationId:h.applicationId,date:h.date,result:h.result||"submitted",formPages:h.formPages||null,duration:h.duration||null,retries:h.retries||0,failedField:h.failedField||null,questionCount:h.questionCount||L.length,questions:L})}K(s,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),T>0&&console.log(` Phase 2: Stripped bloated options from ${T} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let f of l)delete r[f];K(o,r),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var X={};ne(X,{NAME:()=>At,VERSION:()=>$t,up:()=>Ct});import*as k from"fs";import*as ke from"path";var $t=2,At="reset-unread-flags";function Tt(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function Et(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{k.writeFileSync(o,n)}catch(s){try{k.unlinkSync(o)}catch{}throw s}try{k.renameSync(o,e)}catch(s){try{k.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Ct(e){let t=ke.join(e,"conversations.json"),n=Tt(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Et(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var It=Dt(import.meta.url),Rt=d.dirname(It),xt=d.dirname(d.dirname(Rt));function Ot(e){return e&&(e==="~"?ee.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ee.homedir(),e.slice(2)):e)}var A=process.env.DATA_DIR?d.resolve(Ot(process.env.DATA_DIR)):xt,_=d.join(A,"collected-profiles"),F=d.join(A,"market-research"),y=d.join(A,".schema-version"),$e=[d.join(_,".schema-version"),d.join(F,".schema-version")],I=2,C=[{version:1,module:Q},{version:2,module:X}];(function(){C.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of C){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=C.length?C[C.length-1].version:0;if(n!==I)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${I}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<C.length;o++){let s=o+1;if(C[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${C[o].version}`)}})();function Ce(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
12
+ ${t.join(`
13
+ `)}`;try{await we.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var St=yt(import.meta.url),wt=I.dirname(I.dirname(St)),Y=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(wt,"collected-profiles"),z=I.join(Y,"run-log.json");function vt(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";b.writeFileSync(t,n);for(let s=0;s<3;s++)try{b.renameSync(t,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function be(){try{if(!b.existsSync(z))return{runs:[]};let e=JSON.parse(b.readFileSync(z,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ke(e){b.existsSync(Y)||b.mkdirSync(Y,{recursive:!0});try{vt(z,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function $e(e,o="default"){let n=be();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 t=new Date,s={timestamp:t.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>r),ke(n),{script:e,mode:o,startTime:t.getTime(),runIndex:n.runs.length-1}}function K(e,o,n=null,t=null){if(!e)return;let s=null;try{let i=be(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=n,c.error=t,s=c.duration;else{let l=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=o,l.result=o,l.duration=Date.now()-e.startTime,l.stats=n,l.error=t,s=l.duration)}ke(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=o==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";ve({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:t,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ne from"os";import*as d from"path";import{fileURLToPath as Pt}from"url";var Z={};G(Z,{NAME:()=>kt,VERSION:()=>bt,up:()=>Et});import*as k from"fs";import*as W from"path";var bt=1,kt="normalize-jobs-and-questions",$t=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],At=50;function Q(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function X(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{k.writeFileSync(t,n)}catch(s){try{k.unlinkSync(t)}catch{}throw s}try{k.renameSync(t,e)}catch(s){try{k.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Et(e,o){let n=W.join(e,"jobs.json"),t=W.join(o,"scouted-jobs.json"),s=W.join(e,"application-questions.json"),r=Q(n)||{},i=Q(t)||{},c=0,l=[];for(let f of Object.keys(r)){if(!i[f])continue;let w=i[f],m=r[f];for(let v of $t)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(X(n,r),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Q(s);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let P=(m.questions||[]).map(p=>{let M={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=At?M.options=p.options:(M.optionsOmitted=!0,w++)),p.page&&(M.page=p.page),p.wasPreFilled&&(M.wasPreFilled=!0),p.wasRetry&&(M.wasRetry=!0),M});f[v].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||P.length,questions:P})}X(s,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else u&&!u.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(l.length>0){for(let f of l)delete i[f];X(t,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 ee={};G(ee,{NAME:()=>Ct,VERSION:()=>Tt,up:()=>Rt});import*as $ from"fs";import*as Ae from"path";var Tt=2,Ct="reset-unread-flags";function Dt(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function It(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{$.writeFileSync(t,n)}catch(s){try{$.unlinkSync(t)}catch{}throw s}try{$.renameSync(t,e)}catch(s){try{$.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Rt(e){let o=Ae.join(e,"conversations.json"),n=Dt(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}It(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var te={};G(te,{NAME:()=>Ot,VERSION:()=>xt,up:()=>Lt});import*as A from"fs";import*as Ee from"path";var xt=3,Ot="recompute-last-message-by",jt=new Set(["draft","confirmed","rejected","needs_review"]);function _t(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Ft(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{A.writeFileSync(t,n)}catch(s){try{A.unlinkSync(t)}catch{}throw s}try{A.renameSync(t,e)}catch(s){try{A.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Nt(e,o){if(!e||e.length===0)return"them";let n=e.filter(r=>!jt.has(r.status));if(n.length===0)return"them";let t=n.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=t.length>0?t:[...n].reverse();for(let r of s){let i=r.sender;if(i===o)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Lt(e){let o=Ee.join(e,"conversations.json"),n=_t(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,r++);let u=Array.isArray(l.messages)?l.messages:[],f=Nt(u,t),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&i++,l.lastMessageBy=f,l.conversationStatus=w,s++}if(s===0){console.log(" No conversations to recompute.");return}Ft(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Mt=Pt(import.meta.url),qt=d.dirname(Mt),Ut=d.dirname(d.dirname(qt));function Bt(e){return e&&(e==="~"?ne.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ne.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?d.resolve(Bt(process.env.DATA_DIR)):Ut,F=d.join(T,"collected-profiles"),N=d.join(T,"market-research"),y=d.join(T,".schema-version"),Te=[d.join(F,".schema-version"),d.join(N,".schema-version")],R=3,D=[{version:1,module:Z},{version:2,module:ee},{version:3,module:te}];(function(){D.sort((t,s)=>t.version-s.version);let o=new Set;for(let t of D){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let s=t.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=D.length?D[D.length-1].version:0;if(n!==R)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${R}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<D.length;t++){let s=t+1;if(D[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${D[t].version}`)}})();function Re(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
14
14
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
15
- `),process.exit(1));try{a.mkdirSync(A,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
16
- [FATAL] Cannot create DATA_DIR (${A}): ${t.message}`),console.error(` Fix the path or permissions and try again.
17
- `),process.exit(1))}let e;try{e=a.statSync(A)}catch(t){console.error(`
18
- [FATAL] DATA_DIR (${A}) is not accessible: ${t.message}
15
+ `),process.exit(1));try{a.mkdirSync(T,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
16
+ [FATAL] Cannot create DATA_DIR (${T}): ${o.message}`),console.error(` Fix the path or permissions and try again.
17
+ `),process.exit(1))}let e;try{e=a.statSync(T)}catch(o){console.error(`
18
+ [FATAL] DATA_DIR (${T}) is not accessible: ${o.message}
19
19
  `),process.exit(1)}e.isDirectory()||(console.error(`
20
- [FATAL] DATA_DIR (${A}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
21
- `),process.exit(1));for(let t of[_,F]){let n;try{n=a.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
22
- [FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
23
- `),process.exit(1))}}var j=d.join(A,".migration-lock");function jt(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(j,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(a.readFileSync(j,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(r){r.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,i=1/0;if(t.startedAt){let r=Date.parse(t.startedAt);Number.isNaN(r)||(i=Date.now()-r)}o&&i<s&&(console.error(`
24
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${j}
20
+ [FATAL] DATA_DIR (${T}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
21
+ `),process.exit(1));for(let o of[F,N]){let n;try{n=a.lstatSync(o)}catch(t){if(t.code==="ENOENT")continue;throw t}n.isSymbolicLink()&&(console.error(`
22
+ [FATAL] Data subdirectory is a symbolic link: ${o}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
23
+ `),process.exit(1))}}var _=d.join(T,".migration-lock");function Jt(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(_,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(a.readFileSync(_,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(i){i.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,r=1/0;if(o.startedAt){let i=Date.parse(o.startedAt);Number.isNaN(i)||(r=Date.now()-i)}t&&r<s&&(console.error(`
24
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${_}
25
25
  `),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.
26
- `),process.exit(1)),o&&i>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=j+".tmp";try{return a.writeFileSync(n,e),a.renameSync(n,j),!0}catch(o){try{a.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function te(){try{if(JSON.parse(a.readFileSync(j,"utf-8")).pid!==process.pid)return;a.unlinkSync(j)}catch{}}var Ae=!1;function _t(){if(Ae)return;Ae=!0;let e=()=>{try{te()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Ft(){if(a.existsSync(y))return;let e=[],t=[];for(let i of $e)if(a.existsSync(i))try{e.push({file:i,schema:W(i)})}catch(r){t.push({file:i,err:r.message})}if(t.length>0){console.error(`
27
- [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
26
+ `),process.exit(1)),t&&r>=s&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let n=_+".tmp";try{return a.writeFileSync(n,e),a.renameSync(n,_),!0}catch(t){try{a.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function se(){try{if(JSON.parse(a.readFileSync(_,"utf-8")).pid!==process.pid)return;a.unlinkSync(_)}catch{}}var Ce=!1;function Vt(){if(Ce)return;Ce=!0;let e=()=>{try{se()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function Wt(){if(a.existsSync(y))return;let e=[],o=[];for(let r of Te)if(a.existsSync(r))try{e.push({file:r,schema:H(r)})}catch(i){o.push({file:r,err:i.message})}if(o.length>0){console.error(`
27
+ [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of o)console.error(` ${r.file}: ${r.err}`);console.error(`
28
28
  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.
29
- `),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
30
- [FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.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.
31
- `),process.exit(1)}let o=e[0].schema,s=y+".tmp";try{a.writeFileSync(s,JSON.stringify(o,null,2)),a.renameSync(s,y)}catch(i){try{a.unlinkSync(s)}catch{}throw i}for(let i of $e)if(a.existsSync(i))try{a.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function Nt(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 W(e){let t=a.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Te(){if(Ft(),!a.existsSync(y))return{version:0,migrations:[]};let e;try{e=W(y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
29
+ `),process.exit(1)}if(e.length===0)return;let n=e.map(r=>r.schema.version);if(new Set(n).size>1){console.error(`
30
+ [FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
31
+ `),process.exit(1)}let t=e[0].schema,s=y+".tmp";try{a.writeFileSync(s,JSON.stringify(t,null,2)),a.renameSync(s,y)}catch(r){try{a.unlinkSync(s)}catch{}throw r}for(let r of Te)if(a.existsSync(r))try{a.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function Ht(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let o=Number(e.version);return!Number.isFinite(o)||o<0||!Number.isInteger(o)?null:(e.version=o,Array.isArray(e.migrations)||(e.migrations=[]),e)}function H(e){let o=a.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function De(){if(Wt(),!a.existsSync(y))return{version:0,migrations:[]};let e;try{e=H(y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
32
32
  [FATAL] ${y} 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.
33
- `),process.exit(1)}let t=Nt(e);return t===null&&(console.error(`
33
+ `),process.exit(1)}let o=Ht(e);return o===null&&(console.error(`
34
34
  [FATAL] ${y} 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.
35
- `),process.exit(1)),t}function De(e){try{a.chmodSync(e,384)}catch{}}function Lt(e){if(Ce(),a.existsSync(y))try{if(a.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. 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=y+".tmp";try{a.writeFileSync(t,JSON.stringify(e,null,2)),De(t),a.renameSync(t,y)}catch(n){try{a.unlinkSync(t)}catch{}throw n}}function Ee(e,t){if(!a.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let c of o){let l=d.join(e,c),u=d.join(e,c+n);if(a.existsSync(u)){i++;continue}try{Re(l,u),s++}catch(f){r.push({file:c,err:f.message})}}if(r.length>0){let c=new Error(`Failed to back up ${r.length} file(s) in ${d.basename(e)}/: `+r.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${d.basename(e)}/ (${n})${c}`)}}var Z=!1;async function Ie(){if(Z)return;Ce(),Jt();let t=Te().version;if(t===I){Z=!0;return}_t(),jt(),process.on("exit",te),t>I&&(console.error(`
36
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${I}.`),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.
37
- `),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${I}.
35
+ `),process.exit(1)),o}function xe(e){try{a.chmodSync(e,384)}catch{}}function Gt(e){if(Re(),a.existsSync(y))try{if(a.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. 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 o=y+".tmp";try{a.writeFileSync(o,JSON.stringify(e,null,2)),xe(o),a.renameSync(o,y)}catch(n){try{a.unlinkSync(o)}catch{}throw n}}function Ie(e,o){if(!a.existsSync(e))return;let n=`.pre-v${String(o).padStart(3,"0")}.backup`,t=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,c)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let c of t){let l=d.join(e,c),u=d.join(e,c+n);if(a.existsSync(u)){r++;continue}try{je(l,u),s++}catch(f){i.push({file:c,err:f.message})}}if(i.length>0){let c=new Error(`Failed to back up ${i.length} file(s) in ${d.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||r>0){let c=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${d.basename(e)}/ (${n})${c}`)}}var oe=!1;async function Oe(){if(oe)return;Re(),Xt();let o=De().version;if(o===R){oe=!0;return}Vt(),Jt(),process.on("exit",se),o>R&&(console.error(`
36
+ [FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${R}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
37
+ `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${R}.
38
38
  `),process.exit(1)),console.log(`
39
- \u{1F4E6} Schema migration: v${t} \u2192 v${I}`);let n=Vt();if(!n.ok){console.error(`
39
+ \u{1F4E6} Schema migration: v${o} \u2192 v${R}`);let n=Zt();if(!n.ok){console.error(`
40
40
  [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
41
41
  Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
42
- `),process.exit(1)}let o=C.filter(s=>s.version>t);for(let s of o){console.log(`
43
- Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{Ee(_,s.version),Ee(F,s.version)}catch(l){console.error(`
44
- [FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
45
- `),process.exit(1)}let c=s.module;try{await c.up(_,F)}catch(l){console.error(`
46
- [FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let u=Bt(r);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
47
- `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
48
- `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
49
- `)}process.exit(1)}try{let l=new Date().toISOString(),u={version:s.version,name:c.NAME||i,appliedAt:l},f=Te();f.version=s.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),Lt(f)}catch(l){console.error(`
50
- [FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
51
- `),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{le()}catch{}try{fe()}catch{}Z=!0,te(),console.log(`
52
- \u2713 Schema is now at v${I}
53
- `)}var Pt=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Mt(e){let t=e.toLowerCase();return Pt.some(n=>n.test(t))}var qt=6e4;function Ut(){let e=Date.now(),t=[];for(let n of[A,_,F]){if(!a.existsSync(n))continue;let o;try{o=a.readdirSync(n)}catch{continue}for(let s of o){if(!Mt(s))continue;let i=d.join(n,s);try{let r=a.statSync(i);if(!r.isFile()||e-r.mtimeMs<qt)continue;t.push({dir:n,file:s,fullPath:i})}catch{}}}return t}function Jt({verbose:e=!1}={}){let t=Ut();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{a.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${d.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Vt(){let e=[];for(let t of[_,F]){if(!a.existsSync(t))continue;let n=a.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=d.join(t,o);try{W(s)}catch(i){e.push({dir:d.basename(t),file:o,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Bt(e){let t=[],n=[];for(let i of[_,F]){if(!a.existsSync(i))continue;let r=a.readdirSync(i).filter(c=>c.endsWith(e));for(let c of r){let l=d.join(i,c),u=c.slice(0,-e.length),f=d.join(i,u);try{u.toLowerCase().endsWith(".json")?W(l):a.accessSync(l,a.constants.R_OK),t.push({backupPath:l,originalPath:f,fileName:c,dir:i})}catch(T){n.push(`${d.basename(i)}/${c}: ${T.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:i,originalPath:r,fileName:c,dir:l}of t)try{Re(i,r),o++}catch(u){s.push(`${d.basename(l)}/${c}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function Re(e,t){let n=t+".tmp";try{a.copyFileSync(e,n),De(n)}catch(o){try{a.unlinkSync(n)}catch{}throw o}try{a.renameSync(n,t)}catch(o){try{a.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}var Ht=Wt(import.meta.url),Gt=N.dirname(Ht),oe=process.env.DATA_DIR?N.resolve(process.env.DATA_DIR,"market-research"):N.join(Gt,"market-research"),M=N.join(oe,"profile-viewers.json");await Ie();var Oe=process.argv.slice(2),xe=Oe.includes("--save"),Yt=Oe.includes("--list");function zt(){if(!$.existsSync(M)){console.log(`
42
+ `),process.exit(1)}let t=D.filter(s=>s.version>o);for(let s of t){console.log(`
43
+ Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{Ie(F,s.version),Ie(N,s.version)}catch(l){console.error(`
44
+ [FATAL] Pre-migration backup failed for ${r}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
45
+ `),process.exit(1)}let c=s.module;try{await c.up(F,N)}catch(l){console.error(`
46
+ [FATAL] Migration ${r} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=eo(i);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${o}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
47
+ `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
48
+ `))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
49
+ `)}process.exit(1)}try{let l=new Date().toISOString(),u={version:s.version,name:c.NAME||r,appliedAt:l},f=De();f.version=s.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),Gt(f)}catch(l){console.error(`
50
+ [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${o}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
51
+ `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{ue()}catch{}try{de()}catch{}oe=!0,se(),console.log(`
52
+ \u2713 Schema is now at v${R}
53
+ `)}var Yt=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function zt(e){let o=e.toLowerCase();return Yt.some(n=>n.test(o))}var Kt=6e4;function Qt(){let e=Date.now(),o=[];for(let n of[T,F,N]){if(!a.existsSync(n))continue;let t;try{t=a.readdirSync(n)}catch{continue}for(let s of t){if(!zt(s))continue;let r=d.join(n,s);try{let i=a.statSync(r);if(!i.isFile()||e-i.mtimeMs<Kt)continue;o.push({dir:n,file:s,fullPath:r})}catch{}}}return o}function Xt({verbose:e=!1}={}){let o=Qt();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let t of o)try{a.unlinkSync(t.fullPath),n++,e&&console.log(` Removed orphan: ${d.basename(t.dir)}/${t.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function Zt(){let e=[];for(let o of[F,N]){if(!a.existsSync(o))continue;let n=a.readdirSync(o).filter(t=>{let s=t.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let t of n){let s=d.join(o,t);try{H(s)}catch(r){e.push({dir:d.basename(o),file:t,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function eo(e){let o=[],n=[];for(let r of[F,N]){if(!a.existsSync(r))continue;let i=a.readdirSync(r).filter(c=>c.endsWith(e));for(let c of i){let l=d.join(r,c),u=c.slice(0,-e.length),f=d.join(r,u);try{u.toLowerCase().endsWith(".json")?H(l):a.accessSync(l,a.constants.R_OK),o.push({backupPath:l,originalPath:f,fileName:c,dir:r})}catch(w){n.push(`${d.basename(r)}/${c}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let t=0,s=[];for(let{backupPath:r,originalPath:i,fileName:c,dir:l}of o)try{je(r,i),t++}catch(u){s.push(`${d.basename(l)}/${c}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:t}:{ok:!0,restored:t}}function je(e,o){let n=o+".tmp";try{a.copyFileSync(e,n),xe(n)}catch(t){try{a.unlinkSync(n)}catch{}throw t}try{a.renameSync(n,o)}catch(t){try{a.unlinkSync(n)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let s=new Error(`File locked: ${o} (${t.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=t.code,s}throw t}}var oo=to(import.meta.url),no=L.dirname(oo),re=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(no,"market-research"),q=L.join(re,"profile-viewers.json");await Oe();var Fe=process.argv.slice(2),_e=Fe.includes("--save"),so=Fe.includes("--list");function ro(){if(!E.existsSync(q)){console.log(`
54
54
  No viewer data yet. Run: npm run viewers -- --save
55
- `);return}let t=JSON.parse($.readFileSync(M,"utf-8")).scans||[],n=t.flatMap(r=>r.viewers||[]),o=new Map;for(let r of n)(!o.has(r.profileUrl)||r.scanDate>o.get(r.profileUrl).scanDate)&&o.set(r.profileUrl,r);console.log(`
56
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 VIEWERS"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Total scans: ${t.length}`),console.log(` Unique viewers: ${o.size}`);let s=[...o.values()].filter(r=>r.isConnected).length,i=[...o.values()].filter(r=>r.weVisitedThem).length;if(console.log(` Already connected: ${s}`),console.log(` We visited first: ${i} (\u2192 they responded by viewing us)`),o.size>0){console.log(`
57
- Recent viewers:`);let r=[...o.values()].slice(0,10);for(let c of r){let l=[];c.isConnected&&l.push("connected"),c.weVisitedThem&&l.push("we visited"),c.isDiscovered&&l.push("discovered");let u=l.length?` [${l.join(", ")}]`:"";console.log(` ${c.name} (${c.connectionDegree||"?"})${u}`),c.title&&console.log(` ${c.title.slice(0,60)}`)}}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
58
- `)}async function Kt(){if(console.log(`
55
+ `);return}let o=JSON.parse(E.readFileSync(q,"utf-8")).scans||[],n=o.flatMap(i=>i.viewers||[]),t=new Map;for(let i of n)(!t.has(i.profileUrl)||i.scanDate>t.get(i.profileUrl).scanDate)&&t.set(i.profileUrl,i);console.log(`
56
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 VIEWERS"),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Total scans: ${o.length}`),console.log(` Unique viewers: ${t.size}`);let s=[...t.values()].filter(i=>i.isConnected).length,r=[...t.values()].filter(i=>i.weVisitedThem).length;if(console.log(` Already connected: ${s}`),console.log(` We visited first: ${r} (\u2192 they responded by viewing us)`),t.size>0){console.log(`
57
+ Recent viewers:`);let i=[...t.values()].slice(0,10);for(let c of i){let l=[];c.isConnected&&l.push("connected"),c.weVisitedThem&&l.push("we visited"),c.isDiscovered&&l.push("discovered");let u=l.length?` [${l.join(", ")}]`:"";console.log(` ${c.name} (${c.connectionDegree||"?"})${u}`),c.title&&console.log(` ${c.title.slice(0,60)}`)}}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
58
+ `)}async function io(){if(console.log(`
59
59
  LinkedIn Profile Viewers
60
- `),Yt){zt();return}let e=be("viewers",xe?"save":"view"),{browser:t,page:n}=await ce();try{console.log(` Extracting profile viewers...
61
- `);let o=await me(n);console.log(` Found ${o.length} viewers`);let s=he(o);for(let r of s){let c=[];r.isConnected?c.push("\u2713 connected"):r.isPending&&c.push("\u23F3 pending"),r.weVisitedThem&&c.push("\u{1F441} we visited"),r.isDiscovered&&c.push("\u{1F4CB} discovered");let l=c.length?` [${c.join(", ")}]`:"";console.log(` ${r.name} (${r.connectionDegree||"?"})${l}`),r.title&&console.log(` ${r.title.slice(0,70)}`)}if(xe&&s.length>0){$.existsSync(oe)||$.mkdirSync(oe,{recursive:!0});let r={scans:[]};try{$.existsSync(M)&&(r=JSON.parse($.readFileSync(M,"utf-8")))}catch{}r.scans.push({scanDate:new Date().toISOString(),viewerCount:s.length,viewers:s});let c=Date.now()-90*24*60*60*1e3;r.scans=r.scans.filter(l=>new Date(l.scanDate).getTime()>c),$.writeFileSync(M,JSON.stringify(r,null,2)),console.log(`
62
- Saved ${s.length} viewers to ${M}`)}let i={viewers:s.length,connected:s.filter(r=>r.isConnected).length,weVisitedFirst:s.filter(r=>r.weVisitedThem).length};console.log(`
63
- Summary: ${i.viewers} viewers, ${i.connected} connected, ${i.weVisitedFirst} we visited first`),Y(e,"success",i)}catch(o){console.error(`
64
- Error:`,o.message),Y(e,"error",null,o.message)}finally{await t.close().catch(()=>{})}}Kt().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});
60
+ `),so){ro();return}let e=$e("viewers",_e?"save":"view"),{browser:o,page:n}=await ae();try{console.log(` Extracting profile viewers...
61
+ `);let t=await ge(n);console.log(` Found ${t.length} viewers`);let s=ye(t);for(let i of s){let c=[];i.isConnected?c.push("\u2713 connected"):i.isPending&&c.push("\u23F3 pending"),i.weVisitedThem&&c.push("\u{1F441} we visited"),i.isDiscovered&&c.push("\u{1F4CB} discovered");let l=c.length?` [${c.join(", ")}]`:"";console.log(` ${i.name} (${i.connectionDegree||"?"})${l}`),i.title&&console.log(` ${i.title.slice(0,70)}`)}if(_e&&s.length>0){E.existsSync(re)||E.mkdirSync(re,{recursive:!0});let i={scans:[]};try{E.existsSync(q)&&(i=JSON.parse(E.readFileSync(q,"utf-8")))}catch{}i.scans.push({scanDate:new Date().toISOString(),viewerCount:s.length,viewers:s});let c=Date.now()-90*24*60*60*1e3;i.scans=i.scans.filter(l=>new Date(l.scanDate).getTime()>c),E.writeFileSync(q,JSON.stringify(i,null,2)),console.log(`
62
+ Saved ${s.length} viewers to ${q}`)}let r={viewers:s.length,connected:s.filter(i=>i.isConnected).length,weVisitedFirst:s.filter(i=>i.weVisitedThem).length};console.log(`
63
+ Summary: ${r.viewers} viewers, ${r.connected} connected, ${r.weVisitedFirst} we visited first`),K(e,"success",r)}catch(t){console.error(`
64
+ Error:`,t.message),K(e,"error",null,t.message)}finally{await o.close().catch(()=>{})}}io().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});