ilml-plugin-linkedin 1.11.2 → 1.11.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.
@@ -1,4 +1,4 @@
1
- var St=Object.defineProperty;var Pe=(e,t)=>{for(var n in t)St(e,n,{get:t[n],enumerable:!0})};import*as te from"fs";import*as yt from"readline";var he={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},vt={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function re(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function ye(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let l=re(n),a=new Date(t);return l?a.setHours(l.hours,l.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=vt[o[1].toLowerCase()],a=re(o[2]||""),f=new Date(t),m=f.getDay()-l;return m<=0&&(m+=7),f.setDate(f.getDate()-m),a?f.setHours(a.hours,a.minutes,0,0):f.setHours(0,0,0,0),f.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=he[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(s[2],10),f=parseInt(s[3],10),u=re(s[4]||"");return new Date(f,l,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=he[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(r[2],10),f=re(r[3]||""),u=t.getFullYear(),m=new Date(u,l,a,f?.hours||0,f?.minutes||0,0,0);return m>t&&m.setFullYear(u-1),m.toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=he[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(i[2],10),f=re(i[3]||""),u=t.getFullYear(),m=new Date(u,l,a,f?.hours||0,f?.minutes||0,0,0);return m>t&&m.setFullYear(u-1),m.toISOString()}return null}async function A(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Le(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function Ue(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function Be(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}import"dotenv/config";import*as O from"fs";import*as _ from"path";import{fileURLToPath as bt}from"url";var $t=bt(import.meta.url),kt=_.dirname(_.dirname($t)),H=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"collected-profiles"):_.join(kt,"collected-profiles"),we=_.join(H,"people.json"),Ko=_.join(H,"jobs.json"),Qo=_.join(H,"quota.json"),ue=_.join(H,"conversations.json"),Xo=_.join(H,"sync-state.json"),Zo=_.join(H,"application-questions.json"),en=_.join(H,"profile-history");var oe=null,Ct=null,Et=null,z=null,Dt=null,Tt=null;function qe(){oe=null,Ct=null,Et=null,z=null,Dt=null,Tt=null}function fe(){O.existsSync(H)||O.mkdirSync(H,{recursive:!0})}function Se(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let s=0;s<3;s++)try{O.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function Je(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${_.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let s=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.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{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function J(){return oe||(fe(),oe=Je(we,"people.json")||{},oe)}function de(e){fe(),oe=e;try{Se(we,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${_.resolve(we)}`)}}function j(){return z||(fe(),z=Je(ue,"conversations.json")||{},At(z),z)}function At(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(r=>r.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Se(ue,e)}catch{}}}function P(e){fe(),z=e;try{Se(ue,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${_.resolve(ue)}`)}}import{getPluginConfig as Rt}from"@ilivemylife/graph-sdk";var xt=await Rt();for(let[e,t]of Object.entries(xt))process.env[e]===void 0&&(process.env[e]=t);var ne=process.env.LINKEDIN_NAME,k=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ie=Object.freeze(new Set([k.DRAFT,k.CONFIRMED,k.NEEDS_REVIEW])),K=Object.freeze(new Set([k.DRAFT,k.CONFIRMED,k.REJECTED,k.NEEDS_REVIEW]));import"dotenv/config";import*as U from"fs";import*as Y from"path";import{fileURLToPath as Nt}from"url";import"dotenv/config";import{createGraphClient as It,resolveToken as Ot}from"@ilivemylife/graph-sdk";import{config as _t}from"dotenv";_t();var We=Ot()||process.env.TOKEN;We||(console.error(`
1
+ var St=Object.defineProperty;var Pe=(e,t)=>{for(var n in t)St(e,n,{get:t[n],enumerable:!0})};import*as te from"fs";import*as yt from"readline";var he={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},vt={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function re(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&n!==12&&(n+=12),!s&&n===12&&(n=0),{hours:n,minutes:o}}function ye(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let l=re(n),a=new Date(t);return l?a.setHours(l.hours,l.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=vt[o[1].toLowerCase()],a=re(o[2]||""),f=new Date(t),m=f.getDay()-l;return m<=0&&(m+=7),f.setDate(f.getDate()-m),a?f.setHours(a.hours,a.minutes,0,0):f.setHours(0,0,0,0),f.toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=he[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(s[2],10),f=parseInt(s[3],10),u=re(s[4]||"");return new Date(f,l,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=he[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(r[2],10),f=re(r[3]||""),u=t.getFullYear(),m=new Date(u,l,a,f?.hours||0,f?.minutes||0,0,0);return m>t&&m.setFullYear(u-1),m.toISOString()}let i=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=he[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(i[2],10),f=re(i[3]||""),u=t.getFullYear(),m=new Date(u,l,a,f?.hours||0,f?.minutes||0,0,0);return m>t&&m.setFullYear(u-1),m.toISOString()}return null}async function A(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function Le(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function Ue(e){return e&&e.replace(/[®™]/g,"").replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{1F000}-\u{1FAFF}]|[\u{200D}]|[\u{20E3}]|[\u{E0020}-\u{E007F}]/gu,"").replace(/[\u{2B50}\u{2728}\u{2764}\u{270C}\u{270B}\u{1F3FB}-\u{1F3FF}]/gu,"").replace(/\s*\([^)]*[\u4E00-\u9FFF\u3400-\u4DBF][^)]*\)/g,"").replace(/\s{2,}/g," ").trim()}function Be(e){return e&&e.replace(/(?:,\s*(?:Ph\.?D\.?|P\.?E\.?|P\.?Eng\.?|MBA|M\.?Sc\.?|B\.?Sc\.?|M\.?Ed\.?(?:Tech\.?)?|B\.?Tech\.?|B\.?Comm\.?|B\.?Eng\.?|CPA|CFA|CFP|PMP|CISSP|CISM|CSM|CSP|ITIL|FCA|CA|CMA|PE|SE|RA|AIA|LEED\s*AP|SHRM-(?:CP|SCP)|SPHR|PHR|RN|MD|J\.?D\.?|Esq\.?|DDS|OD|DO|PA-C|RD|LPC|LCSW|CDP|ACC|PCC|MCC|ICD\.?D|RCC|CPHR|CHRP|CCP|CIM|CLU|DFSA|CTS|HRMD|CPIR|CPI|MCIPD)\.?\s*)+$/gi,"").replace(/\s+(?:MBA|M\.?Ed\.?(?:Tech\.?)?|Ph\.?D\.?|B\.?Tech\.?|CPHR|CTS)\s*$/gi,"").replace(/,\s*[A-Z][A-Z.\s]*$/g,"").replace(/\s{2,}/g," ").trim()}import{getPluginConfig as bt}from"@ilivemylife/graph-sdk";var $t=await bt();for(let[e,t]of Object.entries($t))process.env[e]===void 0&&(process.env[e]=t);var oe=process.env.LINKEDIN_NAME,k=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ie=Object.freeze(new Set([k.DRAFT,k.CONFIRMED,k.NEEDS_REVIEW])),z=Object.freeze(new Set([k.DRAFT,k.CONFIRMED,k.REJECTED,k.NEEDS_REVIEW]));import"dotenv/config";import*as O from"fs";import*as _ from"path";import{fileURLToPath as kt}from"url";var Ct=kt(import.meta.url),Et=_.dirname(_.dirname(Ct)),H=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"collected-profiles"):_.join(Et,"collected-profiles"),we=_.join(H,"people.json"),Zo=_.join(H,"jobs.json"),en=_.join(H,"quota.json"),ue=_.join(H,"conversations.json"),tn=_.join(H,"sync-state.json"),on=_.join(H,"application-questions.json"),nn=_.join(H,"profile-history");var ne=null,Dt=null,Tt=null,K=null,At=null,Rt=null;function qe(){ne=null,Dt=null,Tt=null,K=null,At=null,Rt=null}function fe(){O.existsSync(H)||O.mkdirSync(H,{recursive:!0})}function Se(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,n);for(let s=0;s<3;s++)try{O.renameSync(o,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function Je(e,t){if(!O.existsSync(e))return null;try{let n=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${_.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let s=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.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{O.copyFileSync(e,e+".corrupted")}catch{}return null}}function J(){return ne||(fe(),ne=Je(we,"people.json")||{},ne)}function de(e){fe(),ne=e;try{Se(we,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${_.resolve(we)}`)}}function j(){return K||(fe(),K=Je(ue,"conversations.json")||{},xt(K),K)}function xt(e){let t=0;for(let n of Object.values(e)){if(!(n.draftStatus!==void 0||n.draftPreparedAt!==void 0))continue;let s=(n.messages||[]).find(r=>r.status==="draft");s&&n.draftStatus&&n.draftStatus!=="pending"&&(s.status=n.draftStatus),delete n.draftStatus,delete n.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Se(ue,e)}catch{}}}function P(e){fe(),K=e;try{Se(ue,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${_.resolve(ue)}`)}}import"dotenv/config";import*as U from"fs";import*as Y from"path";import{fileURLToPath as Nt}from"url";import"dotenv/config";import{createGraphClient as It,resolveToken as Ot}from"@ilivemylife/graph-sdk";import{config as _t}from"dotenv";_t();var We=Ot()||process.env.TOKEN;We||(console.error(`
2
2
  [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.
3
3
  `),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
4
4
  `),console.error(` Or add ILML_TOKEN=... to .env
@@ -8,7 +8,7 @@ ${o.join(`
8
8
  `)}`;try{await He.addMessage(i,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Ft=Nt(import.meta.url),Pt=Y.dirname(Y.dirname(Ft)),ve=process.env.DATA_DIR?Y.resolve(process.env.DATA_DIR,"collected-profiles"):Y.join(Pt,"collected-profiles"),be=Y.join(ve,"run-log.json");function Lt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";U.writeFileSync(o,n);for(let s=0;s<3;s++)try{U.renameSync(o,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 Ye(){try{if(!U.existsSync(be))return{runs:[]};let e=JSON.parse(U.readFileSync(be,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ge(e){U.existsSync(ve)||U.mkdirSync(ve,{recursive:!0});try{Lt(be,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ze(e,t="default"){let n=Ye();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,s={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>r),Ge(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function $e(e,t,n=null,o=null){if(!e)return;let s=null;try{let i=Ye(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,s=l.duration;else{let a=i.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=n,a.error=o,s=a.duration)}Ge(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=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Ve({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import Jt from"puppeteer";import{addExtra as Wt}from"puppeteer-extra";import Ht from"puppeteer-extra-plugin-stealth";import Ke from"fs";import Ut from"path";var Bt="cookies.json";function qt(){let e=process.env.ILML_SCOPE_DIR;return e?Ut.join(e,"plugins-state","linkedin","cookies.json"):Bt}function Qe(){let e=qt();if(!Ke.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Ke.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 et=Wt(Jt);et.use(Ht());async function tt(){let e=await et.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
9
9
  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=Qe();await n.setCookie(...o),console.log(" Browser launched, cookies loaded.")}catch(o){console.error(`
10
10
  [!] ${o.message}
11
- `),await e.close(),process.exit(1)}return{browser:e,page:n}}async function Ce(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await A(3e3)}console.log(" Inbox loaded.")}async function ot(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let i=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",m=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,p,h;if(a.startsWith("You:"))p="me",h=a.slice(4).trim();else{let c=i.split(" ")[0];if(a.startsWith(i+":")||a.startsWith(c+":")){p="them";let g=a.indexOf(":");h=a.slice(g+1).trim()}else p="them",h=a}let d=s.getBoundingClientRect();o.push({name:i,lastMessagePreview:h,lastMessageTime:u,unread:m,lastMessageBy:p,x:d.x+d.width/2,y:d.y+d.height/2})}return o});for(let n of t)n.lastMessageTime=ye(n.lastMessageTime)||n.lastMessageTime;return t}async function nt(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Vt(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let r=document.querySelector(s);if(r){let i=r.textContent?.trim()?.replace(/\s+/g," ");if(i&&i.length>1&&i.length<100&&!t.test(i))return i}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let r=s.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function Xe(e,t){let n=await Vt(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=n.toLowerCase();return{match:r.includes(o)||s.some(l=>r.includes(l)),headerName:n}}async function ke(e,t){let n=t.split(" ")[0],o=8e3,s=500,r=0;for(;r<o;){let{match:a,headerName:f}=await Xe(e,t);if(a)return await A(500),{verified:!0,headerName:f};let u=await e.evaluate(()=>{let m=document.querySelectorAll(".msg-s-message-group__name"),p=Array.from(m).map(d=>d.textContent?.trim()).filter(Boolean),h=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:p,msgCount:h}});if(u.msgCount>0&&u.allSenders.some(p=>p.toLowerCase().includes(n.toLowerCase())))return await A(300),{verified:!0,headerName:n};await A(s),r+=s}let{match:i,headerName:l}=await Xe(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function Yt(e){let n=0,o=0;for(let s=0;s<50;s++){let r=await e.evaluate(()=>{let i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let f=document.querySelector(".msg-overlay-conversation-bubble");f&&(i=f.querySelector(".msg-s-message-list-container")||f.querySelector(".msg-s-message-list"))}if(!i)return{found:!1};let l=i.querySelectorAll("li.msg-s-message-list__event").length;return i.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(i.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!r.found||r.atTop)break;if(await A(800),r.msgCount===n){if(o++,o>=3)break}else o=0;n=r.msgCount}}async function Q(e,{scrollUp:t=!0}={}){t&&await Yt(e);let n=await e.evaluate(()=>{let o=[],s="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(r=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!r)return o;let i=r.querySelectorAll("li.msg-s-message-list__event");if(i.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(i=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(u){let m=u.getAttribute("data-event-urn");if(!m)return null;let p=m.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!p)return null;try{let d=atob(p[1]).match(/^(\d{13})/);if(!d)return null;let c=Number(d[1]);if(c>14200704e5&&c<20512224e5)return c}catch{}return null}let a="";function f(u,m,p){let h=l(u),c=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",g=u.querySelector(".msg-s-event-listitem__message-bubble");if(!g)return null;let y=g.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let v=h?new Date(h).toISOString():p?`${p} ${c}`.trim():c;return{sender:m,text:y,time:v}}for(let u of i){let m=u.querySelector("time.msg-s-message-list__time-heading");m&&(a=m.textContent?.trim()||a);let p=u.querySelectorAll(".msg-s-message-group");if(p.length>0)for(let h of p){let d=h.querySelector(".msg-s-message-group__name");d&&(s=d.textContent?.trim()||s);let c=s||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let v=f(y,c,a);v&&o.push(v)}}else{let h=u.querySelectorAll(".msg-s-event-listitem");for(let d of h){let c=d.querySelector(".msg-s-message-group__name");c&&(s=c.textContent?.trim()||s);let y=f(d,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let m of u){let p=m.textContent?.trim();p&&o.push({sender:"",text:p,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=ye(o.time)||o.time);return n}function se(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function le(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=p=>se(p.sender)+"||"+se(p.text),o=new Set(t.map(n)),s=new Set(e.map(n)),r=e.filter(p=>K.has(p.status)?!1:!o.has(n(p))),i=t.filter(p=>!s.has(n(p))),l=t.filter(p=>s.has(n(p))),a=e.filter(p=>K.has(p.status)),f=[...r,...l,...i],u=[];for(let p of f){let h=se(p.text),d=se(p.sender),c=!1;for(let g=0;g<u.length;g++){let y=u[g];if(se(y.sender)!==d)continue;let v=se(y.text);if(h.length>v.length&&h.endsWith(v)){c=!0;break}if(v.length>h.length&&v.endsWith(h)){u[g]=p,c=!0;break}}c||u.push(p)}return[...u,...a]}async function pe(e,t){let n=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let a of l)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let m=a.getBoundingClientRect();if(m.height>0)return{x:m.x+m.width/2,y:m.y+m.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await A(3e3);let i=await ke(e,t);if(i.verified)return i}let o=Ue(t),s=o!==t?[t,o]:[t];for(let i of s)if(await Ze(e,i,t)){let a=await ke(e,t);if(a.verified)return a}let r=Be(o);if(r!==o&&r.length>0&&await Ze(e,r,t,{requireUnique:!0})){let l=await ke(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Ze(e,t,n,o={}){let{requireUnique:s=!1}=o,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await A(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await A(300),await r.type(t,{delay:30}),await A(500),await e.keyboard.press("Enter"),await A(3500);let i=await e.evaluate((l,a)=>{let f=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),m=document.querySelectorAll(".msg-conversation-listitem"),p=[],h=[];for(let c of m){let y=c.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",v=y.toLowerCase();if(v.includes(f)){let S=c.getBoundingClientRect();if(S.height>0){let C=y.includes(",")||/\d+ other/.test(y),T=v===u?3:v.includes(u)?2:1,I={text:y,isGroup:C,score:T,x:S.x+S.width/2,y:S.y+S.height/2};C?h.push(I):p.push(I)}}}p.sort((c,g)=>g.score-c.score);let d=[...p,...h];return a&&d.length!==1?null:p[0]||h[0]||null},n,s);return i?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function st(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await A(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await A(1e3))}import"dotenv/config";import*as w from"fs";import*as xe from"os";import*as R from"path";import{fileURLToPath as po}from"url";var Te={};Pe(Te,{NAME:()=>zt,VERSION:()=>Gt,up:()=>Xt});import*as B from"fs";import*as me from"path";var Gt=1,zt="normalize-jobs-and-questions",Kt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Qt=50;function Ee(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function De(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 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 Xt(e,t){let n=me.join(e,"jobs.json"),o=me.join(t,"scouted-jobs.json"),s=me.join(e,"application-questions.json"),r=Ee(n)||{},i=Ee(o)||{},l=0,a=[];for(let u of Object.keys(r)){if(!i[u])continue;let m=i[u],p=r[u];for(let h of Kt)m[h]!=null&&p[h]==null&&(p[h]=m[h]);a.push(u),l++}l>0?(De(n,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Ee(s);if(f&&Array.isArray(f.applications)){let u={},m=0;for(let p of f.applications){let h=p.jobId||"unknown";u[h]||(u[h]={applications:[]});let d=(p.questions||[]).map(c=>{let g={type:c.type||"input",question:c.question||"",answer:c.answer||""};return c.options&&(c.options.length<=Qt?g.options=c.options:(g.optionsOmitted=!0,m++)),c.page&&(g.page=c.page),c.wasPreFilled&&(g.wasPreFilled=!0),c.wasRetry&&(g.wasRetry=!0),g});u[h].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||d.length,questions:d})}De(s,u),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete i[u];De(o,i),console.log(` Phase 3: Removed ${a.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 Ae={};Pe(Ae,{NAME:()=>eo,VERSION:()=>Zt,up:()=>no});import*as q from"fs";import*as rt from"path";var Zt=2,eo="reset-unread-flags";function to(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function oo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{q.writeFileSync(o,n)}catch(s){try{q.unlinkSync(o)}catch{}throw s}try{q.renameSync(o,e)}catch(s){try{q.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function no(e){let t=rt.join(e,"conversations.json"),n=to(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}oo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}import"dotenv/config";import*as L from"path";import{fileURLToPath as so}from"url";var ro=so(import.meta.url),io=L.dirname(L.dirname(ro)),ae=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(io,"market-research"),Tn=L.join(ae,"scouted-jobs.json"),An=L.join(ae,"discovered-people.json"),Rn=L.join(ae,"visit-log.json"),xn=L.join(ae,"companies.json"),In=L.join(ae,"job-decisions.json");function it(){lo=null,ao=null,co=null,uo=null,fo=null}var lo=null;var ao=null;var co=null;var uo=null;var fo=null;var mo=po(import.meta.url),go=R.dirname(mo),ho=R.dirname(R.dirname(go));function yo(e){return e&&(e==="~"?xe.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(xe.homedir(),e.slice(2)):e)}var W=process.env.DATA_DIR?R.resolve(yo(process.env.DATA_DIR)):ho,Z=R.join(W,"collected-profiles"),ee=R.join(W,"market-research"),M=R.join(W,".schema-version"),lt=[R.join(Z,".schema-version"),R.join(ee,".schema-version")],G=2,V=[{version:1,module:Te},{version:2,module:Ae}];(function(){V.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of V){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=V.length?V[V.length-1].version:0;if(n!==G)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${G}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<V.length;o++){let s=o+1;if(V[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${V[o].version}`)}})();function ft(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
11
+ `),await e.close(),process.exit(1)}return{browser:e,page:n}}async function Ce(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await A(3e3)}console.log(" Inbox loaded.")}async function ot(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let i=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",m=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,p,h;if(a.startsWith("You:"))p="me",h=a.slice(4).trim();else{let c=i.split(" ")[0];if(a.startsWith(i+":")||a.startsWith(c+":")){p="them";let g=a.indexOf(":");h=a.slice(g+1).trim()}else p="them",h=a}let d=s.getBoundingClientRect();o.push({name:i,lastMessagePreview:h,lastMessageTime:u,unread:m,lastMessageBy:p,x:d.x+d.width/2,y:d.y+d.height/2})}return o});for(let n of t)n.lastMessageTime=ye(n.lastMessageTime)||n.lastMessageTime;return t}async function nt(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Vt(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let r=document.querySelector(s);if(r){let i=r.textContent?.trim()?.replace(/\s+/g," ");if(i&&i.length>1&&i.length<100&&!t.test(i))return i}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let r=s.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function Xe(e,t){let n=await Vt(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=n.toLowerCase();return{match:r.includes(o)||s.some(l=>r.includes(l)),headerName:n}}async function ke(e,t){let n=t.split(" ")[0],o=8e3,s=500,r=0;for(;r<o;){let{match:a,headerName:f}=await Xe(e,t);if(a)return await A(500),{verified:!0,headerName:f};let u=await e.evaluate(()=>{let m=document.querySelectorAll(".msg-s-message-group__name"),p=Array.from(m).map(d=>d.textContent?.trim()).filter(Boolean),h=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:p,msgCount:h}});if(u.msgCount>0&&u.allSenders.some(p=>p.toLowerCase().includes(n.toLowerCase())))return await A(300),{verified:!0,headerName:n};await A(s),r+=s}let{match:i,headerName:l}=await Xe(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function Yt(e){let n=0,o=0;for(let s=0;s<50;s++){let r=await e.evaluate(()=>{let i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let f=document.querySelector(".msg-overlay-conversation-bubble");f&&(i=f.querySelector(".msg-s-message-list-container")||f.querySelector(".msg-s-message-list"))}if(!i)return{found:!1};let l=i.querySelectorAll("li.msg-s-message-list__event").length;return i.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(i.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!r.found||r.atTop)break;if(await A(800),r.msgCount===n){if(o++,o>=3)break}else o=0;n=r.msgCount}}async function Q(e,{scrollUp:t=!0}={}){t&&await Yt(e);let n=await e.evaluate(()=>{let o=[],s="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(r=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!r)return o;let i=r.querySelectorAll("li.msg-s-message-list__event");if(i.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(i=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(u){let m=u.getAttribute("data-event-urn");if(!m)return null;let p=m.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!p)return null;try{let d=atob(p[1]).match(/^(\d{13})/);if(!d)return null;let c=Number(d[1]);if(c>14200704e5&&c<20512224e5)return c}catch{}return null}let a="";function f(u,m,p){let h=l(u),c=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",g=u.querySelector(".msg-s-event-listitem__message-bubble");if(!g)return null;let y=g.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let v=h?new Date(h).toISOString():p?`${p} ${c}`.trim():c;return{sender:m,text:y,time:v}}for(let u of i){let m=u.querySelector("time.msg-s-message-list__time-heading");m&&(a=m.textContent?.trim()||a);let p=u.querySelectorAll(".msg-s-message-group");if(p.length>0)for(let h of p){let d=h.querySelector(".msg-s-message-group__name");d&&(s=d.textContent?.trim()||s);let c=s||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let v=f(y,c,a);v&&o.push(v)}}else{let h=u.querySelectorAll(".msg-s-event-listitem");for(let d of h){let c=d.querySelector(".msg-s-message-group__name");c&&(s=c.textContent?.trim()||s);let y=f(d,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let m of u){let p=m.textContent?.trim();p&&o.push({sender:"",text:p,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=ye(o.time)||o.time);return n}function se(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function le(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=p=>se(p.sender)+"||"+se(p.text),o=new Set(t.map(n)),s=new Set(e.map(n)),r=e.filter(p=>z.has(p.status)?!1:!o.has(n(p))),i=t.filter(p=>!s.has(n(p))),l=t.filter(p=>s.has(n(p))),a=e.filter(p=>z.has(p.status)),f=[...r,...l,...i],u=[];for(let p of f){let h=se(p.text),d=se(p.sender),c=!1;for(let g=0;g<u.length;g++){let y=u[g];if(se(y.sender)!==d)continue;let v=se(y.text);if(h.length>v.length&&h.endsWith(v)){c=!0;break}if(v.length>h.length&&v.endsWith(h)){u[g]=p,c=!0;break}}c||u.push(p)}return[...u,...a]}async function pe(e,t){let n=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let a of l)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let m=a.getBoundingClientRect();if(m.height>0)return{x:m.x+m.width/2,y:m.y+m.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await A(3e3);let i=await ke(e,t);if(i.verified)return i}let o=Ue(t),s=o!==t?[t,o]:[t];for(let i of s)if(await Ze(e,i,t)){let a=await ke(e,t);if(a.verified)return a}let r=Be(o);if(r!==o&&r.length>0&&await Ze(e,r,t,{requireUnique:!0})){let l=await ke(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Ze(e,t,n,o={}){let{requireUnique:s=!1}=o,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await A(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await A(300),await r.type(t,{delay:30}),await A(500),await e.keyboard.press("Enter"),await A(3500);let i=await e.evaluate((l,a)=>{let f=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),m=document.querySelectorAll(".msg-conversation-listitem"),p=[],h=[];for(let c of m){let y=c.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",v=y.toLowerCase();if(v.includes(f)){let S=c.getBoundingClientRect();if(S.height>0){let C=y.includes(",")||/\d+ other/.test(y),T=v===u?3:v.includes(u)?2:1,I={text:y,isGroup:C,score:T,x:S.x+S.width/2,y:S.y+S.height/2};C?h.push(I):p.push(I)}}}p.sort((c,g)=>g.score-c.score);let d=[...p,...h];return a&&d.length!==1?null:p[0]||h[0]||null},n,s);return i?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function st(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await A(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await A(1e3))}import"dotenv/config";import*as w from"fs";import*as xe from"os";import*as R from"path";import{fileURLToPath as po}from"url";var Te={};Pe(Te,{NAME:()=>zt,VERSION:()=>Gt,up:()=>Xt});import*as B from"fs";import*as me from"path";var Gt=1,zt="normalize-jobs-and-questions",Kt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Qt=50;function Ee(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function De(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 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 Xt(e,t){let n=me.join(e,"jobs.json"),o=me.join(t,"scouted-jobs.json"),s=me.join(e,"application-questions.json"),r=Ee(n)||{},i=Ee(o)||{},l=0,a=[];for(let u of Object.keys(r)){if(!i[u])continue;let m=i[u],p=r[u];for(let h of Kt)m[h]!=null&&p[h]==null&&(p[h]=m[h]);a.push(u),l++}l>0?(De(n,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Ee(s);if(f&&Array.isArray(f.applications)){let u={},m=0;for(let p of f.applications){let h=p.jobId||"unknown";u[h]||(u[h]={applications:[]});let d=(p.questions||[]).map(c=>{let g={type:c.type||"input",question:c.question||"",answer:c.answer||""};return c.options&&(c.options.length<=Qt?g.options=c.options:(g.optionsOmitted=!0,m++)),c.page&&(g.page=c.page),c.wasPreFilled&&(g.wasPreFilled=!0),c.wasRetry&&(g.wasRetry=!0),g});u[h].applications.push({applicationId:p.applicationId,date:p.date,result:p.result||"submitted",formPages:p.formPages||null,duration:p.duration||null,retries:p.retries||0,failedField:p.failedField||null,questionCount:p.questionCount||d.length,questions:d})}De(s,u),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete i[u];De(o,i),console.log(` Phase 3: Removed ${a.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 Ae={};Pe(Ae,{NAME:()=>eo,VERSION:()=>Zt,up:()=>no});import*as q from"fs";import*as rt from"path";var Zt=2,eo="reset-unread-flags";function to(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function oo(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{q.writeFileSync(o,n)}catch(s){try{q.unlinkSync(o)}catch{}throw s}try{q.renameSync(o,e)}catch(s){try{q.unlinkSync(o)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function no(e){let t=rt.join(e,"conversations.json"),n=to(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}oo(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}import"dotenv/config";import*as L from"path";import{fileURLToPath as so}from"url";var ro=so(import.meta.url),io=L.dirname(L.dirname(ro)),ae=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(io,"market-research"),An=L.join(ae,"scouted-jobs.json"),Rn=L.join(ae,"discovered-people.json"),xn=L.join(ae,"visit-log.json"),In=L.join(ae,"companies.json"),On=L.join(ae,"job-decisions.json");function it(){lo=null,ao=null,co=null,uo=null,fo=null}var lo=null;var ao=null;var co=null;var uo=null;var fo=null;var mo=po(import.meta.url),go=R.dirname(mo),ho=R.dirname(R.dirname(go));function yo(e){return e&&(e==="~"?xe.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(xe.homedir(),e.slice(2)):e)}var W=process.env.DATA_DIR?R.resolve(yo(process.env.DATA_DIR)):ho,Z=R.join(W,"collected-profiles"),ee=R.join(W,"market-research"),M=R.join(W,".schema-version"),lt=[R.join(Z,".schema-version"),R.join(ee,".schema-version")],G=2,V=[{version:1,module:Te},{version:2,module:Ae}];(function(){V.sort((o,s)=>o.version-s.version);let t=new Set;for(let o of V){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=V.length?V[V.length-1].version:0;if(n!==G)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${G}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<V.length;o++){let s=o+1;if(V[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${V[o].version}`)}})();function ft(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
12
12
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
13
13
  `),process.exit(1));try{w.mkdirSync(W,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
14
  [FATAL] Cannot create DATA_DIR (${W}): ${t.message}`),console.error(` Fix the path or permissions and try again.
@@ -48,7 +48,7 @@ ${o.join(`
48
48
  [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
49
49
  `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{qe()}catch{}try{it()}catch{}Re=!0,Ie(),console.log(`
50
50
  \u2713 Schema is now at v${G}
51
- `)}var ko=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Co(e){let t=e.toLowerCase();return ko.some(n=>n.test(t))}var Eo=6e4;function Do(){let e=Date.now(),t=[];for(let n of[W,Z,ee]){if(!w.existsSync(n))continue;let o;try{o=w.readdirSync(n)}catch{continue}for(let s of o){if(!Co(s))continue;let r=R.join(n,s);try{let i=w.statSync(r);if(!i.isFile()||e-i.mtimeMs<Eo)continue;t.push({dir:n,file:s,fullPath:r})}catch{}}}return t}function To({verbose:e=!1}={}){let t=Do();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{w.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${R.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 Ao(){let e=[];for(let t of[Z,ee]){if(!w.existsSync(t))continue;let n=w.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=R.join(t,o);try{ge(s)}catch(r){e.push({dir:R.basename(t),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ro(e){let t=[],n=[];for(let r of[Z,ee]){if(!w.existsSync(r))continue;let i=w.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let a=R.join(r,l),f=l.slice(0,-e.length),u=R.join(r,f);try{f.toLowerCase().endsWith(".json")?ge(a):w.accessSync(a,w.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:l,dir:r})}catch(m){n.push(`${R.basename(r)}/${l}: ${m.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:a}of t)try{mt(r,i),o++}catch(f){s.push(`${R.basename(a)}/${l}: ${f.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function mt(e,t){let n=t+".tmp";try{w.copyFileSync(e,n),dt(n)}catch(o){try{w.unlinkSync(n)}catch{}throw o}try{w.renameSync(n,t)}catch(o){try{w.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}await pt();var xo=ne.toLowerCase().split(/\s+/).filter(e=>e.length>1);function Me(e){if(!e)return!1;if(e===ne)return!0;let t=e.toLowerCase();return xo.some(n=>t.includes(n))}function Oe(e){return(e.messages||[]).find(t=>ie.has(t.status))}function N(e){return(e.messages||[]).find(t=>K.has(t.status))}function _e(e){return Oe(e)?.text||null}function je(e){return(e.messages||[]).some(t=>ie.has(t.status))}function Io(e){return(e.messages||[]).some(t=>K.has(t.status))}function Oo(e,t){let n=N(e);n&&(n.text=t)}function _o(){let e={list:!1,full:!1,read:null,send:null,sendBatch:null,pushDrafts:!1,reviewDrafts:!1,max:1/0,dryRun:!1,verbose:!1},t=process.argv.slice(2);for(let n=0;n<t.length;n++){let o=t[n];if(o==="--list")e.list=!0;else if(o==="--full")e.full=!0;else if(o==="--dry-run")e.dryRun=!0;else if(o==="--verbose")e.verbose=!0;else if(o.startsWith("--max="))e.max=parseInt(o.split("=")[1],10);else if(o==="--read")e.read=t[++n]||null;else if(o==="--send"){let s=t[++n],r=t[++n]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=te.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.send={target:s,text:r}}else if(o==="--draft"){let s=t[++n],r=t[++n]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=te.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.draft={target:s,text:r}}else if(o==="--push-drafts")e.pushDrafts=!0;else if(o==="--review-drafts")e.reviewDrafts=!0;else if(o==="--follow-up"){let s=t[++n],r=t[++n]||"",i=t[++n]||null;e.followUp={target:s,note:r,date:i}}else if(o==="--follow-up-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.followUpBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read follow-up batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--clear-follow-up")e.clearFollowUp=t[++n]||null;else if(o==="--review")e.review=t[++n]||null;else if(o==="--review-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.reviewBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read review batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--draft-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.draftBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read draft batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--send-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.sendBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}}return e}function jo(){let e=j(),t=Object.entries(e),n=t.length;if(n===0){console.log(`
51
+ `)}var ko=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Co(e){let t=e.toLowerCase();return ko.some(n=>n.test(t))}var Eo=6e4;function Do(){let e=Date.now(),t=[];for(let n of[W,Z,ee]){if(!w.existsSync(n))continue;let o;try{o=w.readdirSync(n)}catch{continue}for(let s of o){if(!Co(s))continue;let r=R.join(n,s);try{let i=w.statSync(r);if(!i.isFile()||e-i.mtimeMs<Eo)continue;t.push({dir:n,file:s,fullPath:r})}catch{}}}return t}function To({verbose:e=!1}={}){let t=Do();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{w.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${R.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 Ao(){let e=[];for(let t of[Z,ee]){if(!w.existsSync(t))continue;let n=w.readdirSync(t).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of n){let s=R.join(t,o);try{ge(s)}catch(r){e.push({dir:R.basename(t),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ro(e){let t=[],n=[];for(let r of[Z,ee]){if(!w.existsSync(r))continue;let i=w.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let a=R.join(r,l),f=l.slice(0,-e.length),u=R.join(r,f);try{f.toLowerCase().endsWith(".json")?ge(a):w.accessSync(a,w.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:l,dir:r})}catch(m){n.push(`${R.basename(r)}/${l}: ${m.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:a}of t)try{mt(r,i),o++}catch(f){s.push(`${R.basename(a)}/${l}: ${f.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function mt(e,t){let n=t+".tmp";try{w.copyFileSync(e,n),dt(n)}catch(o){try{w.unlinkSync(n)}catch{}throw o}try{w.renameSync(n,t)}catch(o){try{w.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}await pt();var xo=oe.toLowerCase().split(/\s+/).filter(e=>e.length>1);function Me(e){if(!e)return!1;if(e===oe)return!0;let t=e.toLowerCase();return xo.some(n=>t.includes(n))}function Oe(e){return(e.messages||[]).find(t=>ie.has(t.status))}function N(e){return(e.messages||[]).find(t=>z.has(t.status))}function _e(e){return Oe(e)?.text||null}function je(e){return(e.messages||[]).some(t=>ie.has(t.status))}function Io(e){return(e.messages||[]).some(t=>z.has(t.status))}function Oo(e,t){let n=N(e);n&&(n.text=t)}function _o(){let e={list:!1,full:!1,read:null,send:null,sendBatch:null,pushDrafts:!1,reviewDrafts:!1,max:1/0,dryRun:!1,verbose:!1},t=process.argv.slice(2);for(let n=0;n<t.length;n++){let o=t[n];if(o==="--list")e.list=!0;else if(o==="--full")e.full=!0;else if(o==="--dry-run")e.dryRun=!0;else if(o==="--verbose")e.verbose=!0;else if(o.startsWith("--max="))e.max=parseInt(o.split("=")[1],10);else if(o==="--read")e.read=t[++n]||null;else if(o==="--send"){let s=t[++n],r=t[++n]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=te.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.send={target:s,text:r}}else if(o==="--draft"){let s=t[++n],r=t[++n]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=te.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.draft={target:s,text:r}}else if(o==="--push-drafts")e.pushDrafts=!0;else if(o==="--review-drafts")e.reviewDrafts=!0;else if(o==="--follow-up"){let s=t[++n],r=t[++n]||"",i=t[++n]||null;e.followUp={target:s,note:r,date:i}}else if(o==="--follow-up-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.followUpBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read follow-up batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--clear-follow-up")e.clearFollowUp=t[++n]||null;else if(o==="--review")e.review=t[++n]||null;else if(o==="--review-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.reviewBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read review batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--draft-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.draftBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read draft batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--send-batch"){let s=t[++n]||"";s.startsWith("@")&&(s=s.slice(1));try{e.sendBatch=JSON.parse(te.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}}return e}function jo(){let e=j(),t=Object.entries(e),n=t.length;if(n===0){console.log(`
52
52
  No conversations synced yet. Run: npm run messages
53
53
  `);return}let o={};for(let[,d]of t){let c=d.conversationStatus||"(none)";o[c]=(o[c]||0)+1}let s=t.filter(([,d])=>d.conversationStatus==="unanswered_by_us").sort((d,c)=>{let g=d[1].lastSynced||"";return(c[1].lastSynced||"").localeCompare(g)});console.log(`
54
54
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` Conversations: ${n} total`),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"),console.log(`
@@ -78,7 +78,7 @@ ${"\u2550".repeat(60)}`),console.log(` ${u+1}/${s.length} ${c} ${m} ${g} ${(p
78
78
  Extracted ${c.length} conversations.`);let g=Jo(c,r);Wo(c,g,r,i)}async function Fo(e,t,n){let o=J(),s=j(),r;if(t.startsWith("http")){let f=o[t],u=Object.entries(s).find(([,m])=>m.profileUrl===t);r=f?.name||u?.[0]}else r=t;if(!r){console.error(` Cannot find name for "${t}". Run inbox scan first.`);return}console.log(`
79
79
  Reading conversation with: ${r}
80
80
  `),await Ce(e);let{verified:i}=await pe(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await Q(e);if(l.length===0){if(console.log(" No messages extracted (DOM may have changed)."),n){let f=await e.evaluate(()=>({events:document.querySelectorAll("li.msg-s-message-list__event").length,bubbles:document.querySelectorAll(".msg-s-event-listitem").length,any:document.querySelectorAll('[class*="msg-s-event"]').length}));console.log(" [DEBUG] Counts:",f)}}else{console.log(` ${l.length} messages:
81
- `);for(let f of l){let u=f.time?` (${f.time})`:"";console.log(` [${f.sender}]${u}`),console.log(` ${f.text}`),console.log()}}let a=r;s[a]||(s[a]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),s[a].messages=le(s[a].messages,l),s[a].lastSynced=new Date().toISOString(),P(s),console.log(` Saved ${s[a].messages.length} messages to conversations.json ["${a}"]`)}function Ne(e){let t=J(),n=e,o=null;if(e.startsWith("http")){let s=t[e];if(s?.name)n=s.name,o=e;else return null}else{let s=Object.entries(t).find(([,i])=>i.name===e);s&&(o=s[0]);let r=j();!o&&r[e]?.profileUrl&&(o=r[e].profileUrl)}return{personName:n,profileUrl:o}}async function Fe(e,t,n,o,s={}){try{let{verified:r}=await pe(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await Q(e),a=j()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages in thread (saved: ${a})`),i.length>a&&a>0){let $=i.length-a,D=i[i.length-1];return console.error(` \u2717 ABORT: ${$} new message(s) since last sync!`),console.error(` Latest: [${D.sender}] ${D.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let $=i[i.length-1],D=null;for(let E=i.length-1;E>=0;E--)if(i[E].sender!=="Unknown"&&i[E].sender!==""){D=i[E].sender;break}if(D===ne)if(s.allowDoubleMessage)console.log(" \u26A0 Last message is from us \u2014 but allowDoubleMessage is set (re-engagement).");else return console.error(" \u2717 ABORT: Last message is already from us!"),console.error(` "${$.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let f=o.slice(0,50).toLowerCase();if(i.some($=>$.text.toLowerCase().startsWith(f)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!s.allowDoubleMessage){let $=new Date().toISOString().slice(0,10);if(i.some(E=>{if(!Me(E.sender))return!1;let F=E.time||"";return F.startsWith($)||F.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}console.log(" \u2713 Safety checks passed");let m=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!m)return console.error(" Message input not found in conversation."),!1;await m.click(),await A(300);let p=o.replace(/\\([!?#$])/g,"$1");p!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=p),await e.keyboard.type(o,{delay:20}),await A(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),d=$=>$.replace(/\s+/g," ").trim(),c=d(o),g=d(h);if(g!==c){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${c.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let $=0;$<Math.max(c.length,g.length);$++)if(c[$]!==g[$]){console.error(` First diff at position ${$}: expected '${c[$]||"EOF"}' got '${g[$]||"EOF"}'`),console.error(` Context: ...${c.slice(Math.max(0,$-10),$+10)}...`);break}return await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1}console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found."),!1;await y.click(),await A(2e3),console.log(" \u2713 Message sent!"),console.log(" Syncing conversation thread..."),await A(1e3);let v=await Q(e);console.log(` Synced ${v.length} messages from thread.`);let S=j(),C=new Date().toISOString(),T=t;S[T]?(S[T].lastMessageBy="me",S[T].lastMessagePreview=o.slice(0,100),S[T].lastMessageTime=C,S[T].conversationStatus="awaiting_reply",S[T].lastSynced=C,S[T].messages=le(S[T].messages,v)):S[T]={profileUrl:n,lastSynced:C,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:v},n&&(S[T].profileUrl=n),P(S);let I=J(),b=n?I[n]:null;return b&&(b.conversationStatus="awaiting_reply",b.lastMessageSent=C,b.lastUpdated=C,de(I)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function ht(e,t,n){if(t?.profileUrl)return t.profileUrl;let o=Object.entries(n).find(([,s])=>s.name===e);return o?o[0]:null}async function Po(e,t,n,o){try{console.log(` \u2192 Profile fallback: navigating to ${n}`),await e.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await A(3e3);let s=await e.evaluate(()=>{let b=0,$=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let E of $){if(E.offsetHeight===0)continue;let x=E.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(x||(x=E.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!x){let F=E.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");F.length>0&&(x=F[F.length-1])}x&&x.offsetHeight>0&&(x.click(),b++)}let D=document.querySelector(".msg-overlay-list-bubble");if(D&&!D.classList.contains("msg-overlay-list-bubble--is-minimized")){let E=D.querySelector(".msg-overlay-bubble-header__button");E&&E.offsetHeight>0&&(E.click(),b++)}return b});s>0&&(console.log(` Closed ${s} existing overlay(s)`),await A(1500));let r=await e.evaluate(()=>{let b=document.querySelectorAll(".msg-overlay-conversation-bubble"),$=Array.from(b).filter(x=>x.offsetHeight>0),D=document.querySelector(".msg-overlay-list-bubble"),E=D?D.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:$.length,trayMinimized:E,bubbleNames:$.map(x=>x.querySelector('a[href*="/in/"]')?.textContent?.trim()?.slice(0,30)||"?")}});r.visibleBubbles>0&&console.log(` \u26A0 Still ${r.visibleBubbles} overlay(s) open: [${r.bubbleNames.join(", ")}], tray minimized: ${r.trayMinimized}`);let i=await e.evaluate(()=>{let b=document.querySelectorAll('a[href*="recipient="]');for(let $ of b)try{let E=new URL($.getAttribute("href"),location.origin).searchParams.get("recipient");if(E)return E}catch{}return null});if(!i)return console.error(" \u2717 Could not extract recipient URN from profile (no <a> with recipient=)"),!1;console.log(` \u2713 Extracted recipient URN: ${i.slice(0,24)}\u2026`);let l=`https://www.linkedin.com/messaging/thread/new/?recipient=${encodeURIComponent(i)}&screenContext=NON_SELF_PROFILE_VIEW`;await e.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3);let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;try{await e.waitForSelector("div.msg-form__contenteditable",{timeout:1e4})}catch{return console.error(" \u2717 Message composer (msg-form__contenteditable) never appeared on compose page"),!1}console.log(" \u2713 Compose page loaded, message form ready");let f=t.split(" ")[0].toLowerCase(),u=t.toLowerCase().split(/[\s,]+/).filter(b=>b.length>1),m=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(m){let b=m.toLowerCase();if(!(b.includes(f)||u.some(D=>b.includes(D))))return console.error(` \u2717 Recipient mismatch: compose shows "${m}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${m}"`)}else console.log(" \u26A0 Could not read recipient pill \u2014 proceeding with URN-trust");let p=await Q(e,{scrollUp:!1});if(p.length>0){let b=o.slice(0,50).toLowerCase();if(p.some(x=>x.text.toLowerCase().startsWith(b)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let D=new Date().toISOString().slice(0,10);if(p.some(x=>{if(!Me(x.sender))return!1;let ce=x.time||"";return ce.startsWith(D)||ce.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let h=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!h)return console.error(" Message input not found in overlay."),!1;await h.click(),await A(300);let d=o.replace(/\\([!?#$])/g,"$1");d!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=d),await e.keyboard.type(o,{delay:20}),await A(500);let c=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),g=b=>b.replace(/\s+/g," ").trim();if(g(c)!==g(o))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${g(o).slice(0,100)}..."`),console.error(` Actual: "${g(c).slice(0,100)}..."`),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1;console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found in overlay."),!1;await y.click(),await A(2e3),console.log(" \u2713 Message sent via profile!"),console.log(" Syncing conversation thread..."),await A(1e3);let v=await Q(e);console.log(` Synced ${v.length} messages from thread.`);let S=j(),C=new Date().toISOString();S[t]?(S[t].lastMessageBy="me",S[t].lastMessagePreview=o.slice(0,100),S[t].lastMessageTime=C,S[t].conversationStatus="awaiting_reply",S[t].lastSynced=C,S[t].messages=le(S[t].messages,v)):S[t]={profileUrl:n,lastSynced:C,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:v},n&&(S[t].profileUrl=n),P(S);let T=J(),I=T[n];return I&&(I.conversationStatus="awaiting_reply",I.lastMessageSent=C,I.lastUpdated=C,de(T)),!0}catch(s){return console.error(" \u2717 Profile send error:",s.message),!1}}async function Lo(e,t,n,o){if(!t||!n)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let s=Ne(t);return s?(console.log(`
81
+ `);for(let f of l){let u=f.time?` (${f.time})`:"";console.log(` [${f.sender}]${u}`),console.log(` ${f.text}`),console.log()}}let a=r;s[a]||(s[a]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),s[a].messages=le(s[a].messages,l),s[a].lastSynced=new Date().toISOString(),P(s),console.log(` Saved ${s[a].messages.length} messages to conversations.json ["${a}"]`)}function Ne(e){let t=J(),n=e,o=null;if(e.startsWith("http")){let s=t[e];if(s?.name)n=s.name,o=e;else return null}else{let s=Object.entries(t).find(([,i])=>i.name===e);s&&(o=s[0]);let r=j();!o&&r[e]?.profileUrl&&(o=r[e].profileUrl)}return{personName:n,profileUrl:o}}async function Fe(e,t,n,o,s={}){try{let{verified:r}=await pe(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await Q(e),a=j()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages in thread (saved: ${a})`),i.length>a&&a>0){let $=i.length-a,D=i[i.length-1];return console.error(` \u2717 ABORT: ${$} new message(s) since last sync!`),console.error(` Latest: [${D.sender}] ${D.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let $=i[i.length-1],D=null;for(let E=i.length-1;E>=0;E--)if(i[E].sender!=="Unknown"&&i[E].sender!==""){D=i[E].sender;break}if(D===oe)if(s.allowDoubleMessage)console.log(" \u26A0 Last message is from us \u2014 but allowDoubleMessage is set (re-engagement).");else return console.error(" \u2717 ABORT: Last message is already from us!"),console.error(` "${$.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let f=o.slice(0,50).toLowerCase();if(i.some($=>$.text.toLowerCase().startsWith(f)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!s.allowDoubleMessage){let $=new Date().toISOString().slice(0,10);if(i.some(E=>{if(!Me(E.sender))return!1;let F=E.time||"";return F.startsWith($)||F.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}console.log(" \u2713 Safety checks passed");let m=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!m)return console.error(" Message input not found in conversation."),!1;await m.click(),await A(300);let p=o.replace(/\\([!?#$])/g,"$1");p!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=p),await e.keyboard.type(o,{delay:20}),await A(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),d=$=>$.replace(/\s+/g," ").trim(),c=d(o),g=d(h);if(g!==c){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${c.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let $=0;$<Math.max(c.length,g.length);$++)if(c[$]!==g[$]){console.error(` First diff at position ${$}: expected '${c[$]||"EOF"}' got '${g[$]||"EOF"}'`),console.error(` Context: ...${c.slice(Math.max(0,$-10),$+10)}...`);break}return await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1}console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found."),!1;await y.click(),await A(2e3),console.log(" \u2713 Message sent!"),console.log(" Syncing conversation thread..."),await A(1e3);let v=await Q(e);console.log(` Synced ${v.length} messages from thread.`);let S=j(),C=new Date().toISOString(),T=t;S[T]?(S[T].lastMessageBy="me",S[T].lastMessagePreview=o.slice(0,100),S[T].lastMessageTime=C,S[T].conversationStatus="awaiting_reply",S[T].lastSynced=C,S[T].messages=le(S[T].messages,v)):S[T]={profileUrl:n,lastSynced:C,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:v},n&&(S[T].profileUrl=n),P(S);let I=J(),b=n?I[n]:null;return b&&(b.conversationStatus="awaiting_reply",b.lastMessageSent=C,b.lastUpdated=C,de(I)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function ht(e,t,n){if(t?.profileUrl)return t.profileUrl;let o=Object.entries(n).find(([,s])=>s.name===e);return o?o[0]:null}async function Po(e,t,n,o){try{console.log(` \u2192 Profile fallback: navigating to ${n}`),await e.goto(n,{waitUntil:"domcontentloaded",timeout:3e4}),await A(3e3);let s=await e.evaluate(()=>{let b=0,$=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let E of $){if(E.offsetHeight===0)continue;let x=E.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(x||(x=E.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!x){let F=E.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");F.length>0&&(x=F[F.length-1])}x&&x.offsetHeight>0&&(x.click(),b++)}let D=document.querySelector(".msg-overlay-list-bubble");if(D&&!D.classList.contains("msg-overlay-list-bubble--is-minimized")){let E=D.querySelector(".msg-overlay-bubble-header__button");E&&E.offsetHeight>0&&(E.click(),b++)}return b});s>0&&(console.log(` Closed ${s} existing overlay(s)`),await A(1500));let r=await e.evaluate(()=>{let b=document.querySelectorAll(".msg-overlay-conversation-bubble"),$=Array.from(b).filter(x=>x.offsetHeight>0),D=document.querySelector(".msg-overlay-list-bubble"),E=D?D.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:$.length,trayMinimized:E,bubbleNames:$.map(x=>x.querySelector('a[href*="/in/"]')?.textContent?.trim()?.slice(0,30)||"?")}});r.visibleBubbles>0&&console.log(` \u26A0 Still ${r.visibleBubbles} overlay(s) open: [${r.bubbleNames.join(", ")}], tray minimized: ${r.trayMinimized}`);let i=await e.evaluate(()=>{let b=document.querySelectorAll('a[href*="recipient="]');for(let $ of b)try{let E=new URL($.getAttribute("href"),location.origin).searchParams.get("recipient");if(E)return E}catch{}return null});if(!i)return console.error(" \u2717 Could not extract recipient URN from profile (no <a> with recipient=)"),!1;console.log(` \u2713 Extracted recipient URN: ${i.slice(0,24)}\u2026`);let l=`https://www.linkedin.com/messaging/thread/new/?recipient=${encodeURIComponent(i)}&screenContext=NON_SELF_PROFILE_VIEW`;await e.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await A(3e3);let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;try{await e.waitForSelector("div.msg-form__contenteditable",{timeout:1e4})}catch{return console.error(" \u2717 Message composer (msg-form__contenteditable) never appeared on compose page"),!1}console.log(" \u2713 Compose page loaded, message form ready");let f=t.split(" ")[0].toLowerCase(),u=t.toLowerCase().split(/[\s,]+/).filter(b=>b.length>1),m=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(m){let b=m.toLowerCase();if(!(b.includes(f)||u.some(D=>b.includes(D))))return console.error(` \u2717 Recipient mismatch: compose shows "${m}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${m}"`)}else console.log(" \u26A0 Could not read recipient pill \u2014 proceeding with URN-trust");let p=await Q(e,{scrollUp:!1});if(p.length>0){let b=o.slice(0,50).toLowerCase();if(p.some(x=>x.text.toLowerCase().startsWith(b)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let D=new Date().toISOString().slice(0,10);if(p.some(x=>{if(!Me(x.sender))return!1;let ce=x.time||"";return ce.startsWith(D)||ce.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let h=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!h)return console.error(" Message input not found in overlay."),!1;await h.click(),await A(300);let d=o.replace(/\\([!?#$])/g,"$1");d!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=d),await e.keyboard.type(o,{delay:20}),await A(500);let c=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),g=b=>b.replace(/\s+/g," ").trim();if(g(c)!==g(o))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${g(o).slice(0,100)}..."`),console.error(` Actual: "${g(c).slice(0,100)}..."`),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1;console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found in overlay."),!1;await y.click(),await A(2e3),console.log(" \u2713 Message sent via profile!"),console.log(" Syncing conversation thread..."),await A(1e3);let v=await Q(e);console.log(` Synced ${v.length} messages from thread.`);let S=j(),C=new Date().toISOString();S[t]?(S[t].lastMessageBy="me",S[t].lastMessagePreview=o.slice(0,100),S[t].lastMessageTime=C,S[t].conversationStatus="awaiting_reply",S[t].lastSynced=C,S[t].messages=le(S[t].messages,v)):S[t]={profileUrl:n,lastSynced:C,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:v},n&&(S[t].profileUrl=n),P(S);let T=J(),I=T[n];return I&&(I.conversationStatus="awaiting_reply",I.lastMessageSent=C,I.lastUpdated=C,de(T)),!0}catch(s){return console.error(" \u2717 Profile send error:",s.message),!1}}async function Lo(e,t,n,o){if(!t||!n)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let s=Ne(t);return s?(console.log(`
82
82
  Sending message to: ${s.personName}`),console.log(` Text: "${n.slice(0,150)}${n.length>150?"...":""}"`),o?(console.log(`
83
83
  [DRY RUN \u2014 message not sent]`),!1):(await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3),Fe(e,s.personName,s.profileUrl,n))):(console.error(` Person not found: ${t}`),!1)}async function Uo(e,t,n){if(console.log(`
84
84
  \u2550\u2550 Batch send: ${t.length} messages \u2550\u2550
@@ -93,7 +93,7 @@ Sending message to: ${s.personName}`),console.log(` Text: "${n.slice(0,150)}${n
93
93
  `);return}if(console.log(`
94
94
  \u2550\u2550 Pushing ${r.length} confirmed draft(s) \u2550\u2550`),i>0&&console.log(` (${i} more pending \u2014 run --review-drafts to confirm)`),console.log(),t){for(let[d,c]of r){let g=ht(d,c,o),y=c.messages?.some(S=>!ie.has(S.status)&&S.status!==k.REJECTED)?"inbox":g?"profile":"no profileUrl";console.log(` [DRY RUN] ${d} (${y}):`);let v=_e(c)||"";console.log(` "${v.slice(0,100)}${v.length>100?"...":""}"`),console.log()}return}console.log(`\u2500\u2500 Pass 1: Inbox search \u2500\u2500
95
95
  `),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let l=[],a=[];for(let d=0;d<r.length;d++){let[c,g]=r[d],y=_e(g);console.log(`
96
- \u2500\u2500 [${d+1}/${r.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let v=Ne(c),S=v?.personName||c,C=v?.profileUrl||g.profileUrl||null,I=(g.messages||[]).filter(D=>!K.has(D.status)).length,b=!1,$=!1;try{await Le(e);let{verified:D}=await pe(e,S);if(D){$=!0;let E=await Q(e);if(E.length>I&&I>0){let x=E.length-I;b=!0,g.messages=le(g.messages,E),console.log(` \u26A0 ${x} new message(s) since draft was created!`);let F=E[E.length-1];console.log(` Latest: [${F.sender}] ${F.text.slice(0,80)}`)}}else console.log(" Not found or wrong thread in inbox search")}catch(D){console.log(` Pre-send sync error: ${D.message}`)}if(b){for(let D of g.messages||[])D.status===k.CONFIRMED&&(D.status=k.NEEDS_REVIEW);l.push({name:c,status:k.NEEDS_REVIEW}),console.log(" \u2192 Skipped \u2014 draft needs review (new messages from them)")}else if($)if(await Fe(e,S,C,y,{allowDoubleMessage:!0})){for(let E of g.messages||[])E.status===k.CONFIRMED&&E.text===y&&(E.status=k.SENT,E.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",P(n),l.push({name:c,status:"sent",method:"inbox"})}else l.push({name:c,status:"failed",method:"inbox"});else a.push({name:c,conv:g,message:y,personName:S}),console.log(" \u2192 Queued for profile fallback");b&&P(n),await wt(e)}if(a.length>0){console.log(`
96
+ \u2500\u2500 [${d+1}/${r.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let v=Ne(c),S=v?.personName||c,C=v?.profileUrl||g.profileUrl||null,I=(g.messages||[]).filter(D=>!z.has(D.status)).length,b=!1,$=!1;try{await Le(e);let{verified:D}=await pe(e,S);if(D){$=!0;let E=await Q(e);if(E.length>I&&I>0){let x=E.length-I;b=!0,g.messages=le(g.messages,E),console.log(` \u26A0 ${x} new message(s) since draft was created!`);let F=E[E.length-1];console.log(` Latest: [${F.sender}] ${F.text.slice(0,80)}`)}}else console.log(" Not found or wrong thread in inbox search")}catch(D){console.log(` Pre-send sync error: ${D.message}`)}if(b){for(let D of g.messages||[])D.status===k.CONFIRMED&&(D.status=k.NEEDS_REVIEW);l.push({name:c,status:k.NEEDS_REVIEW}),console.log(" \u2192 Skipped \u2014 draft needs review (new messages from them)")}else if($)if(await Fe(e,S,C,y,{allowDoubleMessage:!0})){for(let E of g.messages||[])E.status===k.CONFIRMED&&E.text===y&&(E.status=k.SENT,E.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",P(n),l.push({name:c,status:"sent",method:"inbox"})}else l.push({name:c,status:"failed",method:"inbox"});else a.push({name:c,conv:g,message:y,personName:S}),console.log(" \u2192 Queued for profile fallback");b&&P(n),await wt(e)}if(a.length>0){console.log(`
97
97
  \u2500\u2500 Pass 2: Profile fallback (${a.length} remaining) \u2500\u2500
98
98
  `);for(let d=0;d<a.length;d++){let{name:c,conv:g,message:y,personName:v}=a[d];console.log(`
99
99
  \u2500\u2500 [profile ${d+1}/${a.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let S=ht(c,g,o);if(!S){console.error(" \u2717 No profileUrl found \u2014 cannot send via profile"),l.push({name:c,status:"failed",method:"no_url"});continue}if(await Po(e,v,S,y)){for(let T of g.messages||[])T.status===k.CONFIRMED&&T.text===y&&(T.status=k.SENT,T.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",P(n),l.push({name:c,status:"sent",method:"profile"})}else l.push({name:c,status:"failed",method:"profile"})}}console.log(`
@@ -112,7 +112,7 @@ Sending message to: ${s.personName}`),console.log(` Text: "${n.slice(0,150)}${n
112
112
  ${l} conversation(s) marked as reviewed.
113
113
  `)):console.log(`
114
114
  No conversations updated.
115
- `);return}if(e.draft||e.draftBatch){let r=e.draftBatch?e.draftBatch:[{name:e.draft.target,text:e.draft.text}];r.length===0&&(console.error("No drafts to add."),process.exit(1));let i=j(),l=J(),a=0;for(let{name:f,text:u,profileUrl:m}of r){if(!f||!u){console.error(` Skipping invalid draft: name=${f}`);continue}let p=e.draft?u.replace(/\\([!?#$])/g,"$1"):u;if(!i[f]){let c=m||null;if(!c){let g=Object.entries(l).filter(([,y])=>y.name===f);g.length===1?c=g[0][0]:g.length>1&&console.warn(` \u26A0 Multiple people named "${f}" \u2014 pass profileUrl in draft JSON to disambiguate`)}i[f]={profileUrl:c,lastSynced:new Date().toISOString(),conversationStatus:null,messages:[]},c?console.log(` New conversation \u2014 linked to ${c}`):console.warn(" \u26A0 New conversation \u2014 no profileUrl found (push will need inbox search)")}let h=i[f];h.messages||(h.messages=[]),h.messages.push({sender:ne,text:p,time:new Date().toISOString(),status:k.CONFIRMED,draftedAt:new Date().toISOString()}),h.reviewedAtPreview=h.lastMessagePreview||"";let d=h.messages.filter(c=>!ie.has(c.status)&&c.status!==k.REJECTED);console.log(` Draft added for ${f}`),console.log(` Thread: ${d.length} messages + 1 draft`),console.log(` "${p.slice(0,100)}${p.length>100?"...":""}"`),console.log(),a++}P(i),console.log(` ${a} draft(s) saved. Send all: npm run messages -- --push-drafts
115
+ `);return}if(e.draft||e.draftBatch){let r=e.draftBatch?e.draftBatch:[{name:e.draft.target,text:e.draft.text}];r.length===0&&(console.error("No drafts to add."),process.exit(1));let i=j(),l=J(),a=0;for(let{name:f,text:u,profileUrl:m}of r){if(!f||!u){console.error(` Skipping invalid draft: name=${f}`);continue}let p=e.draft?u.replace(/\\([!?#$])/g,"$1"):u;if(!i[f]){let c=m||null;if(!c){let g=Object.entries(l).filter(([,y])=>y.name===f);g.length===1?c=g[0][0]:g.length>1&&console.warn(` \u26A0 Multiple people named "${f}" \u2014 pass profileUrl in draft JSON to disambiguate`)}i[f]={profileUrl:c,lastSynced:new Date().toISOString(),conversationStatus:null,messages:[]},c?console.log(` New conversation \u2014 linked to ${c}`):console.warn(" \u26A0 New conversation \u2014 no profileUrl found (push will need inbox search)")}let h=i[f];h.messages||(h.messages=[]),h.messages.push({sender:oe,text:p,time:new Date().toISOString(),status:k.CONFIRMED,draftedAt:new Date().toISOString()}),h.reviewedAtPreview=h.lastMessagePreview||"";let d=h.messages.filter(c=>!ie.has(c.status)&&c.status!==k.REJECTED);console.log(` Draft added for ${f}`),console.log(` Thread: ${d.length} messages + 1 draft`),console.log(` "${p.slice(0,100)}${p.length>100?"...":""}"`),console.log(),a++}P(i),console.log(` ${a} draft(s) saved. Send all: npm run messages -- --push-drafts
116
116
  `);return}console.log(`
117
117
  \u{1F4E8} LinkedIn Message Bot
118
118
  `),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let t=e.read?"read":e.pushDrafts?"push-drafts":e.sendBatch?"send-batch":e.send?"send":e.full?"full":"incremental",n=ze("messages",t),{browser:o,page:s}=await tt();try{if(e.read)await Fo(s,e.read,e.verbose);else if(e.pushDrafts)await Bo(s,e.dryRun);else if(e.sendBatch)await Uo(s,e.sendBatch,e.dryRun);else if(e.send)await Lo(s,e.send.target,e.send.text,e.dryRun);else{let r=e.full?"full":"incremental";console.log(`Mode: ${r} inbox scan
@@ -1,4 +1,4 @@
1
- var de=Object.defineProperty;var q=(e,o)=>{for(var n in o)de(e,n,{get:o[n],enumerable:!0})};import"dotenv/config";import"dotenv/config";import*as i from"fs";import*as B from"os";import*as l from"path";import{fileURLToPath as Ue}from"url";var U={};q(U,{NAME:()=>me,VERSION:()=>he,up:()=>Se});import*as $ from"fs";import*as _ from"path";var he=1,me="normalize-jobs-and-questions",ge=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ye=50;function M(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function J(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 Se(e,o){let n=_.join(e,"jobs.json"),t=_.join(o,"scouted-jobs.json"),s=_.join(e,"application-questions.json"),r=M(n)||{},c=M(t)||{},E=0,d=[];for(let p of Object.keys(r)){if(!c[p])continue;let j=c[p],u=r[p];for(let A of ge)j[A]!=null&&u[A]==null&&(u[A]=j[A]);d.push(p),E++}E>0?(J(n,r),console.log(` Phase 1: Merged ${E} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=M(s);if(f&&Array.isArray(f.applications)){let p={},j=0;for(let u of f.applications){let A=u.jobId||"unknown";p[A]||(p[A]={applications:[]});let T=(u.questions||[]).map(g=>{let b={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=ye?b.options=g.options:(b.optionsOmitted=!0,j++)),g.page&&(b.page=g.page),g.wasPreFilled&&(b.wasPreFilled=!0),g.wasRetry&&(b.wasRetry=!0),b});p[A].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||T.length,questions:T})}J(s,p),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),j>0&&console.log(` Phase 2: Stripped bloated options from ${j} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(d.length>0){for(let p of d)delete c[p];J(t,c),console.log(` Phase 3: Removed ${d.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var V={};q(V,{NAME:()=>ve,VERSION:()=>be,up:()=>we});import*as w from"fs";import*as Y from"path";var be=2,ve="reset-unread-flags";function ke(e){return w.existsSync(e)?JSON.parse(w.readFileSync(e,"utf-8")):null}function $e(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{w.writeFileSync(t,n)}catch(s){try{w.unlinkSync(t)}catch{}throw s}try{w.renameSync(t,e)}catch(s){try{w.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 we(e){let o=Y.join(e,"conversations.json"),n=ke(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}$e(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}import"dotenv/config";import*as y from"path";import{fileURLToPath as je}from"url";var Ae=je(import.meta.url),Oe=y.dirname(y.dirname(Ae)),D=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(Oe,"collected-profiles"),ro=y.join(D,"people.json"),io=y.join(D,"jobs.json"),lo=y.join(D,"quota.json"),co=y.join(D,"conversations.json"),ao=y.join(D,"sync-state.json"),uo=y.join(D,"application-questions.json"),fo=y.join(D,"profile-history");var Ie=null,Re=null,Ee=null,Te=null,De=null,Ce=null;function H(){Ie=null,Re=null,Ee=null,Te=null,De=null,Ce=null}import"dotenv/config";import*as v from"path";import{fileURLToPath as xe}from"url";var Ne=xe(import.meta.url),Fe=v.dirname(v.dirname(Ne)),N=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"market-research"):v.join(Fe,"market-research"),go=v.join(N,"scouted-jobs.json"),yo=v.join(N,"discovered-people.json"),So=v.join(N,"visit-log.json"),bo=v.join(N,"companies.json"),vo=v.join(N,"job-decisions.json");function Q(){_e=null,Le=null,Pe=null,Me=null,Je=null}var _e=null;var Le=null;var Pe=null;var Me=null;var Je=null;var Ve=Ue(import.meta.url),Be=l.dirname(Ve),We=l.dirname(l.dirname(Be));function Ge(e){return e&&(e==="~"?B.homedir():e.startsWith("~/")||e.startsWith("~\\")?l.join(B.homedir(),e.slice(2)):e)}var S=process.env.DATA_DIR?l.resolve(Ge(process.env.DATA_DIR)):We,I=l.join(S,"collected-profiles"),R=l.join(S,"market-research"),m=l.join(S,".schema-version"),z=[l.join(I,".schema-version"),l.join(R,".schema-version")],L=2,O=[{version:1,module:U},{version:2,module:V}];(function(){O.sort((t,s)=>t.version-s.version);let o=new Set;for(let t of O){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=O.length?O[O.length-1].version:0;if(n!==L)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${L}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<O.length;t++){let s=t+1;if(O[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${O[t].version}`)}})();function ee(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
1
+ var he=Object.defineProperty;var Y=(e,o)=>{for(var n in o)he(e,n,{get:o[n],enumerable:!0})};import"dotenv/config";import"dotenv/config";import*as i from"fs";import*as W from"os";import*as l from"path";import{fileURLToPath as We}from"url";var V={};Y(V,{NAME:()=>ge,VERSION:()=>me,up:()=>be});import*as $ from"fs";import*as L from"path";var me=1,ge="normalize-jobs-and-questions",ye=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Se=50;function J(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function U(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 be(e,o){let n=L.join(e,"jobs.json"),t=L.join(o,"scouted-jobs.json"),s=L.join(e,"application-questions.json"),r=J(n)||{},c=J(t)||{},R=0,d=[];for(let p of Object.keys(r)){if(!c[p])continue;let j=c[p],u=r[p];for(let A of ye)j[A]!=null&&u[A]==null&&(u[A]=j[A]);d.push(p),R++}R>0?(U(n,r),console.log(` Phase 1: Merged ${R} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=J(s);if(f&&Array.isArray(f.applications)){let p={},j=0;for(let u of f.applications){let A=u.jobId||"unknown";p[A]||(p[A]={applications:[]});let T=(u.questions||[]).map(g=>{let b={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=Se?b.options=g.options:(b.optionsOmitted=!0,j++)),g.page&&(b.page=g.page),g.wasPreFilled&&(b.wasPreFilled=!0),g.wasRetry&&(b.wasRetry=!0),b});p[A].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||T.length,questions:T})}U(s,p),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),j>0&&console.log(` Phase 2: Stripped bloated options from ${j} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(d.length>0){for(let p of d)delete c[p];U(t,c),console.log(` Phase 3: Removed ${d.length} merged entries from scouted-jobs.json (${Object.keys(c).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var B={};Y(B,{NAME:()=>ke,VERSION:()=>ve,up:()=>je});import*as w from"fs";import*as H from"path";var ve=2,ke="reset-unread-flags";function $e(e){return w.existsSync(e)?JSON.parse(w.readFileSync(e,"utf-8")):null}function we(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{w.writeFileSync(t,n)}catch(s){try{w.unlinkSync(t)}catch{}throw s}try{w.renameSync(t,e)}catch(s){try{w.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 je(e){let o=H.join(e,"conversations.json"),n=$e(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}we(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}import{getPluginConfig as Ae}from"@ilivemylife/graph-sdk";var Ee=await Ae();for(let[e,o]of Object.entries(Ee))process.env[e]===void 0&&(process.env[e]=o);var lo=process.env.LINKEDIN_NAME,D=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),co=Object.freeze(new Set([D.DRAFT,D.CONFIRMED,D.NEEDS_REVIEW])),ao=Object.freeze(new Set([D.DRAFT,D.CONFIRMED,D.REJECTED,D.NEEDS_REVIEW]));import"dotenv/config";import*as y from"path";import{fileURLToPath as Ie}from"url";var Oe=Ie(import.meta.url),Re=y.dirname(y.dirname(Oe)),C=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"collected-profiles"):y.join(Re,"collected-profiles"),mo=y.join(C,"people.json"),go=y.join(C,"jobs.json"),yo=y.join(C,"quota.json"),So=y.join(C,"conversations.json"),bo=y.join(C,"sync-state.json"),vo=y.join(C,"application-questions.json"),ko=y.join(C,"profile-history");var Te=null,De=null,Ce=null,Ne=null,xe=null,Fe=null;function z(){Te=null,De=null,Ce=null,Ne=null,xe=null,Fe=null}import"dotenv/config";import*as v from"path";import{fileURLToPath as _e}from"url";var Le=_e(import.meta.url),Pe=v.dirname(v.dirname(Le)),F=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"market-research"):v.join(Pe,"market-research"),Ao=v.join(F,"scouted-jobs.json"),Eo=v.join(F,"discovered-people.json"),Io=v.join(F,"visit-log.json"),Oo=v.join(F,"companies.json"),Ro=v.join(F,"job-decisions.json");function Q(){Me=null,Je=null,Ue=null,Ve=null,Be=null}var Me=null;var Je=null;var Ue=null;var Ve=null;var Be=null;var Ge=We(import.meta.url),qe=l.dirname(Ge),Ye=l.dirname(l.dirname(qe));function He(e){return e&&(e==="~"?W.homedir():e.startsWith("~/")||e.startsWith("~\\")?l.join(W.homedir(),e.slice(2)):e)}var S=process.env.DATA_DIR?l.resolve(He(process.env.DATA_DIR)):Ye,I=l.join(S,"collected-profiles"),O=l.join(S,"market-research"),m=l.join(S,".schema-version"),K=[l.join(I,".schema-version"),l.join(O,".schema-version")],P=2,E=[{version:1,module:V},{version:2,module:B}];(function(){E.sort((t,s)=>t.version-s.version);let o=new Set;for(let t of E){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=E.length?E[E.length-1].version:0;if(n!==P)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${P}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<E.length;t++){let s=t+1;if(E[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${E[t].version}`)}})();function oe(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
2
2
  [FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
3
3
  `),process.exit(1));try{i.mkdirSync(S,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
4
4
  [FATAL] Cannot create DATA_DIR (${S}): ${o.message}`),console.error(` Fix the path or permissions and try again.
@@ -6,57 +6,57 @@ var de=Object.defineProperty;var q=(e,o)=>{for(var n in o)de(e,n,{get:o[n],enume
6
6
  [FATAL] DATA_DIR (${S}) is not accessible: ${o.message}
7
7
  `),process.exit(1)}e.isDirectory()||(console.error(`
8
8
  [FATAL] DATA_DIR (${S}) 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.
9
- `),process.exit(1));for(let o of[I,R]){let n;try{n=i.lstatSync(o)}catch(t){if(t.code==="ENOENT")continue;throw t}n.isSymbolicLink()&&(console.error(`
9
+ `),process.exit(1));for(let o of[I,O]){let n;try{n=i.lstatSync(o)}catch(t){if(t.code==="ENOENT")continue;throw t}n.isSymbolicLink()&&(console.error(`
10
10
  [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.
11
- `),process.exit(1))}}var C=l.join(S,".migration-lock");function oe(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return i.writeFileSync(C,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(i.readFileSync(C,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(c){c.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,r=1/0;if(o.startedAt){let c=Date.parse(o.startedAt);Number.isNaN(c)||(r=Date.now()-c)}t&&r<s&&(console.error(`
12
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${C}
11
+ `),process.exit(1))}}var N=l.join(S,".migration-lock");function ne(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return i.writeFileSync(N,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(i.readFileSync(N,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(c){c.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,r=1/0;if(o.startedAt){let c=Date.parse(o.startedAt);Number.isNaN(c)||(r=Date.now()-c)}t&&r<s&&(console.error(`
12
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${N}
13
13
  `),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.
14
- `),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=C+".tmp";try{return i.writeFileSync(n,e),i.renameSync(n,C),!0}catch(t){try{i.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function F(){try{if(JSON.parse(i.readFileSync(C,"utf-8")).pid!==process.pid)return;i.unlinkSync(C)}catch{}}var K=!1;function ne(){if(K)return;K=!0;let e=()=>{try{F()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function qe(){if(i.existsSync(m))return;let e=[],o=[];for(let r of z)if(i.existsSync(r))try{e.push({file:r,schema:P(r)})}catch(c){o.push({file:r,err:c.message})}if(o.length>0){console.error(`
14
+ `),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=N+".tmp";try{return i.writeFileSync(n,e),i.renameSync(n,N),!0}catch(t){try{i.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function _(){try{if(JSON.parse(i.readFileSync(N,"utf-8")).pid!==process.pid)return;i.unlinkSync(N)}catch{}}var X=!1;function te(){if(X)return;X=!0;let e=()=>{try{_()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function ze(){if(i.existsSync(m))return;let e=[],o=[];for(let r of K)if(i.existsSync(r))try{e.push({file:r,schema:M(r)})}catch(c){o.push({file:r,err:c.message})}if(o.length>0){console.error(`
15
15
  [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(`
16
16
  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.
17
17
  `),process.exit(1)}if(e.length===0)return;let n=e.map(r=>r.schema.version);if(new Set(n).size>1){console.error(`
18
18
  [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.
19
- `),process.exit(1)}let t=e[0].schema,s=m+".tmp";try{i.writeFileSync(s,JSON.stringify(t,null,2)),i.renameSync(s,m)}catch(r){try{i.unlinkSync(s)}catch{}throw r}for(let r of z)if(i.existsSync(r))try{i.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${m}`)}function Ye(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 P(e){let o=i.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function W(){if(qe(),!i.existsSync(m))return{version:0,migrations:[]};let e;try{e=P(m)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
19
+ `),process.exit(1)}let t=e[0].schema,s=m+".tmp";try{i.writeFileSync(s,JSON.stringify(t,null,2)),i.renameSync(s,m)}catch(r){try{i.unlinkSync(s)}catch{}throw r}for(let r of K)if(i.existsSync(r))try{i.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${m}`)}function Qe(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 M(e){let o=i.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function G(){if(ze(),!i.existsSync(m))return{version:0,migrations:[]};let e;try{e=M(m)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
20
20
  [FATAL] ${m} 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.
21
- `),process.exit(1)}let o=Ye(e);return o===null&&(console.error(`
21
+ `),process.exit(1)}let o=Qe(e);return o===null&&(console.error(`
22
22
  [FATAL] ${m} 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.
23
- `),process.exit(1)),o}function te(e){try{i.chmodSync(e,384)}catch{}}function He(e){if(ee(),i.existsSync(m))try{if(i.lstatSync(m).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${m}. 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=m+".tmp";try{i.writeFileSync(o,JSON.stringify(e,null,2)),te(o),i.renameSync(o,m)}catch(n){try{i.unlinkSync(o)}catch{}throw n}}function X(e,o){return i.existsSync(e)?i.readdirSync(e).filter(n=>n.endsWith(o)):[]}var Qe=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ze(e){let o=e.toLowerCase();return Qe.some(n=>n.test(o))}var Ke=6e4;function se(){let e=Date.now(),o=[];for(let n of[S,I,R]){if(!i.existsSync(n))continue;let t;try{t=i.readdirSync(n)}catch{continue}for(let s of t){if(!ze(s))continue;let r=l.join(n,s);try{let c=i.statSync(r);if(!c.isFile()||e-c.mtimeMs<Ke)continue;o.push({dir:n,file:s,fullPath:r})}catch{}}}return o}function Xe({verbose:e=!1}={}){let o=se();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let t of o)try{i.unlinkSync(t.fullPath),n++,e&&console.log(` Removed orphan: ${l.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 re(){let e=[];for(let o of[I,R])if(i.existsSync(o))for(let n of i.readdirSync(o))/\.pre-rollback-v\d+\.backup$/.test(n)&&e.push({dir:o,file:n,fullPath:l.join(o,n)});return e}function ie({removePreRollback:e=!0}={}){if(console.log(`
23
+ `),process.exit(1)),o}function se(e){try{i.chmodSync(e,384)}catch{}}function Ke(e){if(oe(),i.existsSync(m))try{if(i.lstatSync(m).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${m}. 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=m+".tmp";try{i.writeFileSync(o,JSON.stringify(e,null,2)),se(o),i.renameSync(o,m)}catch(n){try{i.unlinkSync(o)}catch{}throw n}}function Z(e,o){return i.existsSync(e)?i.readdirSync(e).filter(n=>n.endsWith(o)):[]}var Xe=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Ze(e){let o=e.toLowerCase();return Xe.some(n=>n.test(o))}var eo=6e4;function re(){let e=Date.now(),o=[];for(let n of[S,I,O]){if(!i.existsSync(n))continue;let t;try{t=i.readdirSync(n)}catch{continue}for(let s of t){if(!Ze(s))continue;let r=l.join(n,s);try{let c=i.statSync(r);if(!c.isFile()||e-c.mtimeMs<eo)continue;o.push({dir:n,file:s,fullPath:r})}catch{}}}return o}function oo({verbose:e=!1}={}){let o=re();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let t of o)try{i.unlinkSync(t.fullPath),n++,e&&console.log(` Removed orphan: ${l.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 ie(){let e=[];for(let o of[I,O])if(i.existsSync(o))for(let n of i.readdirSync(o))/\.pre-rollback-v\d+\.backup$/.test(n)&&e.push({dir:o,file:n,fullPath:l.join(o,n)});return e}function le({removePreRollback:e=!0}={}){if(console.log(`
24
24
  \u{1F4E6} Data cleanup
25
25
  `),!i.existsSync(S)){console.log(` DATA_DIR not yet created (${S}) \u2014 nothing to clean.
26
- `);return}ee();let o=!1;try{ne(),oe(),o=!0,process.on("exit",()=>{o&&F()})}catch(s){console.error(`
26
+ `);return}oe();let o=!1;try{te(),ne(),o=!0,process.on("exit",()=>{o&&_()})}catch(s){console.error(`
27
27
  [ERROR] Could not acquire cleanup lock: ${s.message}
28
- `),process.exit(1)}let n=Xe({verbose:!0}),t=0;if(e){let s=re();if(s.length===0)console.log(" No pre-rollback snapshots found.");else for(let r of s)try{i.unlinkSync(r.fullPath),t++,console.log(` Removed pre-rollback snapshot: ${l.basename(r.dir)}/${r.file}`)}catch(c){console.warn(` [!] Could not remove ${r.fullPath}: ${c.message}`)}}o&&(F(),o=!1),console.log(`
28
+ `),process.exit(1)}let n=oo({verbose:!0}),t=0;if(e){let s=ie();if(s.length===0)console.log(" No pre-rollback snapshots found.");else for(let r of s)try{i.unlinkSync(r.fullPath),t++,console.log(` Removed pre-rollback snapshot: ${l.basename(r.dir)}/${r.file}`)}catch(c){console.warn(` [!] Could not remove ${r.fullPath}: ${c.message}`)}}o&&(_(),o=!1),console.log(`
29
29
  Done. Removed ${n} orphan .tmp + ${t} pre-rollback snapshot(s).`),console.log(` NOTE: .pre-vNNN.backup files are kept \u2014 they're needed for 'rollback-data'.
30
- `)}function Ze(){let e=[];for(let o of[I,R]){if(!i.existsSync(o))continue;let n=i.readdirSync(o).filter(t=>{let s=t.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let t of n){let s=l.join(o,t);try{P(s)}catch(r){e.push({dir:l.basename(o),file:t,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Z(e,o){let n=o+".tmp";try{i.copyFileSync(e,n),te(n)}catch(t){try{i.unlinkSync(n)}catch{}throw t}try{i.renameSync(n,o)}catch(t){try{i.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}}function le(){console.log(`
30
+ `)}function no(){let e=[];for(let o of[I,O]){if(!i.existsSync(o))continue;let n=i.readdirSync(o).filter(t=>{let s=t.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let t of n){let s=l.join(o,t);try{M(s)}catch(r){e.push({dir:l.basename(o),file:t,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ee(e,o){let n=o+".tmp";try{i.copyFileSync(e,n),se(n)}catch(t){try{i.unlinkSync(n)}catch{}throw t}try{i.renameSync(n,o)}catch(t){try{i.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}}function ce(){console.log(`
31
31
  \u{1F4E6} Migration status
32
- `);let e=W();if(console.log(` Data root: ${S}`),console.log(` Schema file: ${m}${i.existsSync(m)?"":" (not yet created \u2014 fresh install)"}`),console.log(` Current version: v${e.version}`),e.migrations?.length){console.log(" Applied migrations:");for(let r of e.migrations){if(!r||typeof r!="object"){console.log(` (malformed entry: ${JSON.stringify(r)})`);continue}let c=String(r.version??"?").padStart(3,"0");console.log(` v${c} \u2014 ${r.name??"(no name)"} (at ${r.appliedAt??"?"})`)}}e.rolledBackAt&&console.log(` Last rollback: ${e.rolledBackAt}`);for(let[r,c]of[["collected-profiles",I],["market-research",R]]){if(!i.existsSync(c))continue;let E=i.readdirSync(c).filter(d=>/\.pre-v\d+\.backup$/.test(d));if(E.length){let d=[...new Set(E.map(f=>f.match(/\.pre-v(\d+)\.backup$/)[1]))].sort();console.log(` Pre-migration backups in ${r}/: ${d.map(f=>`v${f} (${E.filter(p=>p.includes(`pre-v${f}`)).length} files)`).join(", ")}`)}}let o=re();o.length>0&&console.log(` Pre-rollback snapshots: ${o.length} file(s) (run 'data-cleanup' to remove)`);let n=se();if(n.length>0){console.log(` Orphan .tmp files: ${n.length} (will be cleaned on next plugin run, or now via 'data-cleanup')`);for(let r of n)console.log(` ${l.basename(r.dir)}/${r.file}`)}console.log(),console.log(` Latest available schema: v${L}`);let t=O.filter(r=>r.version>e.version);t.length?(console.log(` Pending: ${t.map(r=>`v${String(r.version).padStart(3,"0")}`).join(", ")}`),console.log(" Run any plugin command (e.g. 'ilml linkedin today') to apply pending migrations.")):console.log(" \u2713 Up to date."),console.log();let s=Ze();if(s.ok)console.log(" Data integrity: \u2713 all JSON files parse cleanly");else{console.log(` Data integrity: \u2717 ${s.broken.length} file(s) corrupted:`);for(let r of s.broken)console.log(` ${r.dir}/${r.file}: ${r.err}`);console.log(" Migrations will refuse to run until these are repaired.")}console.log()}async function ce({confirmed:e=!1}={}){let n=W().version;if(n===0){console.log(`
32
+ `);let e=G();if(console.log(` Data root: ${S}`),console.log(` Schema file: ${m}${i.existsSync(m)?"":" (not yet created \u2014 fresh install)"}`),console.log(` Current version: v${e.version}`),e.migrations?.length){console.log(" Applied migrations:");for(let r of e.migrations){if(!r||typeof r!="object"){console.log(` (malformed entry: ${JSON.stringify(r)})`);continue}let c=String(r.version??"?").padStart(3,"0");console.log(` v${c} \u2014 ${r.name??"(no name)"} (at ${r.appliedAt??"?"})`)}}e.rolledBackAt&&console.log(` Last rollback: ${e.rolledBackAt}`);for(let[r,c]of[["collected-profiles",I],["market-research",O]]){if(!i.existsSync(c))continue;let R=i.readdirSync(c).filter(d=>/\.pre-v\d+\.backup$/.test(d));if(R.length){let d=[...new Set(R.map(f=>f.match(/\.pre-v(\d+)\.backup$/)[1]))].sort();console.log(` Pre-migration backups in ${r}/: ${d.map(f=>`v${f} (${R.filter(p=>p.includes(`pre-v${f}`)).length} files)`).join(", ")}`)}}let o=ie();o.length>0&&console.log(` Pre-rollback snapshots: ${o.length} file(s) (run 'data-cleanup' to remove)`);let n=re();if(n.length>0){console.log(` Orphan .tmp files: ${n.length} (will be cleaned on next plugin run, or now via 'data-cleanup')`);for(let r of n)console.log(` ${l.basename(r.dir)}/${r.file}`)}console.log(),console.log(` Latest available schema: v${P}`);let t=E.filter(r=>r.version>e.version);t.length?(console.log(` Pending: ${t.map(r=>`v${String(r.version).padStart(3,"0")}`).join(", ")}`),console.log(" Run any plugin command (e.g. 'ilml linkedin today') to apply pending migrations.")):console.log(" \u2713 Up to date."),console.log();let s=no();if(s.ok)console.log(" Data integrity: \u2713 all JSON files parse cleanly");else{console.log(` Data integrity: \u2717 ${s.broken.length} file(s) corrupted:`);for(let r of s.broken)console.log(` ${r.dir}/${r.file}: ${r.err}`);console.log(" Migrations will refuse to run until these are repaired.")}console.log()}async function ae({confirmed:e=!1}={}){let n=G().version;if(n===0){console.log(`
33
33
  No migrations applied \u2014 nothing to roll back.
34
- `);return}let t=!1,s=`.pre-v${String(n).padStart(3,"0")}.backup`,r=X(I,s),c=X(R,s);if(r.length+c.length===0&&(console.error(`
34
+ `);return}let t=!1,s=`.pre-v${String(n).padStart(3,"0")}.backup`,r=Z(I,s),c=Z(O,s);if(r.length+c.length===0&&(console.error(`
35
35
  [ERROR] No backup files (${s}) found in either data directory.`),console.error(` Cannot roll back v${n} \u2014 backups may have been deleted.
36
36
  `),process.exit(1)),!e){console.log(`
37
37
  \u26A0 rollback-data ONLY rolls back DATA, NOT the plugin code.
38
38
  `),console.log(" The full rollback is a TWO-STEP procedure. Doing only step 1 leaves you"),console.log(` in a broken state where the next plugin run will re-apply the migration.
39
39
  `),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` STEP 1 (this command): roll back DATA schema v${n} \u2192 v${n-1}`),console.log(" STEP 2 (you, after): roll back CODE ilml plugin install linkedin@<previous>"),console.log(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
40
- `),console.log(" Between step 1 and step 2: DO NOT run any 'ilml linkedin' command."),console.log(` The current plugin (CURRENT_SCHEMA_VERSION=${L}) will see your data on v${n-1}`),console.log(` and immediately re-apply migration v${n}, undoing this rollback.
40
+ `),console.log(" Between step 1 and step 2: DO NOT run any 'ilml linkedin' command."),console.log(` The current plugin (CURRENT_SCHEMA_VERSION=${P}) will see your data on v${n-1}`),console.log(` and immediately re-apply migration v${n}, undoing this rollback.
41
41
  `),console.log(" This step 1 will also:"),console.log(" - OVERWRITE current data with the pre-migration backup"),console.log(` (${r.length} files in collected-profiles/, ${c.length} in market-research/)`),console.log(` - Permanently LOSE any data changes made after migration v${n}`),console.log(" (new conversations synced, drafts written, notes added \u2014 all gone)"),console.log(` - Snapshot current state to *.pre-rollback-v${String(n).padStart(3,"0")}.backup before overwriting
42
42
  `),console.log(" If you only need to inspect old data without downgrading the plugin,"),console.log(" copy your DATA_DIR somewhere else and use that copy instead \u2014 leaves your"),console.log(` live setup untouched.
43
43
  `),console.log(" Proceed with step 1? Re-run with --confirm:"),console.log(" npm run rollback:data -- --confirm"),console.log(` ilml linkedin rollback-data --confirm
44
- `);return}ne(),oe(),t=!0,process.on("exit",()=>{t&&F()});let d=`.pre-rollback-v${String(n).padStart(3,"0")}.backup`,f=[],p=0;for(let a of[I,R]){if(!i.existsSync(a))continue;let x;try{x=i.readdirSync(a).filter(h=>{let k=h.toLowerCase();if(k.includes(".backup")||k===".schema-version"||k.endsWith(".tmp"))return!1;try{return i.statSync(l.join(a,h)).isFile()}catch{return!1}})}catch(h){f.push(`${l.basename(a)}: ${h.message}`);continue}for(let h of x)try{Z(l.join(a,h),l.join(a,h+d)),p++}catch(k){f.push(`${l.basename(a)}/${h}: ${k.message}`)}}if(f.length>0){console.error(`
44
+ `);return}te(),ne(),t=!0,process.on("exit",()=>{t&&_()});let d=`.pre-rollback-v${String(n).padStart(3,"0")}.backup`,f=[],p=0;for(let a of[I,O]){if(!i.existsSync(a))continue;let x;try{x=i.readdirSync(a).filter(h=>{let k=h.toLowerCase();if(k.includes(".backup")||k===".schema-version"||k.endsWith(".tmp"))return!1;try{return i.statSync(l.join(a,h)).isFile()}catch{return!1}})}catch(h){f.push(`${l.basename(a)}: ${h.message}`);continue}for(let h of x)try{ee(l.join(a,h),l.join(a,h+d)),p++}catch(k){f.push(`${l.basename(a)}/${h}: ${k.message}`)}}if(f.length>0){console.error(`
45
45
  [FATAL] ${f.length} file(s) could not be snapshotted:`);for(let a of f)console.error(` ${a}`);console.error(`
46
46
  Aborting rollback \u2014 without a complete snapshot of your CURRENT state, a`),console.error(' "change your mind" recovery would silently lose the data you have NOW.'),console.error(` Your current data is unchanged. Pre-rollback snapshots created so far: *${d}`),console.error(" (run 'data-cleanup' to remove them, or retry the rollback once the underlying"),console.error(` issue is resolved \u2014 usually a transient file lock from antivirus or an editor).
47
- `),process.exit(1)}console.log(` Snapshotted ${p} files \u2192 *${d} (in case you change your mind)`);let j=[],u=[];for(let[a,x]of[[I,r],[R,c]])for(let h of x){let k=l.join(a,h),G=h.slice(0,-s.length),fe=l.join(a,G);try{G.toLowerCase().endsWith(".json")?P(k):i.accessSync(k,i.constants.R_OK),j.push({backupPath:k,originalPath:fe,fileName:h})}catch(pe){u.push({file:h,dir:l.basename(a),err:pe.message})}}if(u.length>0){console.error(`
47
+ `),process.exit(1)}console.log(` Snapshotted ${p} files \u2192 *${d} (in case you change your mind)`);let j=[],u=[];for(let[a,x]of[[I,r],[O,c]])for(let h of x){let k=l.join(a,h),q=h.slice(0,-s.length),pe=l.join(a,q);try{q.toLowerCase().endsWith(".json")?M(k):i.accessSync(k,i.constants.R_OK),j.push({backupPath:k,originalPath:pe,fileName:h})}catch(de){u.push({file:h,dir:l.basename(a),err:de.message})}}if(u.length>0){console.error(`
48
48
  [ERROR] ${u.length} backup file(s) are corrupted or unreadable:`);for(let a of u)console.error(` ${a.dir}/${a.file}: ${a.err}`);console.error(`
49
49
  Aborting rollback BEFORE touching any original file \u2014`),console.error(" partial restore would leave the DB in an inconsistent state."),console.error(` Your current data is unchanged. Pre-rollback snapshots: *${d}
50
50
  `),console.error(" Options:"),console.error(" - Restore the corrupted backup(s) from another source and re-run rollback"),console.error(` - Or accept the new schema and don't roll back
51
51
  `),process.exit(1)}j.length===0&&(console.error(`
52
52
  [ERROR] No backup files found to restore. Aborting.
53
- `),process.exit(1));let A=new Date().toISOString(),T=W();T.version=n-1,T.migrations=(T.migrations||[]).filter(a=>a&&Number.isInteger(a.version)&&a.version<n),T.rolledBackAt=A,He(T);let g=0,b=[];for(let{backupPath:a,originalPath:x,fileName:h}of j)try{Z(a,x),g++}catch(k){b.push({fileName:h,err:k.message})}if(b.length>0){console.error(`
53
+ `),process.exit(1));let A=new Date().toISOString(),T=G();T.version=n-1,T.migrations=(T.migrations||[]).filter(a=>a&&Number.isInteger(a.version)&&a.version<n),T.rolledBackAt=A,Ke(T);let g=0,b=[];for(let{backupPath:a,originalPath:x,fileName:h}of j)try{ee(a,x),g++}catch(k){b.push({fileName:h,err:k.message})}if(b.length>0){console.error(`
54
54
  [WARNING] ${b.length} file(s) could not be restored:`);for(let a of b)console.error(` ${a.fileName}: ${a.err}`);console.error(`
55
55
  Schema has been lowered to v${n-1} but data is in a mixed state:`),console.error(` ${g} files restored from backup`),console.error(` ${b.length} files still in their post-migration form`),console.error(` The next plugin run will detect pending migration v${n} and re-apply it,`),console.error(" re-converging the data \u2014 but if you intended to roll back, that's not what you want."),console.error(` Manual fix: copy the missing *${s} files back over their originals, then`),console.error(" re-run 'rollback-data --confirm' to redo the rollback. Pre-rollback snapshots"),console.error(` (*${d}) are still on disk if you'd rather restore the v${n} state.
56
- `),process.exit(1)}try{H()}catch{}try{Q()}catch{}F(),t=!1,console.log(`
56
+ `),process.exit(1)}try{z()}catch{}try{Q()}catch{}_(),t=!1,console.log(`
57
57
  \u2713 STEP 1 DONE. Restored ${g} files. Data schema is now at v${n-1}.
58
58
  `),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(" \u26A0 STEP 2 REQUIRED \u2014 DO NOT RUN ANY 'ilml linkedin' COMMAND UNTIL"),console.log(` YOU DOWNGRADE THE PLUGIN CODE, or migration v${n} will be re-applied`),console.log(" and this rollback will be silently undone."),console.log(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
59
59
  `),console.log(" Run NOW (or as soon as possible):"),console.log(` ilml plugin install linkedin@<previous-version>
60
60
  `),console.log(` If something looks wrong, your pre-rollback snapshot is in *${d} files`),console.log(` \u2014 copy them back manually to undo this rollback.
61
- `)}var ue=process.argv.slice(2),ae=ue[0],eo=ue.includes("--confirm");async function oo(){switch(ae){case"status":le();break;case"rollback-data":await ce({confirmed:eo});break;case"data-cleanup":ie();break;default:console.log("Usage:"),console.log(" node migrationCli.mjs status Show schema state + leftover files"),console.log(" node migrationCli.mjs data-cleanup Remove .tmp orphans + pre-rollback snapshots"),console.log(" node migrationCli.mjs rollback-data Preview data rollback (read-only)"),console.log(" node migrationCli.mjs rollback-data --confirm Actually roll back data"),console.log(""),console.log("Note: rollback-data only touches DATA. To roll back the plugin code as well,"),console.log("also run: ilml plugin install linkedin@<previous-version>"),process.exit(ae?1:0)}}oo().catch(e=>{console.error(`
61
+ `)}var fe=process.argv.slice(2),ue=fe[0],to=fe.includes("--confirm");async function so(){switch(ue){case"status":ce();break;case"rollback-data":await ae({confirmed:to});break;case"data-cleanup":le();break;default:console.log("Usage:"),console.log(" node migrationCli.mjs status Show schema state + leftover files"),console.log(" node migrationCli.mjs data-cleanup Remove .tmp orphans + pre-rollback snapshots"),console.log(" node migrationCli.mjs rollback-data Preview data rollback (read-only)"),console.log(" node migrationCli.mjs rollback-data --confirm Actually roll back data"),console.log(""),console.log("Note: rollback-data only touches DATA. To roll back the plugin code as well,"),console.log("also run: ilml plugin install linkedin@<previous-version>"),process.exit(ue?1:0)}}so().catch(e=>{console.error(`
62
62
  [ERROR]`,e.message),process.env.VERBOSE&&console.error(e.stack),process.exit(1)});
@@ -1,9 +1,9 @@
1
- import"dotenv/config";import*as p from"fs";import*as g from"path";import"dotenv/config";import*as r from"fs";import*as i from"path";import{fileURLToPath as F}from"url";var T=F(import.meta.url),x=i.dirname(i.dirname(T)),u=process.env.DATA_DIR?i.resolve(process.env.DATA_DIR,"collected-profiles"):i.join(x,"collected-profiles"),k=i.join(u,"people.json"),W=i.join(u,"jobs.json"),q=i.join(u,"quota.json"),H=i.join(u,"conversations.json"),Q=i.join(u,"sync-state.json"),B=i.join(u,"application-questions.json"),E=i.join(u,"profile-history");var y=null;function _(){r.existsSync(u)||r.mkdirSync(u,{recursive:!0})}function D(e,o){if(!r.existsSync(e))return null;try{let s=JSON.parse(r.readFileSync(e,"utf-8"));try{r.copyFileSync(e,e+".backup")}catch{}return s}catch(s){console.error(`[!] ${o} is corrupted: ${s.message}`),console.error(` File: ${i.resolve(e)}`);let t=e+".backup";if(r.existsSync(t))try{let n=JSON.parse(r.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{r.copyFileSync(t,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{r.copyFileSync(e,e+".corrupted")}catch{}return null}}function h(e){if(!e)return null;let o=e.match(/\/in\/([^/?#]+)/);return o?o[1].toLowerCase():null}function v(e){let o=h(e);return o?i.join(E,`${o}.json`):null}function A(e){let o=v(e);return o?D(o,`profile-history/${h(e)}.json`)||[]:[]}function m(){return y||(_(),y=D(k,"people.json")||{},y)}var j=process.argv.slice(2),R=j.includes("--all"),$=j.find(e=>e.startsWith("--since="))?.split("=")[1]||null,d=j.find(e=>e.startsWith("--field="))?.split("=")[1]||null,O=j.find(e=>!e.startsWith("--"))||null,N=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(process.cwd(),"collected-profiles"),S=g.join(N,"profile-history");function I(){return p.existsSync(S)?p.readdirSync(S).filter(e=>e.endsWith(".json")).map(e=>e.replace(/\.json$/,"")):[]}function L(e){let o=m();for(let s of Object.keys(o))if(h(s)===e)return s;return null}function J(e){let o=e.startsWith("http")?h(e):e.toLowerCase();if(!o){console.log("Could not derive slug");return}let s=L(o),t=m(),n=s?t[s]:null,a=s?A(s):(()=>{let l=g.join(S,`${o}.json`);return p.existsSync(l)?JSON.parse(p.readFileSync(l,"utf-8")):[]})();console.log(`
1
+ import"dotenv/config";import*as p from"fs";import*as g from"path";import{getPluginConfig as F}from"@ilivemylife/graph-sdk";var T=await F();for(let[e,o]of Object.entries(T))process.env[e]===void 0&&(process.env[e]=o);var H=process.env.LINKEDIN_NAME,h=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Q=Object.freeze(new Set([h.DRAFT,h.CONFIRMED,h.NEEDS_REVIEW])),Y=Object.freeze(new Set([h.DRAFT,h.CONFIRMED,h.REJECTED,h.NEEDS_REVIEW]));import"dotenv/config";import*as r from"fs";import*as i from"path";import{fileURLToPath as R}from"url";var x=R(import.meta.url),_=i.dirname(i.dirname(x)),u=process.env.DATA_DIR?i.resolve(process.env.DATA_DIR,"collected-profiles"):i.join(_,"collected-profiles"),v=i.join(u,"people.json"),X=i.join(u,"jobs.json"),Z=i.join(u,"quota.json"),ee=i.join(u,"conversations.json"),ne=i.join(u,"sync-state.json"),oe=i.join(u,"application-questions.json"),k=i.join(u,"profile-history");var j=null;function N(){r.existsSync(u)||r.mkdirSync(u,{recursive:!0})}function A(e,o){if(!r.existsSync(e))return null;try{let s=JSON.parse(r.readFileSync(e,"utf-8"));try{r.copyFileSync(e,e+".backup")}catch{}return s}catch(s){console.error(`[!] ${o} is corrupted: ${s.message}`),console.error(` File: ${i.resolve(e)}`);let t=e+".backup";if(r.existsSync(t))try{let n=JSON.parse(r.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{r.copyFileSync(t,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{r.copyFileSync(e,e+".corrupted")}catch{}return null}}function S(e){if(!e)return null;let o=e.match(/\/in\/([^/?#]+)/);return o?o[1].toLowerCase():null}function L(e){let o=S(e);return o?i.join(k,`${o}.json`):null}function E(e){let o=L(e);return o?A(o,`profile-history/${S(e)}.json`)||[]:[]}function m(){return j||(N(),j=A(v,"people.json")||{},j)}var b=process.argv.slice(2),M=b.includes("--all"),w=b.find(e=>e.startsWith("--since="))?.split("=")[1]||null,d=b.find(e=>e.startsWith("--field="))?.split("=")[1]||null,I=b.find(e=>!e.startsWith("--"))||null,J=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(process.cwd(),"collected-profiles"),y=g.join(J,"profile-history");function O(){return p.existsSync(y)?p.readdirSync(y).filter(e=>e.endsWith(".json")).map(e=>e.replace(/\.json$/,"")):[]}function P(e){let o=m();for(let s of Object.keys(o))if(S(s)===e)return s;return null}function V(e){let o=e.startsWith("http")?S(e):e.toLowerCase();if(!o){console.log("Could not derive slug");return}let s=P(o),t=m(),n=s?t[s]:null,a=s?E(s):(()=>{let l=g.join(y,`${o}.json`);return p.existsSync(l)?JSON.parse(p.readFileSync(l,"utf-8")):[]})();console.log(`
2
2
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` ${n?.name||"(unknown)"} \u2014 ${o}`),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
3
3
  `),n&&(console.log("CURRENT:"),console.log(` title: ${n.title||"(null)"}`),console.log(` location: ${n.location||"(null)"}`),console.log(` currentCompany: ${n.currentCompany||"(null)"}`),console.log(` connectionDeg: ${n.connectionDegree||"(null)"}`),console.log(` openToWork: ${n.openToWork}`),console.log(` hiring: ${n.hiring}`),console.log(` lastUpdated: ${n.lastUpdated||"(null)"}`),console.log(` lastSnapshotAt: ${n.lastSnapshotAt||"(null)"}`)),console.log(`
4
4
  HISTORY (${a.length} snapshot${a.length===1?"":"s"}):
5
- `);for(let l of a){if(console.log(` ${l.capturedAt} changed: [${(l.changedFields||[]).join(", ")}]`),l.snapshot)for(let c of l.changedFields||[]){let f=l.snapshot[c],b=n?n[c]:"?",C=w=>Array.isArray(w)?w.join(", "):w??"(null)";console.log(` ${c.padEnd(18)} OLD: ${C(f)}`),console.log(` ${" ".repeat(18)} NEW: ${C(b)}`)}console.log()}}function M(){let e=I();console.log(`
5
+ `);for(let l of a){if(console.log(` ${l.capturedAt} changed: [${(l.changedFields||[]).join(", ")}]`),l.snapshot)for(let c of l.changedFields||[]){let f=l.snapshot[c],C=n?n[c]:"?",$=D=>Array.isArray(D)?D.join(", "):D??"(null)";console.log(` ${c.padEnd(18)} OLD: ${$(f)}`),console.log(` ${" ".repeat(18)} NEW: ${$(C)}`)}console.log()}}function W(){let e=O();console.log(`
6
6
  ${e.length} profiles have history files:
7
- `);let o=m(),s=[];for(let t of e){let n=Object.keys(o).find(f=>h(f)===t),a=n?o[n]:null,l=g.join(S,`${t}.json`),c=JSON.parse(p.readFileSync(l,"utf-8"));s.push({slug:t,name:a?.name||"(unknown)",snapshots:c.length,mostRecentChange:c[0]?.capturedAt||null,mostRecentFields:c[0]?.changedFields?.join(", ")||""})}s.sort((t,n)=>(n.mostRecentChange||"").localeCompare(t.mostRecentChange||""));for(let t of s)console.log(` ${t.mostRecentChange?.slice(0,10)||"----------"} ${t.snapshots}\xD7 ${t.name.padEnd(28)} [${t.mostRecentFields}]`)}function P(){let e=I(),o=new Date($).getTime(),s=m(),t=[];for(let n of e){let a=g.join(S,`${n}.json`),l=JSON.parse(p.readFileSync(a,"utf-8"));for(let c of l){if(new Date(c.capturedAt).getTime()<o||d&&!(c.changedFields||[]).includes(d))continue;let f=Object.keys(s).find(b=>h(b)===n);t.push({date:c.capturedAt,slug:n,name:(f?s[f]:null)?.name||"(unknown)",fields:(c.changedFields||[]).join(", "),...d?{oldValue:c.snapshot?.[d],newValue:(f?s[f]:null)?.[d]}:{}})}}t.sort((n,a)=>a.date.localeCompare(n.date)),console.log(`
8
- ${t.length} change events since ${$}${d?` (field=${d})`:""}:
9
- `);for(let n of t)if(console.log(` ${n.date.slice(0,10)} ${n.name.padEnd(28)} [${n.fields}]`),d){let a=l=>Array.isArray(l)?l.join(", "):l??"(null)";console.log(` OLD: ${a(n.oldValue)}`),console.log(` NEW: ${a(n.newValue)}`)}}O?J(O):R?M():$?P():(console.log("Usage:"),console.log(" node profileHistory.mjs <slug-or-url>"),console.log(" node profileHistory.mjs --all"),console.log(" node profileHistory.mjs --since=YYYY-MM-DD [--field=NAME]"));
7
+ `);let o=m(),s=[];for(let t of e){let n=Object.keys(o).find(f=>S(f)===t),a=n?o[n]:null,l=g.join(y,`${t}.json`),c=JSON.parse(p.readFileSync(l,"utf-8"));s.push({slug:t,name:a?.name||"(unknown)",snapshots:c.length,mostRecentChange:c[0]?.capturedAt||null,mostRecentFields:c[0]?.changedFields?.join(", ")||""})}s.sort((t,n)=>(n.mostRecentChange||"").localeCompare(t.mostRecentChange||""));for(let t of s)console.log(` ${t.mostRecentChange?.slice(0,10)||"----------"} ${t.snapshots}\xD7 ${t.name.padEnd(28)} [${t.mostRecentFields}]`)}function U(){let e=O(),o=new Date(w).getTime(),s=m(),t=[];for(let n of e){let a=g.join(y,`${n}.json`),l=JSON.parse(p.readFileSync(a,"utf-8"));for(let c of l){if(new Date(c.capturedAt).getTime()<o||d&&!(c.changedFields||[]).includes(d))continue;let f=Object.keys(s).find(C=>S(C)===n);t.push({date:c.capturedAt,slug:n,name:(f?s[f]:null)?.name||"(unknown)",fields:(c.changedFields||[]).join(", "),...d?{oldValue:c.snapshot?.[d],newValue:(f?s[f]:null)?.[d]}:{}})}}t.sort((n,a)=>a.date.localeCompare(n.date)),console.log(`
8
+ ${t.length} change events since ${w}${d?` (field=${d})`:""}:
9
+ `);for(let n of t)if(console.log(` ${n.date.slice(0,10)} ${n.name.padEnd(28)} [${n.fields}]`),d){let a=l=>Array.isArray(l)?l.join(", "):l??"(null)";console.log(` OLD: ${a(n.oldValue)}`),console.log(` NEW: ${a(n.newValue)}`)}}I?V(I):M?W():w?U():(console.log("Usage:"),console.log(" node profileHistory.mjs <slug-or-url>"),console.log(" node profileHistory.mjs --all"),console.log(" node profileHistory.mjs --since=YYYY-MM-DD [--field=NAME]"));