ilml-plugin-linkedin 1.11.4 → 1.11.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,120 +1,120 @@
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(`
1
+ var $t=Object.defineProperty;var ye=(e,t)=>{for(var s in t)$t(e,s,{get:t[s],enumerable:!0})};import*as oe from"fs";import*as vt from"readline";var we={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},kt={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function ie(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let s=parseInt(t[1],10),o=parseInt(t[2],10),n=t[3].toUpperCase()==="PM";return n&&s!==12&&(s+=12),!n&&s===12&&(s=0),{hours:s,minutes:o}}function Se(e,t){if(!e)return null;let s=e.trim();if(!s)return null;if(t=t||new Date,/^just\s*now$/i.test(s))return t.toISOString();if(/^today\b/i.test(s)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(s)){let l=ie(s),a=new Date(t);return l?a.setHours(l.hours,l.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=s.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=kt[o[1].toLowerCase()],a=ie(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 n=s.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(n){let l=we[n[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(n[2],10),f=parseInt(n[3],10),u=ie(n[4]||"");return new Date(f,l,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let r=s.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=we[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(r[2],10),f=ie(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=s.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=we[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(i[2],10),f=ie(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 T(e){let t=Math.floor(Math.random()*2001),s=e+t;return new Promise(o=>setTimeout(o,s))}async function Be(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 T(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 qe(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 Je(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 Et}from"@ilivemylife/graph-sdk";var Ct=await Et();for(let[e,t]of Object.entries(Ct))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"}),le=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 O from"fs";import*as _ from"path";import{fileURLToPath as Dt}from"url";var At=Dt(import.meta.url),Tt=_.dirname(_.dirname(At)),V=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"collected-profiles"):_.join(Tt,"collected-profiles"),ve=_.join(V,"people.json"),un=_.join(V,"jobs.json"),fn=_.join(V,"quota.json"),fe=_.join(V,"conversations.json"),dn=_.join(V,"sync-state.json"),pn=_.join(V,"application-questions.json"),mn=_.join(V,"profile-history");var se=null,Rt=null,xt=null,Q=null,It=null,Ot=null;function We(){se=null,Rt=null,xt=null,Q=null,It=null,Ot=null}function de(){O.existsSync(V)||O.mkdirSync(V,{recursive:!0})}function be(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";O.writeFileSync(o,s);for(let n=0;n<3;n++)try{O.renameSync(o,e);return}catch(r){if(n<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function He(e,t){if(!O.existsSync(e))return null;try{let s=JSON.parse(O.readFileSync(e,"utf-8"));try{O.copyFileSync(e,e+".backup")}catch{}return s}catch(s){console.error(`[!] ${t} is corrupted: ${s.message}`),console.error(` File: ${_.resolve(e)}`);let o=e+".backup";if(O.existsSync(o))try{let n=JSON.parse(O.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{O.copyFileSync(o,e)}catch{}return n}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 W(){return se||(de(),se=He(ve,"people.json")||{},se)}function pe(e){de(),se=e;try{be(ve,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${_.resolve(ve)}`)}}function j(){return Q||(de(),Q=He(fe,"conversations.json")||{},_t(Q),Q)}function _t(e){let t=0;for(let s of Object.values(e)){if(!(s.draftStatus!==void 0||s.draftPreparedAt!==void 0))continue;let n=(s.messages||[]).find(r=>r.status==="draft");n&&s.draftStatus&&s.draftStatus!=="pending"&&(n.status=s.draftStatus),delete s.draftStatus,delete s.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{be(fe,e)}catch{}}}function P(e){de(),Q=e;try{be(fe,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${_.resolve(fe)}`)}}import"dotenv/config";import*as U from"fs";import*as G from"path";import{fileURLToPath as Lt}from"url";import"dotenv/config";import{createGraphClient as jt,resolveToken as Nt}from"@ilivemylife/graph-sdk";import{config as Mt}from"dotenv";Mt();var Ve=Nt()||process.env.TOKEN;Ve||(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
5
- `),process.exit(1));var He=It({token:We});function jt(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Mt({scriptName:e,mode:t,status:n,error:o,duration:s}){let r=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${jt(s)}`:"",a=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",f=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${f} \u2014 ${a} \u2014 ${i}${l}`}async function Ve({scriptName:e,mode:t,status:n,summaryLines:o,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let a=`**${Mt({scriptName:e,mode:t,status:n,error:s,duration:r})}**
5
+ `),process.exit(1));var Ye=jt({token:Ve});function Ft(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60),o=t%60;return o?`${s}m ${o}s`:`${s}m`}function Pt({scriptName:e,mode:t,status:s,error:o,duration:n}){let r=s==="error"?"\u2717":s==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=n?` ${Ft(n)}`:"",a=s==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:s==="quota-reached"?"daily quota reached":"done",f=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${f} \u2014 ${a} \u2014 ${i}${l}`}async function Ge({scriptName:e,mode:t,status:s,summaryLines:o,error:n,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let a=`**${Pt({scriptName:e,mode:t,status:s,error:n,duration:r})}**
6
6
 
7
7
  ${o.join(`
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
- 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(`
8
+ `)}`;try{await Ye.addMessage(i,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Ut=Lt(import.meta.url),Bt=G.dirname(G.dirname(Ut)),$e=process.env.DATA_DIR?G.resolve(process.env.DATA_DIR,"collected-profiles"):G.join(Bt,"collected-profiles"),ke=G.join($e,"run-log.json");function qt(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";U.writeFileSync(o,s);for(let n=0;n<3;n++)try{U.renameSync(o,e);return}catch(r){if(n<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function ze(){try{if(!U.existsSync(ke))return{runs:[]};let e=JSON.parse(U.readFileSync(ke,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ke(e){U.existsSync($e)||U.mkdirSync($e,{recursive:!0});try{qt(ke,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Qe(e,t="default"){let s=ze();for(let i of s.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,n={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};s.runs.push(n);let r=Date.now()-30*24*60*60*1e3;return s.runs=s.runs.filter(i=>new Date(i.timestamp).getTime()>r),Ke(s),{script:e,mode:t,startTime:o.getTime(),runIndex:s.runs.length-1}}function Ee(e,t,s=null,o=null){if(!e)return;let n=null;try{let i=ze(),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=s,l.error=o,n=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=s,a.error=o,n=a.duration)}Ke(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=s&&Array.isArray(s.summaryLines)?s.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":s&&s.dailyLimitHit?"quota-reached":"done";Ge({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:o,duration:n??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import Vt from"puppeteer";import{addExtra as Yt}from"puppeteer-extra";import Gt from"puppeteer-extra-plugin-stealth";import Xe from"fs";import Jt from"path";var Wt="cookies.json";function Ht(){let e=process.env.ILML_SCOPE_DIR;return e?Jt.join(e,"plugins-state","linkedin","cookies.json"):Wt}function Ze(){let e=Ht();if(!Xe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Xe.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let s;try{s=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(s)||s.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return s}var ot=Yt(Vt);ot.use(Gt());async function nt(){let e=await ot.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
9
+ Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let s=await e.newPage();await s.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=Ze();await s.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=>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(`
11
+ `),await e.close(),process.exit(1)}return{browser:e,page:s}}async function De(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await T(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 T(3e3)}console.log(" Inbox loaded.")}async function st(e){let t=await e.evaluate(()=>{let s=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let n of s){let i=n.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let a=n.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=n.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",m=n.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||n.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=n.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 s of t)s.lastMessageTime=Se(s.lastMessageTime)||s.lastMessageTime;return t}async function rt(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 n=document.querySelector(o);if(n&&n.scrollHeight>n.clientHeight)return n.scrollBy(0,600),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight}}let s=document.querySelector(".msg-conversation-listitem");if(s){let o=s.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 zt(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,s=['.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 n of s){let r=document.querySelector(n);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 n of o){let r=n.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function et(e,t){let s=await zt(e);if(!s)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),n=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=s.toLowerCase();return{match:r.includes(o)||n.some(l=>r.includes(l)),headerName:s}}async function Ce(e,t){let s=t.split(" ")[0],o=8e3,n=500,r=0;for(;r<o;){let{match:a,headerName:f}=await et(e,t);if(a)return await T(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(s.toLowerCase())))return await T(300),{verified:!0,headerName:s};await T(n),r+=n}let{match:i,headerName:l}=await et(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function Kt(e){let s=0,o=0;for(let n=0;n<50;n++){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 T(800),r.msgCount===s){if(o++,o>=3)break}else o=0;s=r.msgCount}}async function X(e,{scrollUp:t=!0}={}){t&&await Kt(e);let s=await e.evaluate(()=>{let o=[],n="",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&&(n=d.textContent?.trim()||n);let c=n||"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&&(n=c.textContent?.trim()||n);let y=f(d,n||"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 s)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Se(o.time)||o.time);return s}function re(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function ae(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let s=p=>re(p.sender)+"||"+re(p.text),o=new Set(t.map(s)),n=new Set(e.map(s)),r=e.filter(p=>K.has(p.status)?!1:!o.has(s(p))),i=t.filter(p=>!n.has(s(p))),l=t.filter(p=>n.has(s(p))),a=e.filter(p=>K.has(p.status)),f=[...r,...l,...i],u=[];for(let p of f){let h=re(p.text),d=re(p.sender),c=!1;for(let g=0;g<u.length;g++){let y=u[g];if(re(y.sender)!==d)continue;let v=re(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 me(e,t){let s=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(s){await e.mouse.click(s.x,s.y),await T(3e3);let i=await Ce(e,t);if(i.verified)return i}let o=qe(t),n=o!==t?[t,o]:[t];for(let i of n)if(await tt(e,i,t)){let a=await Ce(e,t);if(a.verified)return a}let r=Je(o);if(r!==o&&r.length>0&&await tt(e,r,t,{requireUnique:!0})){let l=await Ce(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function tt(e,t,s,o={}){let{requireUnique:n=!1}=o,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await T(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await T(300),await r.type(t,{delay:30}),await T(500),await e.keyboard.press("Enter"),await T(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 E=y.includes(",")||/\d+ other/.test(y),A=v===u?3:v.includes(u)?2:1,I={text:y,isGroup:E,score:A,x:S.x+S.width/2,y:S.y+S.height/2};E?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},s,n);return i?(n&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function it(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await T(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 T(1e3))}import"dotenv/config";import*as w from"fs";import*as _e from"os";import*as R from"path";import{fileURLToPath as ko}from"url";var Re={};ye(Re,{NAME:()=>Xt,VERSION:()=>Qt,up:()=>to});import*as B from"fs";import*as ge from"path";var Qt=1,Xt="normalize-jobs-and-questions",Zt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],eo=50;function Ae(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function Te(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{B.writeFileSync(o,s)}catch(n){try{B.unlinkSync(o)}catch{}throw n}try{B.renameSync(o,e)}catch(n){try{B.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function to(e,t){let s=ge.join(e,"jobs.json"),o=ge.join(t,"scouted-jobs.json"),n=ge.join(e,"application-questions.json"),r=Ae(s)||{},i=Ae(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 Zt)m[h]!=null&&p[h]==null&&(p[h]=m[h]);a.push(u),l++}l>0?(Te(s,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Ae(n);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<=eo?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})}Te(n,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];Te(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 xe={};ye(xe,{NAME:()=>no,VERSION:()=>oo,up:()=>io});import*as q from"fs";import*as lt from"path";var oo=2,no="reset-unread-flags";function so(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function ro(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{q.writeFileSync(o,s)}catch(n){try{q.unlinkSync(o)}catch{}throw n}try{q.renameSync(o,e)}catch(n){try{q.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function io(e){let t=lt.join(e,"conversations.json"),s=so(t);if(!s){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let n of Object.keys(s))s[n].unread===!0&&(s[n].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}ro(t,s),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ie={};ye(Ie,{NAME:()=>ao,VERSION:()=>lo,up:()=>mo});import*as J from"fs";import*as at from"path";var lo=3,ao="recompute-last-message-by",co=new Set(["draft","confirmed","rejected","needs_review"]);function uo(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function fo(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{J.writeFileSync(o,s)}catch(n){try{J.unlinkSync(o)}catch{}throw n}try{J.renameSync(o,e)}catch(n){try{J.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}function po(e,t){if(!e||e.length===0)return"them";let s=e.filter(r=>!co.has(r.status));if(s.length===0)return"them";let o=s.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),n=o.length>0?o:[...s].reverse();for(let r of n){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function mo(e){let t=at.join(e,"conversations.json"),s=uo(t);if(!s){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,r=0,i=0;for(let l of Object.keys(s)){let a=s[l];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let f=Array.isArray(a.messages)?a.messages:[],u=po(f,o),m=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&i++,a.lastMessageBy=u,a.conversationStatus=m,n++}if(n===0){console.log(" No conversations to recompute.");return}fo(t,s),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}import"dotenv/config";import*as L from"path";import{fileURLToPath as go}from"url";var ho=go(import.meta.url),yo=L.dirname(L.dirname(ho)),ce=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(yo,"market-research"),Pn=L.join(ce,"scouted-jobs.json"),Ln=L.join(ce,"discovered-people.json"),Un=L.join(ce,"visit-log.json"),Bn=L.join(ce,"companies.json"),qn=L.join(ce,"job-decisions.json");function ct(){wo=null,So=null,vo=null,bo=null,$o=null}var wo=null;var So=null;var vo=null;var bo=null;var $o=null;var Eo=ko(import.meta.url),Co=R.dirname(Eo),Do=R.dirname(R.dirname(Co));function Ao(e){return e&&(e==="~"?_e.homedir():e.startsWith("~/")||e.startsWith("~\\")?R.join(_e.homedir(),e.slice(2)):e)}var H=process.env.DATA_DIR?R.resolve(Ao(process.env.DATA_DIR)):Do,ee=R.join(H,"collected-profiles"),te=R.join(H,"market-research"),N=R.join(H,".schema-version"),ut=[R.join(ee,".schema-version"),R.join(te,".schema-version")],z=3,Y=[{version:1,module:Re},{version:2,module:xe},{version:3,module:Ie}];(function(){Y.sort((o,n)=>o.version-n.version);let t=new Set;for(let o of Y){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 n=o.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let s=Y.length?Y[Y.length-1].version:0;if(s!==z)throw new Error(`MIGRATION_REGISTRY: highest version v${s} but CURRENT_SCHEMA_VERSION=${z}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<Y.length;o++){let n=o+1;if(Y[o].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${o} but found v${Y[o].version}`)}})();function mt(){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
- `),process.exit(1));try{w.mkdirSync(W,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
- [FATAL] Cannot create DATA_DIR (${W}): ${t.message}`),console.error(` Fix the path or permissions and try again.
15
- `),process.exit(1))}let e;try{e=w.statSync(W)}catch(t){console.error(`
16
- [FATAL] DATA_DIR (${W}) is not accessible: ${t.message}
13
+ `),process.exit(1));try{w.mkdirSync(H,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
14
+ [FATAL] Cannot create DATA_DIR (${H}): ${t.message}`),console.error(` Fix the path or permissions and try again.
15
+ `),process.exit(1))}let e;try{e=w.statSync(H)}catch(t){console.error(`
16
+ [FATAL] DATA_DIR (${H}) is not accessible: ${t.message}
17
17
  `),process.exit(1)}e.isDirectory()||(console.error(`
18
- [FATAL] DATA_DIR (${W}) 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.
19
- `),process.exit(1));for(let t of[Z,ee]){let n;try{n=w.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
18
+ [FATAL] DATA_DIR (${H}) 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.
19
+ `),process.exit(1));for(let t of[ee,te]){let s;try{s=w.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}s.isSymbolicLink()&&(console.error(`
20
20
  [FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
21
- `),process.exit(1))}}var X=R.join(W,".migration-lock");function wo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return w.writeFileSync(X,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(w.readFileSync(X,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let s=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}o&&r<s&&(console.error(`
22
- [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${X}
21
+ `),process.exit(1))}}var Z=R.join(H,".migration-lock");function To(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return w.writeFileSync(Z,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(w.readFileSync(Z,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let n=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}o&&r<n&&(console.error(`
22
+ [FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${Z}
23
23
  `),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.
24
- `),process.exit(1)),o&&r>=s&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=X+".tmp";try{return w.writeFileSync(n,e),w.renameSync(n,X),!0}catch(o){try{w.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Ie(){try{if(JSON.parse(w.readFileSync(X,"utf-8")).pid!==process.pid)return;w.unlinkSync(X)}catch{}}var at=!1;function So(){if(at)return;at=!0;let e=()=>{try{Ie()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function vo(){if(w.existsSync(M))return;let e=[],t=[];for(let r of lt)if(w.existsSync(r))try{e.push({file:r,schema:ge(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
24
+ `),process.exit(1)),o&&r>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let s=Z+".tmp";try{return w.writeFileSync(s,e),w.renameSync(s,Z),!0}catch(o){try{w.unlinkSync(s)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function je(){try{if(JSON.parse(w.readFileSync(Z,"utf-8")).pid!==process.pid)return;w.unlinkSync(Z)}catch{}}var ft=!1;function Ro(){if(ft)return;ft=!0;let e=()=>{try{je()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function xo(){if(w.existsSync(N))return;let e=[],t=[];for(let r of ut)if(w.existsSync(r))try{e.push({file:r,schema:he(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
25
25
  [FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
26
26
  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.
27
- `),process.exit(1)}if(e.length===0)return;let n=e.map(r=>r.schema.version);if(new Set(n).size>1){console.error(`
27
+ `),process.exit(1)}if(e.length===0)return;let s=e.map(r=>r.schema.version);if(new Set(s).size>1){console.error(`
28
28
  [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.
29
- `),process.exit(1)}let o=e[0].schema,s=M+".tmp";try{w.writeFileSync(s,JSON.stringify(o,null,2)),w.renameSync(s,M)}catch(r){try{w.unlinkSync(s)}catch{}throw r}for(let r of lt)if(w.existsSync(r))try{w.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${M}`)}function bo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function ge(e){let t=w.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function ct(){if(vo(),!w.existsSync(M))return{version:0,migrations:[]};let e;try{e=ge(M)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
30
- [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.
31
- `),process.exit(1)}let t=bo(e);return t===null&&(console.error(`
32
- [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.
33
- `),process.exit(1)),t}function dt(e){try{w.chmodSync(e,384)}catch{}}function $o(e){if(ft(),w.existsSync(M))try{if(w.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 t=M+".tmp";try{w.writeFileSync(t,JSON.stringify(e,null,2)),dt(t),w.renameSync(t,M)}catch(n){try{w.unlinkSync(t)}catch{}throw n}}function ut(e,t){if(!w.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=w.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return w.statSync(R.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of o){let a=R.join(e,l),f=R.join(e,l+n);if(w.existsSync(f)){r++;continue}try{mt(a,f),s++}catch(u){i.push({file:l,err:u.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${R.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(s>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${R.basename(e)}/ (${n})${l}`)}}var Re=!1;async function pt(){if(Re)return;ft(),To();let t=ct().version;if(t===G){Re=!0;return}So(),wo(),process.on("exit",Ie),t>G&&(console.error(`
34
- [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${G}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
35
- `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${G}.
29
+ `),process.exit(1)}let o=e[0].schema,n=N+".tmp";try{w.writeFileSync(n,JSON.stringify(o,null,2)),w.renameSync(n,N)}catch(r){try{w.unlinkSync(n)}catch{}throw r}for(let r of ut)if(w.existsSync(r))try{w.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${N}`)}function Io(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function he(e){let t=w.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dt(){if(xo(),!w.existsSync(N))return{version:0,migrations:[]};let e;try{e=he(N)}catch(s){if(s.code==="ENOENT")return{version:0,migrations:[]};console.error(`
30
+ [FATAL] ${N} is not valid JSON: ${s.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.
31
+ `),process.exit(1)}let t=Io(e);return t===null&&(console.error(`
32
+ [FATAL] ${N} 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.
33
+ `),process.exit(1)),t}function gt(e){try{w.chmodSync(e,384)}catch{}}function Oo(e){if(mt(),w.existsSync(N))try{if(w.lstatSync(N).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${N}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(s){if(s.message?.includes("symbolic link"))throw s}let t=N+".tmp";try{w.writeFileSync(t,JSON.stringify(e,null,2)),gt(t),w.renameSync(t,N)}catch(s){try{w.unlinkSync(t)}catch{}throw s}}function pt(e,t){if(!w.existsSync(e))return;let s=`.pre-v${String(t).padStart(3,"0")}.backup`,o=w.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return w.statSync(R.join(e,l)).isFile()}catch{return!1}}),n=0,r=0,i=[];for(let l of o){let a=R.join(e,l),f=R.join(e,l+s);if(w.existsSync(f)){r++;continue}try{yt(a,f),n++}catch(u){i.push({file:l,err:u.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${R.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(n>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${R.basename(e)}/ (${s})${l}`)}}var Oe=!1;async function ht(){if(Oe)return;mt(),Fo();let t=dt().version;if(t===z){Oe=!0;return}Ro(),To(),process.on("exit",je),t>z&&(console.error(`
34
+ [FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${z}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
35
+ `),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${z}.
36
36
  `),process.exit(1)),console.log(`
37
- \u{1F4E6} Schema migration: v${t} \u2192 v${G}`);let n=Ao();if(!n.ok){console.error(`
38
- [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
37
+ \u{1F4E6} Schema migration: v${t} \u2192 v${z}`);let s=Po();if(!s.ok){console.error(`
38
+ [FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of s.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
39
39
  Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
40
- `),process.exit(1)}let o=V.filter(s=>s.version>t);for(let s of o){console.log(`
41
- Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{ut(Z,s.version),ut(ee,s.version)}catch(a){console.error(`
40
+ `),process.exit(1)}let o=Y.filter(n=>n.version>t);for(let n of o){console.log(`
41
+ Running migration v${String(n.version).padStart(3,"0")}...`);let r=`v${String(n.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{pt(ee,n.version),pt(te,n.version)}catch(a){console.error(`
42
42
  [FATAL] Pre-migration backup failed for ${r}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
43
- `),process.exit(1)}let l=s.module;try{await l.up(Z,ee)}catch(a){console.error(`
44
- [FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let f=Ro(i);f.ok?(console.error(` \u2713 Auto-rollback restored ${f.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
43
+ `),process.exit(1)}let l=n.module;try{await l.up(ee,te)}catch(a){console.error(`
44
+ [FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let f=Lo(i);f.ok?(console.error(` \u2713 Auto-rollback restored ${f.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
45
45
  `)):(console.error(` [!] Auto-rollback INCOMPLETE: ${f.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
46
46
  `))}catch(f){console.error(` [!] Auto-rollback CRASHED while restoring: ${f.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
47
- `)}process.exit(1)}try{let a=new Date().toISOString(),f={version:s.version,name:l.NAME||r,appliedAt:a},u=ct();u.version=s.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(f),$o(u)}catch(a){console.error(`
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
- `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{qe()}catch{}try{it()}catch{}Re=!0,Ie(),console.log(`
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=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(`
47
+ `)}process.exit(1)}try{let a=new Date().toISOString(),f={version:n.version,name:l.NAME||r,appliedAt:a},u=dt();u.version=n.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(f),Oo(u)}catch(a){console.error(`
48
+ [FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${n.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
+ `),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{We()}catch{}try{ct()}catch{}Oe=!0,je(),console.log(`
50
+ \u2713 Schema is now at v${z}
51
+ `)}var _o=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function jo(e){let t=e.toLowerCase();return _o.some(s=>s.test(t))}var No=6e4;function Mo(){let e=Date.now(),t=[];for(let s of[H,ee,te]){if(!w.existsSync(s))continue;let o;try{o=w.readdirSync(s)}catch{continue}for(let n of o){if(!jo(n))continue;let r=R.join(s,n);try{let i=w.statSync(r);if(!i.isFile()||e-i.mtimeMs<No)continue;t.push({dir:s,file:n,fullPath:r})}catch{}}}return t}function Fo({verbose:e=!1}={}){let t=Mo();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let s=0;for(let o of t)try{w.unlinkSync(o.fullPath),s++,e&&console.log(` Removed orphan: ${R.basename(o.dir)}/${o.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${n.message}`)}return!e&&s>0&&console.log(` Cleaned up ${s} orphan .tmp file(s) from previous run.`),s}function Po(){let e=[];for(let t of[ee,te]){if(!w.existsSync(t))continue;let s=w.readdirSync(t).filter(o=>{let n=o.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let o of s){let n=R.join(t,o);try{he(n)}catch(r){e.push({dir:R.basename(t),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Lo(e){let t=[],s=[];for(let r of[ee,te]){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")?he(a):w.accessSync(a,w.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:l,dir:r})}catch(m){s.push(`${R.basename(r)}/${l}: ${m.message}`)}}}if(s.length>0)return{ok:!1,error:s.join("; "),restored:0};let o=0,n=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:a}of t)try{yt(r,i),o++}catch(f){n.push(`${R.basename(a)}/${l}: ${f.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:o}:{ok:!0,restored:o}}function yt(e,t){let s=t+".tmp";try{w.copyFileSync(e,s),gt(s)}catch(o){try{w.unlinkSync(s)}catch{}throw o}try{w.renameSync(s,t)}catch(o){try{w.unlinkSync(s)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let n=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 n.code=o.code,n}throw o}}await ht();var Uo=ne.toLowerCase().split(/\s+/).filter(e=>e.length>1);function Pe(e){if(!e)return!1;if(e===ne)return!0;let t=e.toLowerCase();return Uo.some(s=>t.includes(s))}function Ne(e){return(e.messages||[]).find(t=>le.has(t.status))}function M(e){return(e.messages||[]).find(t=>K.has(t.status))}function Me(e){return Ne(e)?.text||null}function Fe(e){return(e.messages||[]).some(t=>le.has(t.status))}function Bo(e){return(e.messages||[]).some(t=>K.has(t.status))}function qo(e,t){let s=M(e);s&&(s.text=t)}function Jo(){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 s=0;s<t.length;s++){let o=t[s];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[++s]||null;else if(o==="--send"){let n=t[++s],r=t[++s]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=oe.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.send={target:n,text:r}}else if(o==="--draft"){let n=t[++s],r=t[++s]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=oe.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.draft={target:n,text:r}}else if(o==="--push-drafts")e.pushDrafts=!0;else if(o==="--review-drafts")e.reviewDrafts=!0;else if(o==="--follow-up"){let n=t[++s],r=t[++s]||"",i=t[++s]||null;e.followUp={target:n,note:r,date:i}}else if(o==="--follow-up-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.followUpBatch=JSON.parse(oe.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read follow-up batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--clear-follow-up")e.clearFollowUp=t[++s]||null;else if(o==="--review")e.review=t[++s]||null;else if(o==="--review-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.reviewBatch=JSON.parse(oe.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read review batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--draft-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.draftBatch=JSON.parse(oe.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read draft batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--send-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.sendBatch=JSON.parse(oe.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}}return e}function Wo(){let e=j(),t=Object.entries(e),s=t.length;if(s===0){console.log(`
52
52
  No conversations synced yet. Run: npm run messages
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
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(`
53
+ `);return}let o={};for(let[,d]of t){let c=d.conversationStatus||"(none)";o[c]=(o[c]||0)+1}let n=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
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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: ${s} 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(`
55
55
  By status:`);for(let[d,c]of Object.entries(o).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${c}`);let r={};for(let[,d]of t){let c=d.category||"(none)";r[c]=(r[c]||0)+1}let i=t.filter(([,d])=>d.category).length;if(i>0){console.log(`
56
- By category (${i} categorized):`);for(let[d,c]of Object.entries(r).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${c}`)}let l=t.filter(([,d])=>je(d));if(l.length>0){let d=l.filter(([,C])=>C.conversationStatus==="unanswered_by_us"),c=l.filter(([,C])=>C.conversationStatus==="awaiting_reply"),g=l.filter(([,C])=>C.conversationStatus!=="unanswered_by_us"&&C.conversationStatus!=="awaiting_reply");console.log(`
56
+ By category (${i} categorized):`);for(let[d,c]of Object.entries(r).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${c}`)}let l=t.filter(([,d])=>Fe(d));if(l.length>0){let d=l.filter(([,E])=>E.conversationStatus==="unanswered_by_us"),c=l.filter(([,E])=>E.conversationStatus==="awaiting_reply"),g=l.filter(([,E])=>E.conversationStatus!=="unanswered_by_us"&&E.conversationStatus!=="awaiting_reply");console.log(`
57
57
  \u{1F4DD} DRAFTS READY TO PUSH \u2014 ${l.length} total:
58
- `);let y=([C,T])=>{let I=T.priority?` [${T.priority.toUpperCase()}]`:"",b=N(T),$=b?.status||k.DRAFT,D={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[$]||"",E=b?.text||"";console.log(` ${D} ${C}${I}`),console.log(` "${E.slice(0,80)}${E.length>80?"...":""}"`)};d.length>0&&(console.log(` \u2500\u2500 Replies (they wrote last) \u2014 ${d.length}:`),d.forEach(y),console.log()),c.length>0&&(console.log(` \u2500\u2500 Re-engagement (we wrote last, following up) \u2014 ${c.length}:`),c.forEach(y),console.log()),g.length>0&&(console.log(` \u2500\u2500 Other \u2014 ${g.length}:`),g.forEach(y),console.log());let v=l.filter(([,C])=>N(C)?.status===k.CONFIRMED).length,S=l.filter(([,C])=>{let T=N(C)?.status;return T===k.DRAFT||T===k.NEEDS_REVIEW}).length;console.log(` ${v} confirmed, ${S} pending review`),S>0&&console.log(" Review: npm run messages -- --review-drafts"),v>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let a=new Date,f=t.filter(([,d])=>d.priority&&d.conversationStatus==="awaiting_reply").filter(([,d])=>d.followUpAfter?new Date(d.followUpAfter)<=a:!0).sort((d,c)=>{let g={high:0,medium:1,low:2}[d[1].priority]??3,y={high:0,medium:1,low:2}[c[1].priority]??3;return g-y});if(f.length>0){console.log(`
58
+ `);let y=([E,A])=>{let I=A.priority?` [${A.priority.toUpperCase()}]`:"",b=M(A),$=b?.status||k.DRAFT,D={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[$]||"",C=b?.text||"";console.log(` ${D} ${E}${I}`),console.log(` "${C.slice(0,80)}${C.length>80?"...":""}"`)};d.length>0&&(console.log(` \u2500\u2500 Replies (they wrote last) \u2014 ${d.length}:`),d.forEach(y),console.log()),c.length>0&&(console.log(` \u2500\u2500 Re-engagement (we wrote last, following up) \u2014 ${c.length}:`),c.forEach(y),console.log()),g.length>0&&(console.log(` \u2500\u2500 Other \u2014 ${g.length}:`),g.forEach(y),console.log());let v=l.filter(([,E])=>M(E)?.status===k.CONFIRMED).length,S=l.filter(([,E])=>{let A=M(E)?.status;return A===k.DRAFT||A===k.NEEDS_REVIEW}).length;console.log(` ${v} confirmed, ${S} pending review`),S>0&&console.log(" Review: npm run messages -- --review-drafts"),v>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let a=new Date,f=t.filter(([,d])=>d.priority&&d.conversationStatus==="awaiting_reply").filter(([,d])=>d.followUpAfter?new Date(d.followUpAfter)<=a:!0).sort((d,c)=>{let g={high:0,medium:1,low:2}[d[1].priority]??3,y={high:0,medium:1,low:2}[c[1].priority]??3;return g-y});if(f.length>0){console.log(`
59
59
  \u{1F514} FOLLOW-UP NEEDED \u2014 ${f.length} priority contacts waiting:
60
- `);for(let[d,c]of f){let g=c.priority.toUpperCase(),y=c.lastSynced?Math.floor((a-new Date(c.lastSynced))/864e5):"?",v=c.lastMessagePreview?.slice(0,50)||"";console.log(` [${g}] ${d} \u2014 ${y}d ago`),c.notes&&console.log(` \u{1F4CC} ${c.notes}`),console.log(` ${v}`),console.log()}}if(s.length>0){console.log(`\u26A1 ACTION NEEDED \u2014 ${s.length} unanswered messages:
61
- `);for(let[d,c]of s){let g=je(c)?" [DRAFT READY]":"",y=c.priority?` [${c.priority.toUpperCase()}]`:c.suggestedPriority?` [${c.suggestedPriority}]`:"",v=c.category?` (${c.category})`:"",S=c.actionNeeded&&c.actionNeeded!=="none"?` \u2192 ${c.actionNeeded}`:"",C=c.lastMessageTime||"",T=(c.autoTags||[]).slice(0,4).join(", ");if(console.log(` ${d}${v}${y}${g}${S}`),c.summary)console.log(` ${c.summary}`);else{let I=c.lastMessagePreview?c.lastMessagePreview.slice(0,60)+(c.lastMessagePreview.length>60?"...":""):"";console.log(` ${C} | ${I}`)}T&&console.log(` #${T.replace(/, /g," #")}`),c.notes&&console.log(` \u{1F4CC} ${c.notes}`),c.profileUrl&&console.log(` ${c.profileUrl}`),console.log()}}else console.log(`
62
- All caught up \u2014 no unanswered messages.`);let u=J(),m=new Set(Object.keys(e)),p=new Set(Object.values(e).map(d=>d.profileUrl).filter(Boolean)),h=Object.entries(u).filter(([d,c])=>c.connectionStatus==="connected"&&c.personActionNeeded==="initiate_contact"&&!p.has(d)&&!(c.name&&m.has(c.name))).sort((d,c)=>{let g={high:0,medium:1,low:2}[d[1].personPriority]??3,y={high:0,medium:1,low:2}[c[1].personPriority]??3;return g!==y?g-y:(c[1].connectionDate||"").localeCompare(d[1].connectionDate||"")});if(h.length>0){console.log(`
60
+ `);for(let[d,c]of f){let g=c.priority.toUpperCase(),y=c.lastSynced?Math.floor((a-new Date(c.lastSynced))/864e5):"?",v=c.lastMessagePreview?.slice(0,50)||"";console.log(` [${g}] ${d} \u2014 ${y}d ago`),c.notes&&console.log(` \u{1F4CC} ${c.notes}`),console.log(` ${v}`),console.log()}}if(n.length>0){console.log(`\u26A1 ACTION NEEDED \u2014 ${n.length} unanswered messages:
61
+ `);for(let[d,c]of n){let g=Fe(c)?" [DRAFT READY]":"",y=c.priority?` [${c.priority.toUpperCase()}]`:c.suggestedPriority?` [${c.suggestedPriority}]`:"",v=c.category?` (${c.category})`:"",S=c.actionNeeded&&c.actionNeeded!=="none"?` \u2192 ${c.actionNeeded}`:"",E=c.lastMessageTime||"",A=(c.autoTags||[]).slice(0,4).join(", ");if(console.log(` ${d}${v}${y}${g}${S}`),c.summary)console.log(` ${c.summary}`);else{let I=c.lastMessagePreview?c.lastMessagePreview.slice(0,60)+(c.lastMessagePreview.length>60?"...":""):"";console.log(` ${E} | ${I}`)}A&&console.log(` #${A.replace(/, /g," #")}`),c.notes&&console.log(` \u{1F4CC} ${c.notes}`),c.profileUrl&&console.log(` ${c.profileUrl}`),console.log()}}else console.log(`
62
+ All caught up \u2014 no unanswered messages.`);let u=W(),m=new Set(Object.keys(e)),p=new Set(Object.values(e).map(d=>d.profileUrl).filter(Boolean)),h=Object.entries(u).filter(([d,c])=>c.connectionStatus==="connected"&&c.personActionNeeded==="initiate_contact"&&!p.has(d)&&!(c.name&&m.has(c.name))).sort((d,c)=>{let g={high:0,medium:1,low:2}[d[1].personPriority]??3,y={high:0,medium:1,low:2}[c[1].personPriority]??3;return g!==y?g-y:(c[1].connectionDate||"").localeCompare(d[1].connectionDate||"")});if(h.length>0){console.log(`
63
63
  \u2709\uFE0F NEW CONNECTIONS TO MESSAGE \u2014 ${h.length} total:
64
64
  `);let d=15;for(let[c,g]of h.slice(0,d)){let y=g.personPriority?`[${g.personPriority.toUpperCase()}]`:"",v=g.title?`${g.title}${g.company?` at ${g.company}`:""}`:g.company||"";console.log(` ${y} ${g.name||"Unknown"} \u2014 ${v}`),g.personSummary&&console.log(` ${g.personSummary}`),c&&console.log(` ${c}`),console.log()}h.length>d&&console.log(` ... and ${h.length-d} more. Run: npm run today
65
- `)}console.log()}function gt(e,t){return new Promise(n=>e.question(t,n))}async function Mo(){let e=j(),t=J(),n={};for(let u of Object.values(t))u.name&&u.title&&(n[u.name]=u.title);let o={draft:0,needs_review:0,confirmed:1,rejected:2},s=Object.entries(e).filter(([,u])=>Io(u)).sort((u,m)=>{let p=o[N(u[1])?.status]??0,h=o[N(m[1])?.status]??0;if(p!==h)return p-h;let d={high:0,medium:1,low:2}[u[1].priority]??3,c={high:0,medium:1,low:2}[m[1].priority]??3;return d-c});if(s.length===0){console.log(`
65
+ `)}console.log()}function wt(e,t){return new Promise(s=>e.question(t,s))}async function Ho(){let e=j(),t=W(),s={};for(let u of Object.values(t))u.name&&u.title&&(s[u.name]=u.title);let o={draft:0,needs_review:0,confirmed:1,rejected:2},n=Object.entries(e).filter(([,u])=>Bo(u)).sort((u,m)=>{let p=o[M(u[1])?.status]??0,h=o[M(m[1])?.status]??0;if(p!==h)return p-h;let d={high:0,medium:1,low:2}[u[1].priority]??3,c={high:0,medium:1,low:2}[m[1].priority]??3;return d-c});if(n.length===0){console.log(`
66
66
  No drafts to review.
67
- `);return}let r=s.filter(([,u])=>{let m=N(u)?.status;return m===k.DRAFT||m===k.NEEDS_REVIEW}),i=s.filter(([,u])=>N(u)?.status===k.CONFIRMED),l=s.filter(([,u])=>N(u)?.status===k.REJECTED);console.log(`
68
- \u2550\u2550 Draft Review \u2550\u2550`),console.log(` Total: ${s.length} drafts (${r.length} pending, ${i.length} confirmed, ${l.length} rejected)
67
+ `);return}let r=n.filter(([,u])=>{let m=M(u)?.status;return m===k.DRAFT||m===k.NEEDS_REVIEW}),i=n.filter(([,u])=>M(u)?.status===k.CONFIRMED),l=n.filter(([,u])=>M(u)?.status===k.REJECTED);console.log(`
68
+ \u2550\u2550 Draft Review \u2550\u2550`),console.log(` Total: ${n.length} drafts (${r.length} pending, ${i.length} confirmed, ${l.length} rejected)
69
69
  `),console.log(` Commands: [c]onfirm [r]eject [e]dit [s]kip [q]uit
70
- `);let a=yt.createInterface({input:process.stdin,output:process.stdout}),f=0;for(let u=0;u<s.length;u++){let[m,p]=s[u],h=N(p),d=h?.status||k.DRAFT,c={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[d]||"?",g={high:"\u{1F534}",medium:"\u{1F7E1}",low:"\u26AA"}[p.priority]||"",y=n[m]||"",v=p.messages||[],S=p.conversationStatus||"?";if(console.log(`
71
- ${"\u2550".repeat(60)}`),console.log(` ${u+1}/${s.length} ${c} ${m} ${g} ${(p.priority||"").toUpperCase()}`),y&&console.log(` ${y}`),console.log(` Status: ${S} | ${v.length} msgs synced`),p.notes&&console.log(` Notes: ${p.notes}`),console.log(`${"\u2500".repeat(60)}`),v.length>0){console.log(" Conversation:");let $=v.slice(-4);v.length>4&&console.log(` ... (${v.length-4} earlier messages)`);for(let D of $){let E=D.sender||"Unknown",x=(D.text||"").replace(/\n/g," ").substring(0,120),ce=Me(E)?" \u2192":" \u2190";console.log(` ${ce} [${E}] ${x}`)}}else p.lastMessagePreview&&console.log(` Preview: "${p.lastMessagePreview}"`);console.log(`${"\u2500".repeat(60)}`),console.log(" Draft:");let C=_e(p)||"",T=C.match(/.{1,80}/g)||[C];for(let $ of T)console.log(` ${$}`);console.log(`${"\u2500".repeat(60)}`);let b=(await gt(a," [c]onfirm [r]eject [e]dit [s]kip [q]uit > ")).trim().toLowerCase();if(b==="c"||b==="confirm"||b==="y"||b==="yes")h.status=k.CONFIRMED,f++,console.log(" \u2705 Confirmed");else if(b==="r"||b==="reject"||b==="n"||b==="no")h.status=k.REJECTED,f++,console.log(" \u274C Rejected");else if(b==="e"||b==="edit"){console.log(" Enter new draft text (end with empty line):");let $=[];for(;;){let D=await gt(a," ");if(D.trim()==="")break;$.push(D)}$.length>0?(Oo(p,$.join(`
72
- `)),h.status=k.CONFIRMED,f++,console.log(" \u2705 Edited & Confirmed")):console.log(" (no changes)")}else if(b==="q"||b==="quit"){console.log(" Quitting review...");break}else console.log(" \u23ED Skipped")}if(a.close(),f>0){P(e);let u=Object.values(e).filter(h=>N(h)?.status===k.CONFIRMED).length,m=Object.values(e).filter(h=>N(h)?.status===k.REJECTED).length,p=Object.values(e).filter(h=>{let d=N(h)?.status;return d===k.DRAFT||d===k.NEEDS_REVIEW}).length;console.log(`
73
- Saved. ${u} confirmed, ${p} pending, ${m} rejected.`),u>0&&console.log(" Ready to send: npm run messages -- --push-drafts")}console.log()}async function wt(e){try{await st(e)}catch{}}async function No(e,t){let{full:n,max:o,verbose:s,dryRun:r}=t,i=n?"full":"incremental",l=j(),a=new Set(Object.keys(l)),f=new Map,u=0,m=0,p=3,h=0,d=3;for(;;){u++;let y=await ot(e),v=0,S=0;for(let C of y)C.name&&(f.has(C.name)||(f.set(C.name,C),a.has(C.name)?S++:v++));if(s?console.log(` Round #${u}: ${v} new, ${S} known | Total: ${f.size}`):process.stdout.write(`\r Conversations found: ${f.size} (page #${u})`),f.size>=o){console.log(`
70
+ `);let a=vt.createInterface({input:process.stdin,output:process.stdout}),f=0;for(let u=0;u<n.length;u++){let[m,p]=n[u],h=M(p),d=h?.status||k.DRAFT,c={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[d]||"?",g={high:"\u{1F534}",medium:"\u{1F7E1}",low:"\u26AA"}[p.priority]||"",y=s[m]||"",v=p.messages||[],S=p.conversationStatus||"?";if(console.log(`
71
+ ${"\u2550".repeat(60)}`),console.log(` ${u+1}/${n.length} ${c} ${m} ${g} ${(p.priority||"").toUpperCase()}`),y&&console.log(` ${y}`),console.log(` Status: ${S} | ${v.length} msgs synced`),p.notes&&console.log(` Notes: ${p.notes}`),console.log(`${"\u2500".repeat(60)}`),v.length>0){console.log(" Conversation:");let $=v.slice(-4);v.length>4&&console.log(` ... (${v.length-4} earlier messages)`);for(let D of $){let C=D.sender||"Unknown",x=(D.text||"").replace(/\n/g," ").substring(0,120),ue=Pe(C)?" \u2192":" \u2190";console.log(` ${ue} [${C}] ${x}`)}}else p.lastMessagePreview&&console.log(` Preview: "${p.lastMessagePreview}"`);console.log(`${"\u2500".repeat(60)}`),console.log(" Draft:");let E=Me(p)||"",A=E.match(/.{1,80}/g)||[E];for(let $ of A)console.log(` ${$}`);console.log(`${"\u2500".repeat(60)}`);let b=(await wt(a," [c]onfirm [r]eject [e]dit [s]kip [q]uit > ")).trim().toLowerCase();if(b==="c"||b==="confirm"||b==="y"||b==="yes")h.status=k.CONFIRMED,f++,console.log(" \u2705 Confirmed");else if(b==="r"||b==="reject"||b==="n"||b==="no")h.status=k.REJECTED,f++,console.log(" \u274C Rejected");else if(b==="e"||b==="edit"){console.log(" Enter new draft text (end with empty line):");let $=[];for(;;){let D=await wt(a," ");if(D.trim()==="")break;$.push(D)}$.length>0?(qo(p,$.join(`
72
+ `)),h.status=k.CONFIRMED,f++,console.log(" \u2705 Edited & Confirmed")):console.log(" (no changes)")}else if(b==="q"||b==="quit"){console.log(" Quitting review...");break}else console.log(" \u23ED Skipped")}if(a.close(),f>0){P(e);let u=Object.values(e).filter(h=>M(h)?.status===k.CONFIRMED).length,m=Object.values(e).filter(h=>M(h)?.status===k.REJECTED).length,p=Object.values(e).filter(h=>{let d=M(h)?.status;return d===k.DRAFT||d===k.NEEDS_REVIEW}).length;console.log(`
73
+ Saved. ${u} confirmed, ${p} pending, ${m} rejected.`),u>0&&console.log(" Ready to send: npm run messages -- --push-drafts")}console.log()}async function bt(e){try{await it(e)}catch{}}async function Vo(e,t){let{full:s,max:o,verbose:n,dryRun:r}=t,i=s?"full":"incremental",l=j(),a=new Set(Object.keys(l)),f=new Map,u=0,m=0,p=3,h=0,d=3;for(;;){u++;let y=await st(e),v=0,S=0;for(let E of y)E.name&&(f.has(E.name)||(f.set(E.name,E),a.has(E.name)?S++:v++));if(n?console.log(` Round #${u}: ${v} new, ${S} known | Total: ${f.size}`):process.stdout.write(`\r Conversations found: ${f.size} (page #${u})`),f.size>=o){console.log(`
74
74
  Reached --max=${o}, stopping.`);break}if(v===0&&S===0){if(h++,h>=d){console.log(`
75
- ${d} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!n&&v===0&&S>0){if(m++,m>=p){console.log(`
76
- ${p} pages of already-synced conversations \u2014 caught up.`);break}}else v>0&&(m=0);await nt(e),await A(2e3)}s||process.stdout.write(`
75
+ ${d} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!s&&v===0&&S>0){if(m++,m>=p){console.log(`
76
+ ${p} pages of already-synced conversations \u2014 caught up.`);break}}else v>0&&(m=0);await rt(e),await T(2e3)}n||process.stdout.write(`
77
77
  `);let c=Array.from(f.values());console.log(`
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(`
78
+ Extracted ${c.length} conversations.`);let g=Zo(c,r);en(c,g,r,i)}async function Yo(e,t,s){let o=W(),n=j(),r;if(t.startsWith("http")){let f=o[t],u=Object.entries(n).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
- `),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===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
- Sending message to: ${s.personName}`),console.log(` Text: "${n.slice(0,150)}${n.length>150?"...":""}"`),o?(console.log(`
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(`
80
+ `),await De(e);let{verified:i}=await me(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await X(e);if(l.length===0){if(console.log(" No messages extracted (DOM may have changed)."),s){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;n[a]||(n[a]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),n[a].messages=ae(n[a].messages,l),n[a].lastSynced=new Date().toISOString(),P(n),console.log(` Saved ${n[a].messages.length} messages to conversations.json ["${a}"]`)}function Le(e){let t=W(),s=e,o=null;if(e.startsWith("http")){let n=t[e];if(n?.name)s=n.name,o=e;else return null}else{let n=Object.entries(t).find(([,i])=>i.name===e);n&&(o=n[0]);let r=j();!o&&r[e]?.profileUrl&&(o=r[e].profileUrl)}return{personName:s,profileUrl:o}}async function Ue(e,t,s,o,n={}){try{let{verified:r}=await me(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await X(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 C=i.length-1;C>=0;C--)if(i[C].sender!=="Unknown"&&i[C].sender!==""){D=i[C].sender;break}if(D===ne)if(n.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(!n.allowDoubleMessage){let $=new Date().toISOString().slice(0,10);if(i.some(C=>{if(!Pe(C.sender))return!1;let F=C.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 T(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 T(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 T(2e3),console.log(" \u2713 Message sent!"),console.log(" Syncing conversation thread..."),await T(1e3);let v=await X(e);console.log(` Synced ${v.length} messages from thread.`);let S=j(),E=new Date().toISOString(),A=t;S[A]?(S[A].lastMessageBy="me",S[A].lastMessagePreview=o.slice(0,100),S[A].lastMessageTime=E,S[A].conversationStatus="awaiting_reply",S[A].lastSynced=E,S[A].messages=ae(S[A].messages,v)):S[A]={profileUrl:s,lastSynced:E,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:v},s&&(S[A].profileUrl=s),P(S);let I=W(),b=s?I[s]:null;return b&&(b.conversationStatus="awaiting_reply",b.lastMessageSent=E,b.lastUpdated=E,pe(I)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function St(e,t,s){if(t?.profileUrl)return t.profileUrl;let o=Object.entries(s).find(([,n])=>n.name===e);return o?o[0]:null}async function Go(e,t,s,o){try{console.log(` \u2192 Profile fallback: navigating to ${s}`),await e.goto(s,{waitUntil:"domcontentloaded",timeout:3e4}),await T(3e3);let n=await e.evaluate(()=>{let b=0,$=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let C of $){if(C.offsetHeight===0)continue;let x=C.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(x||(x=C.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!x){let F=C.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 C=D.querySelector(".msg-overlay-bubble-header__button");C&&C.offsetHeight>0&&(C.click(),b++)}return b});n>0&&(console.log(` Closed ${n} existing overlay(s)`),await T(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"),C=D?D.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:$.length,trayMinimized:C,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 C=new URL($.getAttribute("href"),location.origin).searchParams.get("recipient");if(C)return C}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 T(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, div[contenteditable="true"][role="textbox"]',{timeout:1e4})}catch{return console.error(' \u2717 Message composer never appeared on compose page (neither msg-form__contenteditable nor [contenteditable="true"][role="textbox"])'),!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 X(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(!Pe(x.sender))return!1;let ue=x.time||"";return ue.startsWith(D)||ue.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 T(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 T(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 T(2e3),console.log(" \u2713 Message sent via profile!"),console.log(" Syncing conversation thread..."),await T(1e3);let v=await X(e);console.log(` Synced ${v.length} messages from thread.`);let S=j(),E=new Date().toISOString();S[t]?(S[t].lastMessageBy="me",S[t].lastMessagePreview=o.slice(0,100),S[t].lastMessageTime=E,S[t].conversationStatus="awaiting_reply",S[t].lastSynced=E,S[t].messages=ae(S[t].messages,v)):S[t]={profileUrl:s,lastSynced:E,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:v},s&&(S[t].profileUrl=s),P(S);let A=W(),I=A[s];return I&&(I.conversationStatus="awaiting_reply",I.lastMessageSent=E,I.lastUpdated=E,pe(A)),!0}catch(n){return console.error(" \u2717 Profile send error:",n.message),!1}}async function zo(e,t,s,o){if(!t||!s)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let n=Le(t);return n?(console.log(`
82
+ Sending message to: ${n.personName}`),console.log(` Text: "${s.slice(0,150)}${s.length>150?"...":""}"`),o?(console.log(`
83
+ [DRY RUN \u2014 message not sent]`),!1):(await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await T(4e3),Ue(e,n.personName,n.profileUrl,s))):(console.error(` Person not found: ${t}`),!1)}async function Ko(e,t,s){if(console.log(`
84
84
  \u2550\u2550 Batch send: ${t.length} messages \u2550\u2550
85
- `),n){for(let{name:i,message:l}of t)console.log(` [DRY RUN] ${i}: "${l.slice(0,80)}..."`);return}await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let o=[];for(let i=0;i<t.length;i++){let{name:l,message:a}=t[i];console.log(`
86
- \u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`);let f=Ne(l);if(!f){console.error(` \u2717 Cannot resolve: ${l}`),o.push({name:l,status:"not_found"});continue}console.log(` Text: "${a.slice(0,100)}${a.length>100?"...":""}"`);let u=await Fe(e,f.personName,f.profileUrl,a);o.push({name:l,status:u?"sent":"failed"}),await wt(e)}console.log(`
85
+ `),s){for(let{name:i,message:l}of t)console.log(` [DRY RUN] ${i}: "${l.slice(0,80)}..."`);return}await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await T(4e3);let o=[];for(let i=0;i<t.length;i++){let{name:l,message:a}=t[i];console.log(`
86
+ \u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`);let f=Le(l);if(!f){console.error(` \u2717 Cannot resolve: ${l}`),o.push({name:l,status:"not_found"});continue}console.log(` Text: "${a.slice(0,100)}${a.length>100?"...":""}"`);let u=await Ue(e,f.personName,f.profileUrl,a);o.push({name:l,status:u?"sent":"failed"}),await bt(e)}console.log(`
87
87
  \u2550\u2550 Batch results \u2550\u2550
88
- `);let s=o.filter(i=>i.status===k.SENT),r=o.filter(i=>i.status!==k.SENT);for(let i of o){let l=i.status===k.SENT?"\u2713":"\u2717";console.log(` ${l} ${i.name} \u2014 ${i.status}`)}console.log(`
89
- Total: ${s.length} sent, ${r.length} failed/skipped`)}async function Bo(e,t){let n=j(),o=J(),s=Object.entries(n).filter(([,d])=>je(d)),r=s.filter(([,d])=>Oe(d)?.status===k.CONFIRMED),i=s.filter(([,d])=>{let c=Oe(d)?.status;return c===k.DRAFT||c===k.NEEDS_REVIEW}).length;if(s.length===0){console.log(`
88
+ `);let n=o.filter(i=>i.status===k.SENT),r=o.filter(i=>i.status!==k.SENT);for(let i of o){let l=i.status===k.SENT?"\u2713":"\u2717";console.log(` ${l} ${i.name} \u2014 ${i.status}`)}console.log(`
89
+ Total: ${n.length} sent, ${r.length} failed/skipped`)}async function Qo(e,t){let s=j(),o=W(),n=Object.entries(s).filter(([,d])=>Fe(d)),r=n.filter(([,d])=>Ne(d)?.status===k.CONFIRMED),i=n.filter(([,d])=>{let c=Ne(d)?.status;return c===k.DRAFT||c===k.NEEDS_REVIEW}).length;if(n.length===0){console.log(`
90
90
  No drafts to push. Prepare drafts in conversations.json first.
91
91
  `);return}if(r.length===0){console.log(`
92
92
  No confirmed drafts to push (${i} pending, need review).`),console.log(` Run: npm run messages -- --review-drafts
93
93
  `);return}if(console.log(`
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
- `),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=>!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(`
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=St(d,c,o),y=c.messages?.some(S=>!le.has(S.status)&&S.status!==k.REJECTED)?"inbox":g?"profile":"no profileUrl";console.log(` [DRY RUN] ${d} (${y}):`);let v=Me(c)||"";console.log(` "${v.slice(0,100)}${v.length>100?"...":""}"`),console.log()}return}console.log(`\u2500\u2500 Pass 1: Inbox search \u2500\u2500
95
+ `),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await T(4e3);let l=[],a=[];for(let d=0;d<r.length;d++){let[c,g]=r[d],y=Me(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=Le(c),S=v?.personName||c,E=v?.profileUrl||g.profileUrl||null,I=(g.messages||[]).filter(D=>!K.has(D.status)).length,b=!1,$=!1;try{await Be(e);let{verified:D}=await me(e,S);if(D){$=!0;let C=await X(e);if(C.length>I&&I>0){let x=C.length-I;b=!0,g.messages=ae(g.messages,C),console.log(` \u26A0 ${x} new message(s) since draft was created!`);let F=C[C.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 Ue(e,S,E,y,{allowDoubleMessage:!0})){for(let C of g.messages||[])C.status===k.CONFIRMED&&C.text===y&&(C.status=k.SENT,C.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",P(s),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(s),await bt(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
- \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(`
99
+ \u2500\u2500 [profile ${d+1}/${a.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let S=St(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 Go(e,v,S,y)){for(let A of g.messages||[])A.status===k.CONFIRMED&&A.text===y&&(A.status=k.SENT,A.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",P(s),l.push({name:c,status:"sent",method:"profile"})}else l.push({name:c,status:"failed",method:"profile"})}}console.log(`
100
100
  \u2550\u2550 Push results \u2550\u2550
101
101
  `);let f=l.filter(d=>d.status===k.SENT),u=l.filter(d=>d.status===k.NEEDS_REVIEW),m=l.filter(d=>d.status==="failed");for(let d of l){let c={sent:"\u2713",needs_review:"\u26A0",failed:"\u2717"}[d.status]||"?",g=d.method?` (${d.method})`:"";console.log(` ${c} ${d.name} \u2014 ${d.status}${g}`)}let p=f.filter(d=>d.method==="inbox").length,h=f.filter(d=>d.method==="profile").length;console.log(`
102
- Total: ${f.length} sent (${p} inbox, ${h} profile), ${u.length} need review, ${m.length} failed`)}function qo(e){let t={};for(let[n,o]of Object.entries(e)){let s=o.name;s&&(t[s]?o.connectionStatus==="connected"&&t[s].connectionStatus!=="connected"&&(t[s]={url:n,...o}):t[s]={url:n,...o})}return t}function Jo(e,t){let n=j(),o=J(),s=qo(o),r=new Date().toISOString(),i={newConversations:0,updatedConversations:0,unansweredByUs:0,awaitingReply:0,peopleLinked:0,newPeople:0};for(let l of e){if(!l.name)continue;let a;l.lastMessageBy==="them"?(a="unanswered_by_us",i.unansweredByUs++):l.lastMessageBy==="me"?(a="awaiting_reply",i.awaitingReply++):a="mutual_silence";let u=s[l.name]?.url||null,m=n[l.name];if(m?(m.lastSynced=r,m.lastMessageBy=l.lastMessageBy,m.lastMessagePreview=l.lastMessagePreview||m.lastMessagePreview,m.lastMessageTime=l.lastMessageTime||m.lastMessageTime,m.unread=l.unread,m.conversationStatus||(m.conversationStatus=a),u&&!m.profileUrl&&(m.profileUrl=u),i.updatedConversations++):(n[l.name]={profileUrl:u,lastSynced:r,lastMessageBy:l.lastMessageBy,lastMessagePreview:l.lastMessagePreview||"",lastMessageTime:l.lastMessageTime||"",unread:l.unread||!1,conversationStatus:a,messages:[]},i.newConversations++),u){let p=o[u];p.conversationStatus=a,l.lastMessageBy==="them"&&(p.lastMessageReceived=p.lastMessageReceived||r),l.lastMessageBy==="me"&&(p.lastMessageSent=p.lastMessageSent||r),p.lastUpdated=r,i.peopleLinked++}}return t||(P(n),de(o)),i}function Wo(e,t,n,o){let s=j(),r=Object.entries(s),i=r.filter(([,l])=>l.conversationStatus==="unanswered_by_us").sort((l,a)=>{let f=l[1].lastSynced||"";return(a[1].lastSynced||"").localeCompare(f)});if(console.log(`
102
+ Total: ${f.length} sent (${p} inbox, ${h} profile), ${u.length} need review, ${m.length} failed`)}function Xo(e){let t={};for(let[s,o]of Object.entries(e)){let n=o.name;n&&(t[n]?o.connectionStatus==="connected"&&t[n].connectionStatus!=="connected"&&(t[n]={url:s,...o}):t[n]={url:s,...o})}return t}function Zo(e,t){let s=j(),o=W(),n=Xo(o),r=new Date().toISOString(),i={newConversations:0,updatedConversations:0,unansweredByUs:0,awaitingReply:0,peopleLinked:0,newPeople:0};for(let l of e){if(!l.name)continue;let a;l.lastMessageBy==="them"?(a="unanswered_by_us",i.unansweredByUs++):l.lastMessageBy==="me"?(a="awaiting_reply",i.awaitingReply++):a="mutual_silence";let u=n[l.name]?.url||null,m=s[l.name];if(m?(m.lastSynced=r,m.lastMessageBy=l.lastMessageBy,m.lastMessagePreview=l.lastMessagePreview||m.lastMessagePreview,m.lastMessageTime=l.lastMessageTime||m.lastMessageTime,m.unread=l.unread,m.conversationStatus||(m.conversationStatus=a),u&&!m.profileUrl&&(m.profileUrl=u),i.updatedConversations++):(s[l.name]={profileUrl:u,lastSynced:r,lastMessageBy:l.lastMessageBy,lastMessagePreview:l.lastMessagePreview||"",lastMessageTime:l.lastMessageTime||"",unread:l.unread||!1,conversationStatus:a,messages:[]},i.newConversations++),u){let p=o[u];p.conversationStatus=a,l.lastMessageBy==="them"&&(p.lastMessageReceived=p.lastMessageReceived||r),l.lastMessageBy==="me"&&(p.lastMessageSent=p.lastMessageSent||r),p.lastUpdated=r,i.peopleLinked++}}return t||(P(s),pe(o)),i}function en(e,t,s,o){let n=j(),r=Object.entries(n),i=r.filter(([,l])=>l.conversationStatus==="unanswered_by_us").sort((l,a)=>{let f=l[1].lastSynced||"";return(a[1].lastSynced||"").localeCompare(f)});if(console.log(`
103
103
  \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` Message Bot Summary (${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"),console.log(` Conversations scanned: ${e.length}`),console.log(` New conversations: ${t.newConversations}`),console.log(` Updated conversations: ${t.updatedConversations}`),console.log(` Linked to people.json: ${t.peopleLinked}`),t.newPeople>0&&console.log(` New people (non-contact): ${t.newPeople}`),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"),console.log(` This scan \u2014 unanswered: ${t.unansweredByUs}`),console.log(` This scan \u2014 awaiting: ${t.awaitingReply}`),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"),console.log(` Total in DB: ${r.length} conversations`),console.log(` Total unanswered: ${i.length}`),i.length>0){let a=i.slice(0,15);console.log(`
104
104
  \u26A1 ACTION NEEDED \u2014 ${i.length} unanswered messages:
105
105
  `);for(let[f,u]of a){let m=f.padEnd(30),p=(u.lastMessageTime||"").padEnd(10),h=u.lastMessagePreview?u.lastMessagePreview.slice(0,55)+(u.lastMessagePreview.length>55?"...":""):"";console.log(` ${m} ${p} ${h}`)}i.length>15&&console.log(`
106
106
  ... and ${i.length-15} more. Use --list for full list.`)}else console.log(`
107
- All caught up \u2014 no unanswered messages.`);n&&console.log(`
107
+ All caught up \u2014 no unanswered messages.`);s&&console.log(`
108
108
  [DRY RUN \u2014 nothing written to DB]`),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
109
- `)}async function Ho(){let e=_o();if(e.list){jo();return}if(e.reviewDrafts){await Mo();return}if(e.followUp||e.followUpBatch||e.clearFollowUp){let r=j(),i=0;if(e.clearFollowUp){let l=r[e.clearFollowUp];l?(delete l.followUpNote,delete l.followUpDate,i++,console.log(` \u2713 ${e.clearFollowUp} \u2014 follow-up cleared`)):console.log(` ? ${e.clearFollowUp} \u2014 not found`)}else{let l=e.followUpBatch||[e.followUp];for(let a of l){let f=a.target||a.name,u=a.note||a.text||"",m=a.date||null,p=r[f];p?(p.followUpNote=u,m&&(p.followUpDate=m),i++,console.log(` + ${f} \u2014 follow-up set${m?` for ${m}`:""}: ${u.slice(0,60)}`)):(r[f]={profileUrl:null,lastSynced:new Date().toISOString(),followUpNote:u,followUpDate:m||null,messages:[]},i++,console.log(` + ${f} \u2014 new entry with follow-up${m?` for ${m}`:""}`))}}i>0&&(P(r),console.log(`
109
+ `)}async function tn(){let e=Jo();if(e.list){Wo();return}if(e.reviewDrafts){await Ho();return}if(e.followUp||e.followUpBatch||e.clearFollowUp){let r=j(),i=0;if(e.clearFollowUp){let l=r[e.clearFollowUp];l?(delete l.followUpNote,delete l.followUpDate,i++,console.log(` \u2713 ${e.clearFollowUp} \u2014 follow-up cleared`)):console.log(` ? ${e.clearFollowUp} \u2014 not found`)}else{let l=e.followUpBatch||[e.followUp];for(let a of l){let f=a.target||a.name,u=a.note||a.text||"",m=a.date||null,p=r[f];p?(p.followUpNote=u,m&&(p.followUpDate=m),i++,console.log(` + ${f} \u2014 follow-up set${m?` for ${m}`:""}: ${u.slice(0,60)}`)):(r[f]={profileUrl:null,lastSynced:new Date().toISOString(),followUpNote:u,followUpDate:m||null,messages:[]},i++,console.log(` + ${f} \u2014 new entry with follow-up${m?` for ${m}`:""}`))}}i>0&&(P(r),console.log(`
110
110
  ${i} follow-up(s) updated.
111
111
  `));return}if(e.review||e.reviewBatch){let r=e.reviewBatch||[e.review],i=j(),l=0;for(let a of r){let f=i[a];f?(f.reviewedAtPreview=f.lastMessagePreview||"",l++,console.log(` + ${a} \u2014 marked as reviewed`)):console.log(` ? ${a} \u2014 not found in conversations`)}l>0?(P(i),console.log(`
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: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
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=W(),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=>!le.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
- `),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
119
- `),await Ce(s),await No(s,{full:e.full,max:e.max,verbose:e.verbose,dryRun:e.dryRun})}$e(n,"success")}catch(r){console.error(`
120
- \u2717 Error:`,r.message),e.verbose&&console.error(r.stack),$e(n,"error",null,r.message)}finally{await o.close()}}Ho();
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",s=Qe("messages",t),{browser:o,page:n}=await nt();try{if(e.read)await Yo(n,e.read,e.verbose);else if(e.pushDrafts)await Qo(n,e.dryRun);else if(e.sendBatch)await Ko(n,e.sendBatch,e.dryRun);else if(e.send)await zo(n,e.send.target,e.send.text,e.dryRun);else{let r=e.full?"full":"incremental";console.log(`Mode: ${r} inbox scan
119
+ `),await De(n),await Vo(n,{full:e.full,max:e.max,verbose:e.verbose,dryRun:e.dryRun})}Ee(s,"success")}catch(r){console.error(`
120
+ \u2717 Error:`,r.message),e.verbose&&console.error(r.stack),Ee(s,"error",null,r.message)}finally{await o.close()}}tn();