ilml-plugin-linkedin 1.20.2 → 1.20.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/connect.mjs +51 -51
- package/dist/enrichProfile.mjs +10 -10
- package/dist/enrichProfiles.mjs +34 -35
- package/dist/funnelRunner.mjs +38 -38
- package/dist/messageBot.mjs +74 -75
- package/dist/readPost.mjs +10 -10
- package/dist/run.mjs +58 -59
- package/dist/scout.mjs +38 -39
- package/dist/src/saveLoginState.mjs +4 -4
- package/dist/syncAll.mjs +79 -80
- package/dist/syncConnections.mjs +30 -31
- package/dist/verifyAbout.mjs +18 -19
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +20 -21
- package/dist/visit.mjs +36 -37
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/messageBot.mjs
CHANGED
|
@@ -1,120 +1,119 @@
|
|
|
1
|
-
var
|
|
1
|
+
var eo=Object.defineProperty;var ye=(e,t)=>{for(var o in t)eo(e,o,{get:t[o],enumerable:!0})};import*as ie from"fs";import*as Qt from"readline";var De={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},to={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function fe(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let o=parseInt(t[1],10),n=parseInt(t[2],10),s=t[3].toUpperCase()==="PM";return s&&o!==12&&(o+=12),!s&&o===12&&(o=0),{hours:o,minutes:n}}function _e(e,t){if(!e)return null;let o=e.trim();if(!o)return null;if(t=t||new Date,/^just\s*now$/i.test(o))return t.toISOString();if(/^today\b/i.test(o)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(o)){let l=fe(o),c=new Date(t);return l?c.setHours(l.hours,l.minutes,0,0):c.setHours(0,0,0,0),c.toISOString()}let n=o.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(n){let l=to[n[1].toLowerCase()],c=fe(n[2]||""),d=new Date(t),m=d.getDay()-l;return m<=0&&(m+=7),d.setDate(d.getDate()-m),c?d.setHours(c.hours,c.minutes,0,0):d.setHours(0,0,0,0),d.toISOString()}let s=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=De[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(s[2],10),d=parseInt(s[3],10),u=fe(s[4]||"");return new Date(d,l,c,u?.hours||0,u?.minutes||0,0,0).toISOString()}let r=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=De[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(r[2],10),d=fe(r[3]||""),u=t.getFullYear(),m=new Date(u,l,c,d?.hours||0,d?.minutes||0,0,0);return m>t&&m.setFullYear(u-1),m.toISOString()}let i=o.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=De[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(i[2],10),d=fe(i[3]||""),u=t.getFullYear(),m=new Date(u,l,c,d?.hours||0,d?.minutes||0,0,0);return m>t&&m.setFullYear(u-1),m.toISOString()}return null}async function E(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}async function we(e,t,{timeout:o=45e3,poll:n=1e3,label:s="page"}={}){let r=Date.now();for(;Date.now()-r<o;){try{if(await e.evaluate(l=>!!document.querySelector(l),t)){let l=Date.now()-r;return l>6e3&&console.log(` (waited ${Math.round(l/1e3)}s for LinkedIn to finish loading ${s})`),!0}}catch{}await new Promise(i=>setTimeout(i,n))}return!1}async function tt(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 E(4e3);let n=e.url();if(n.includes("/login")||n.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function ot(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 nt(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 oo}from"@ilivemylife/graph-sdk";var no=await oo();for(let[e,t]of Object.entries(no))process.env[e]===void 0&&(process.env[e]=t);var le=process.env.LINKEDIN_NAME,$=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),de=Object.freeze(new Set([$.DRAFT,$.CONFIRMED,$.NEEDS_REVIEW])),ee=Object.freeze(new Set([$.DRAFT,$.CONFIRMED,$.REJECTED,$.NEEDS_REVIEW]));import"dotenv/config";import*as j from"fs";import*as N from"path";import{fileURLToPath as so}from"url";var ro=so(import.meta.url),io=N.dirname(N.dirname(ro)),z=process.env.DATA_DIR?N.resolve(process.env.DATA_DIR,"collected-profiles"):N.join(io,"collected-profiles"),Ie=N.join(z,"people.json"),Xn=N.join(z,"jobs.json"),es=N.join(z,"quota.json"),Se=N.join(z,"conversations.json"),ts=N.join(z,"sync-state.json"),os=N.join(z,"application-questions.json"),ns=N.join(z,"profile-history"),st=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},ss=st(process.env.CONNECT_MAX_DAILY,20),rs=st(process.env.CONNECT_MAX_WEEKLY,100),ce=null,lo=null,co=null,te=null,ao=null,uo=null;function rt(){ce=null,lo=null,co=null,te=null,ao=null,uo=null}function ve(){j.existsSync(z)||j.mkdirSync(z,{recursive:!0})}function Re(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";j.writeFileSync(n,o);for(let s=0;s<3;s++)try{j.renameSync(n,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 it(e,t){if(!j.existsSync(e))return null;try{let o=JSON.parse(j.readFileSync(e,"utf-8"));try{j.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${N.resolve(e)}`);let n=e+".backup";if(j.existsSync(n))try{let s=JSON.parse(j.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{j.copyFileSync(n,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{j.copyFileSync(e,e+".corrupted")}catch{}return null}}function V(){return ce||(ve(),ce=it(Ie,"people.json")||{},ce)}function be(e){ve(),ce=e;try{Re(Ie,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${N.resolve(Ie)}`)}}function M(){return te||(ve(),te=it(Se,"conversations.json")||{},fo(te),te)}function fo(e){let t=0;for(let o of Object.values(e)){if(!(o.draftStatus!==void 0||o.draftPreparedAt!==void 0))continue;let s=(o.messages||[]).find(r=>r.status==="draft");s&&o.draftStatus&&o.draftStatus!=="pending"&&(s.status=o.draftStatus),delete o.draftStatus,delete o.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Re(Se,e)}catch{}}}function L(e){ve(),te=e;try{Re(Se,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${N.resolve(Se)}`)}}import"dotenv/config";import*as B from"fs";import*as Q from"path";import{fileURLToPath as wo}from"url";import"dotenv/config";import{createGraphClient as po,resolveToken as mo}from"@ilivemylife/graph-sdk";import{config as go}from"dotenv";go();var lt=mo()||process.env.TOKEN;lt||(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
|
|
5
|
+
`),process.exit(1));var ct=po({token:lt});function ho(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),n=t%60;return n?`${o}m ${n}s`:`${o}m`}function yo({scriptName:e,mode:t,status:o,error:n,duration:s}){let r=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=s?` ${ho(s)}`:"",c=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",d=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${d} \u2014 ${c} \u2014 ${i}${l}`}async function at({scriptName:e,mode:t,status:o,summaryLines:n,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let c=`**${yo({scriptName:e,mode:t,status:o,error:s,duration:r})}**
|
|
6
6
|
|
|
7
7
|
${n.join(`
|
|
8
|
-
`)}`;try{await tt.addMessage(i,c)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var ro=so(import.meta.url),io=Q.dirname(Q.dirname(ro)),xe=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"collected-profiles"):Q.join(io,"collected-profiles"),De=Q.join(xe,"run-log.json");function lo(e,t){let s=JSON.stringify(t,null,2),n=e+".tmp";B.writeFileSync(n,s);for(let o=0;o<3;o++)try{B.renameSync(n,e);return}catch(r){if(o<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function nt(){try{if(!B.existsSync(De))return{runs:[]};let e=JSON.parse(B.readFileSync(De,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function st(e){B.existsSync(xe)||B.mkdirSync(xe,{recursive:!0});try{lo(De,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function rt(e,t="default"){let s=nt();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 n=new Date,o={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};s.runs.push(o);let r=Date.now()-30*24*60*60*1e3;return s.runs=s.runs.filter(i=>new Date(i.timestamp).getTime()>r),st(s),{script:e,mode:t,startTime:n.getTime(),runIndex:s.runs.length-1}}function _e(e,t,s=null,n=null){if(!e)return;let o=null;try{let i=nt(),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=n,o=l.duration;else{let c=i.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());c&&(c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=s,c.error=n,o=c.duration)}st(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";ot({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:o??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import po from"puppeteer";import{addExtra as mo}from"puppeteer-extra";import go from"puppeteer-extra-plugin-stealth";import Y from"fs";import Z from"path";var co="cookies.json";function it(){let e=process.env.ILML_SCOPE_DIR;return e?Z.join(e,"plugins-state","linkedin","cookies.json"):co}function lt(){let e=it();if(!Y.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=Y.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.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}function ct(){return Y.existsSync(it())}function ao(){let e=process.env.ILML_SCOPE_DIR;return e?Z.join(e,"plugins-state","linkedin"):"."}function at(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function uo(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?at(t[1]):"default"}function ut(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),Z.resolve(t);let s=at(e||uo()),n=Z.join(ao(),"chrome-profile",s);return Y.existsSync(n)||Y.mkdirSync(n,{recursive:!0}),Z.resolve(n)}var ft=".ilml-seeded";function dt(e){return!Y.existsSync(Z.join(e,ft))}function pt(e){try{Y.writeFileSync(Z.join(e,ft),new Date().toISOString())}catch{}}function mt(e){let t=0;for(let s of["SingletonLock","SingletonCookie","SingletonSocket"])try{Y.rmSync(Z.join(e,s),{force:!0}),t++}catch{}return t}var fo={headless:!1,defaultViewport:null,protocolTimeout:3e5};async function gt(e,t={}){let s=ut(),n={...fo,...t,userDataDir:s},o;try{o=await e.launch(n)}catch{mt(s);try{o=await e.launch(n)}catch(i){throw new Error(`Could not open the LinkedIn automation Chrome profile at ${s}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${i.message})`)}}return{browser:o,profileDir:s,needsSeed:dt(s)}}async function ht(e,t){if(!t||!t.needsSeed)return!1;if(!ct())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...lt()),pt(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var St=mo(po);St.use(go());async function vt(){let{browser:e,profileDir:t,needsSeed:s}=await gt(St),n=async()=>{console.log(`
|
|
9
|
-
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",n),process.on("SIGTERM",n);let o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await ht(o,{profileDir:t,needsSeed:s}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function Ie(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await E(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login (not logged in, or session expired). Run: ilml linkedin 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 E(3e3)}console.log(" Inbox loaded.")}async function bt(e){let t=await e.evaluate(()=>{let s=document.querySelectorAll(".msg-conversation-listitem"),n=[];for(let o of s){let i=o.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let c=o.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(c)||/^\s*Promoted\b/i.test(c))continue;let u=o.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",p=o.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||o.querySelector(".msg-conversation-card__unread-count")!==null,m,h;if(c.startsWith("You:"))m="me",h=c.slice(4).trim();else{let a=i.split(" ")[0];if(c.startsWith(i+":")||c.startsWith(a+":")){m="them";let g=c.indexOf(":");h=c.slice(g+1).trim()}else m="them",h=c}let d=o.getBoundingClientRect();n.push({name:i,lastMessagePreview:h,lastMessageTime:u,unread:p,lastMessageBy:m,x:d.x+d.width/2,y:d.y+d.height/2})}return n});for(let s of t)s.lastMessageTime=Ae(s.lastMessageTime)||s.lastMessageTime;return t}async function $t(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let n of t){let o=document.querySelector(n);if(o&&o.scrollHeight>o.clientHeight)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight}}let s=document.querySelector(".msg-conversation-listitem");if(s){let n=s.parentElement;for(;n;){if(n.scrollHeight>n.clientHeight+10)return n.scrollBy(0,600),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight};n=n.parentElement}}return null})}async function ho(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 o of s){let r=document.querySelector(o);if(r){let i=r.textContent?.trim()?.replace(/\s+/g," ");if(i&&i.length>1&&i.length<100&&!t.test(i))return i}}let n=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let o of n){let r=o.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function yt(e,t){let s=await ho(e);if(!s)return{match:!1,headerName:null};let n=t.split(" ")[0].toLowerCase(),o=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=s.toLowerCase();return{match:r.includes(n)||o.some(l=>r.includes(l)),headerName:s}}async function Te(e,t){let s=t.split(" ")[0],n=8e3,o=500,r=0;for(;r<n;){let{match:c,headerName:f}=await yt(e,t);if(c)return await E(500),{verified:!0,headerName:f};let u=await e.evaluate(()=>{let p=document.querySelectorAll(".msg-s-message-group__name"),m=Array.from(p).map(d=>d.textContent?.trim()).filter(Boolean),h=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:m,msgCount:h}});if(u.msgCount>0&&u.allSenders.some(m=>m.toLowerCase().includes(s.toLowerCase())))return await E(300),{verified:!0,headerName:s};await E(o),r+=o}let{match:i,headerName:l}=await yt(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function yo(e){let s=0,n=0;for(let o=0;o<50;o++){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 E(800),r.msgCount===s){if(n++,n>=3)break}else n=0;s=r.msgCount}}async function oe(e,{scrollUp:t=!0}={}){t&&await yo(e);let s=await e.evaluate(()=>{let n=[],o="",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 n;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 p=u.getAttribute("data-event-urn");if(!p)return null;let m=p.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!m)return null;try{let d=atob(m[1]).match(/^(\d{13})/);if(!d)return null;let a=Number(d[1]);if(a>14200704e5&&a<20512224e5)return a}catch{}return null}let c="";function f(u,p,m){let h=l(u),a=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 S=h?new Date(h).toISOString():m?`${m} ${a}`.trim():a;return{sender:p,text:y,time:S}}for(let u of i){let p=u.querySelector("time.msg-s-message-list__time-heading");p&&(c=p.textContent?.trim()||c);let m=u.querySelectorAll(".msg-s-message-group");if(m.length>0)for(let h of m){let d=h.querySelector(".msg-s-message-group__name");d&&(o=d.textContent?.trim()||o);let a=o||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let S=f(y,a,c);S&&n.push(S)}}else{let h=u.querySelectorAll(".msg-s-event-listitem");for(let d of h){let a=d.querySelector(".msg-s-message-group__name");a&&(o=a.textContent?.trim()||o);let y=f(d,o||"Unknown",c);y&&n.push(y)}}}if(n.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let p of u){let m=p.textContent?.trim();m&&n.push({sender:"",text:m,time:""})}}return n});for(let n of s)(!n.time||!/^\d{4}-\d{2}-\d{2}T/.test(n.time))&&(n.time=Ae(n.time)||n.time);return s}function ae(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function de(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let s=m=>ae(m.sender)+"||"+ae(m.text),n=new Set(t.map(s)),o=new Set(e.map(s)),r=e.filter(m=>ee.has(m.status)?!1:!n.has(s(m))),i=t.filter(m=>!o.has(s(m))),l=t.filter(m=>o.has(s(m))),c=e.filter(m=>ee.has(m.status)),f=[...r,...l,...i],u=[];for(let m of f){let h=ae(m.text),d=ae(m.sender),a=!1;for(let g=0;g<u.length;g++){let y=u[g];if(ae(y.sender)!==d)continue;let S=ae(y.text);if(h.length>S.length&&h.endsWith(S)){a=!0;break}if(S.length>h.length&&S.endsWith(h)){u[g]=m,a=!0;break}}a||u.push(m)}return[...u,...c]}async function we(e,t){let s=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let c of l)if(c.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let p=c.getBoundingClientRect();if(p.height>0)return{x:p.x+p.width/2,y:p.y+p.height/2}}return null},t);if(s){await e.mouse.click(s.x,s.y),await E(3e3);let i=await Te(e,t);if(i.verified)return i}let n=ze(t),o=n!==t?[t,n]:[t];for(let i of o)if(await wt(e,i,t)){let c=await Te(e,t);if(c.verified)return c}let r=Ke(n);if(r!==n&&r.length>0&&await wt(e,r,t,{requireUnique:!0})){let l=await Te(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function wt(e,t,s,n={}){let{requireUnique:o=!1}=n,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await E(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await E(300),await r.type(t,{delay:30}),await E(500),await e.keyboard.press("Enter"),await E(3500);let i=await e.evaluate((l,c)=>{let f=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),p=document.querySelectorAll(".msg-conversation-listitem"),m=[],h=[];for(let a of p){let y=a.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(f)){let C=a.getBoundingClientRect();if(C.height>0){let v=y.includes(",")||/\d+ other/.test(y),x=S===u?3:S.includes(u)?2:1,R={text:y,isGroup:v,score:x,x:C.x+C.width/2,y:C.y+C.height/2};v?h.push(R):m.push(R)}}}m.sort((a,g)=>g.score-a.score);let d=[...m,...h];return c&&d.length!==1?null:m[0]||h[0]||null},s,o);return i?(o&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function kt(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await E(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 E(1e3))}import"dotenv/config";import*as w from"fs";import*as Le from"os";import*as _ from"path";import{fileURLToPath as zo}from"url";var je={};me(je,{NAME:()=>So,VERSION:()=>wo,up:()=>$o});import*as q from"fs";import*as Se from"path";var wo=1,So="normalize-jobs-and-questions",vo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],bo=50;function Re(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function Oe(e,t){let s=JSON.stringify(t,null,2),n=e+".tmp";try{q.writeFileSync(n,s)}catch(o){try{q.unlinkSync(n)}catch{}throw o}try{q.renameSync(n,e)}catch(o){try{q.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${e} (${o.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=o.code,r}throw o}}async function $o(e,t){let s=Se.join(e,"jobs.json"),n=Se.join(t,"scouted-jobs.json"),o=Se.join(e,"application-questions.json"),r=Re(s)||{},i=Re(n)||{},l=0,c=[];for(let u of Object.keys(r)){if(!i[u])continue;let p=i[u],m=r[u];for(let h of vo)p[h]!=null&&m[h]==null&&(m[h]=p[h]);c.push(u),l++}l>0?(Oe(s,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Re(o);if(f&&Array.isArray(f.applications)){let u={},p=0;for(let m of f.applications){let h=m.jobId||"unknown";u[h]||(u[h]={applications:[]});let d=(m.questions||[]).map(a=>{let g={type:a.type||"input",question:a.question||"",answer:a.answer||""};return a.options&&(a.options.length<=bo?g.options=a.options:(g.optionsOmitted=!0,p++)),a.page&&(g.page=a.page),a.wasPreFilled&&(g.wasPreFilled=!0),a.wasRetry&&(g.wasRetry=!0),g});u[h].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||d.length,questions:d})}Oe(o,u),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} 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(c.length>0){for(let u of c)delete i[u];Oe(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ne={};me(Ne,{NAME:()=>Ao,VERSION:()=>ko,up:()=>xo});import*as J from"fs";import*as At from"path";var ko=2,Ao="reset-unread-flags";function Co(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function Eo(e,t){let s=JSON.stringify(t,null,2),n=e+".tmp";try{J.writeFileSync(n,s)}catch(o){try{J.unlinkSync(n)}catch{}throw o}try{J.renameSync(n,e)}catch(o){try{J.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${e} (${o.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=o.code,r}throw o}}async function xo(e){let t=At.join(e,"conversations.json"),s=Co(t);if(!s){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let o of Object.keys(s))s[o].unread===!0&&(s[o].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Eo(t,s),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Me={};me(Me,{NAME:()=>_o,VERSION:()=>Do,up:()=>jo});import*as W from"fs";import*as Ct from"path";var Do=3,_o="recompute-last-message-by",To=new Set(["draft","confirmed","rejected","needs_review"]);function Io(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function Ro(e,t){let s=JSON.stringify(t,null,2),n=e+".tmp";try{W.writeFileSync(n,s)}catch(o){try{W.unlinkSync(n)}catch{}throw o}try{W.renameSync(n,e)}catch(o){try{W.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${e} (${o.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=o.code,r}throw o}}function Oo(e,t){if(!e||e.length===0)return"them";let s=e.filter(r=>!To.has(r.status));if(s.length===0)return"them";let n=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),o=n.length>0?n:[...s].reverse();for(let r of o){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function jo(e){let t=Ct.join(e,"conversations.json"),s=Io(t);if(!s){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.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 o=0,r=0,i=0;for(let l of Object.keys(s)){let c=s[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let f=Array.isArray(c.messages)?c.messages:[],u=Oo(f,n),p=u==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==u&&i++,c.lastMessageBy=u,c.conversationStatus=p,o++}if(o===0){console.log(" No conversations to recompute.");return}Ro(t,s),console.log(` Recomputed lastMessageBy + conversationStatus on ${o} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Fe={};me(Fe,{NAME:()=>Mo,VERSION:()=>No,up:()=>Uo});import*as H from"fs";import*as Et from"path";var No=4,Mo="split-connection-timestamps",Fo=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Po(e){if(!H.existsSync(e))return null;let t=H.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Lo(e,t){let s=JSON.stringify(t,null,2),n=e+".tmp";try{H.writeFileSync(n,s)}catch(o){try{H.unlinkSync(n)}catch{}throw o}try{H.renameSync(n,e)}catch(o){try{H.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=new Error(`File locked: ${e} (${o.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=o.code,r}throw o}}async function Uo(e){let t=Et.join(e,"people.json"),s=Po(t);if(!s||typeof s!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,o=0;for(let r of Object.keys(s)){let i=s[r];!i||typeof i!="object"||(o++,Fo.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${o} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Lo(t,s),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${o} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as U from"path";import{fileURLToPath as Bo}from"url";var qo=Bo(import.meta.url),Jo=U.dirname(U.dirname(qo)),pe=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(Jo,"market-research"),Ss=U.join(pe,"scouted-jobs.json"),vs=U.join(pe,"discovered-people.json"),bs=U.join(pe,"visit-log.json"),$s=U.join(pe,"companies.json"),ks=U.join(pe,"job-decisions.json");function xt(){Wo=null,Ho=null,Vo=null,Yo=null,Go=null}var Wo=null;var Ho=null;var Vo=null;var Yo=null;var Go=null;var Ko=zo(import.meta.url),Qo=_.dirname(Ko),Zo=_.dirname(_.dirname(Qo));function Xo(e){return e&&(e==="~"?Le.homedir():e.startsWith("~/")||e.startsWith("~\\")?_.join(Le.homedir(),e.slice(2)):e)}var G=process.env.DATA_DIR?_.resolve(Xo(process.env.DATA_DIR)):Zo,se=_.join(G,"collected-profiles"),re=_.join(G,"market-research"),F=_.join(G,".schema-version"),Dt=[_.join(se,".schema-version"),_.join(re,".schema-version")],X=4,K=[{version:1,module:je},{version:2,module:Ne},{version:3,module:Me},{version:4,module:Fe}];(function(){K.sort((n,o)=>n.version-o.version);let t=new Set;for(let n of K){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let o=n.module;if(!o||typeof o.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(o.VERSION!==void 0&&o.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${o.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let s=K.length?K[K.length-1].version:0;if(s!==X)throw new Error(`MIGRATION_REGISTRY: highest version v${s} but CURRENT_SCHEMA_VERSION=${X}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<K.length;n++){let o=n+1;if(K[n].version!==o)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${o} at position ${n} but found v${K[n].version}`)}})();function Rt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
8
|
+
`)}`;try{await ct.addMessage(i,c)}catch(d){console.error(`[runReport] Failed to post end-of-session message: ${d.message}`)}}var So=wo(import.meta.url),vo=Q.dirname(Q.dirname(So)),Te=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"collected-profiles"):Q.join(vo,"collected-profiles"),Oe=Q.join(Te,"run-log.json");function bo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";B.writeFileSync(n,o);for(let s=0;s<3;s++)try{B.renameSync(n,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 ut(){try{if(!B.existsSync(Oe))return{runs:[]};let e=JSON.parse(B.readFileSync(Oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ft(e){B.existsSync(Te)||B.mkdirSync(Te,{recursive:!0});try{bo(Oe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function dt(e,t="default"){let o=ut();for(let i of o.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,s={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(i=>new Date(i.timestamp).getTime()>r),ft(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function je(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=ut(),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=o,l.error=n,s=l.duration;else{let c=i.runs.find(d=>d.script===e.script&&d.status==="running"&&d.timestamp===new Date(e.startTime).toISOString());c&&(c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=n,s=c.duration)}ft(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";at({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:n,duration:s??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import Ro from"puppeteer";import{addExtra as To}from"puppeteer-extra";import Oo from"puppeteer-extra-plugin-stealth";import G from"fs";import Z from"path";var $o="cookies.json";function pt(){let e=process.env.ILML_SCOPE_DIR;return e?Z.join(e,"plugins-state","linkedin","cookies.json"):$o}function mt(){let e=pt();if(!G.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=G.readFileSync(e,"utf-8")}catch(n){throw new Error(`Failed to read cookies at ${e}: ${n.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function gt(){return G.existsSync(pt())}function ko(){let e=process.env.ILML_SCOPE_DIR;return e?Z.join(e,"plugins-state","linkedin"):"."}function ht(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Ao(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?ht(t[1]):"default"}function yt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return G.existsSync(t)||G.mkdirSync(t,{recursive:!0}),Z.resolve(t);let o=ht(e||Ao()),n=Z.join(ko(),"chrome-profile",o);return G.existsSync(n)||G.mkdirSync(n,{recursive:!0}),Z.resolve(n)}var wt=".ilml-seeded";function St(e){return!G.existsSync(Z.join(e,wt))}function vt(e){try{G.writeFileSync(Z.join(e,wt),new Date().toISOString())}catch{}}function bt(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{G.rmSync(Z.join(e,o),{force:!0}),t++}catch{}return t}import Ne from"fs";import Co from"path";var Eo={headless:!1,defaultViewport:null,protocolTimeout:3e5},me=new Set,$t=!1;async function $e(){let e=[...me].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});me.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function xo(){if($t)return;$t=!0;let e=t=>async()=>{await $e(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await $e(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await $e(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await $e(),process.exit(0))}),process.on("exit",()=>{for(let t of me)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Me(e){return Co.join(e,".ilml-browser-session.json")}function Et(e,t={}){try{Ne.writeFileSync(Me(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Do(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();Et(e,o?{wsEndpoint:o}:{})}catch{}}function _o(e){let t=xt(e);t&&t.ownerPid===process.pid&&pe(e)}function pe(e){try{Ne.rmSync(Me(e),{force:!0})}catch{}}function xt(e){try{return JSON.parse(Ne.readFileSync(Me(e),"utf-8"))}catch{return null}}function kt(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function At(e,t,o){let n,s=new Promise(i=>{n=setTimeout(()=>i(o),t)}),r=Promise.resolve(e).then(i=>(clearTimeout(n),i),i=>{throw clearTimeout(n),i});return Promise.race([r,s])}async function Ct(e,t,{probeTimeoutMs:o=4e3}={}){let n=xt(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&kt(n.ownerPid)?"live":(pe(t),"free");let s=Symbol("timeout"),r=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await At(r,o,s);if(i===s)return r.then(c=>{if(c)try{c.disconnect()}catch{}}),"live";if(!i)return pe(t),"free";if(kt(n.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await At(i.close().then(()=>!0).catch(()=>!1),o,!1))return pe(t),"free";try{i.disconnect()}catch{}return"live"}function Io(e,t){e&&(xo(),me.add(e),e.on("disconnected",()=>{me.delete(e),t&&pe(t)}))}async function Dt(e,t={}){let o=yt(),n={...Eo,...t,userDataDir:o},s=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ct(e,o)==="live")throw new Error(s);Et(o);let r;try{r=await e.launch(n)}catch{if(await Ct(e,o)==="live")throw new Error(s);bt(o);try{r=await e.launch(n)}catch(l){throw _o(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${l.message})`)}}return Io(r,o),Do(o,r),{browser:r,profileDir:o,needsSeed:St(o)}}async function _t(e,t){if(!t||!t.needsSeed)return!1;if(!gt())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...mt()),vt(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Tt=To(Ro);Tt.use(Oo());async function Ot(){let{browser:e,profileDir:t,needsSeed:o}=await Dt(Tt),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await _t(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}async function Pe(e){if(await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),!await we(e,".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:45e3,label:"inbox"})){let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Redirected to login (not logged in, or session expired). Run: ilml linkedin login");console.warn(" Inbox container not found via known selectors, proceeding..."),await E(3e3)}console.log(" Inbox loaded.")}async function jt(e){let t=await e.evaluate(()=>{let o=document.querySelectorAll(".msg-conversation-listitem"),n=[];for(let s of o){let i=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let c=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(c)||/^\s*Promoted\b/i.test(c))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(c.startsWith("You:"))p="me",h=c.slice(4).trim();else{let a=i.split(" ")[0];if(c.startsWith(i+":")||c.startsWith(a+":")){p="them";let g=c.indexOf(":");h=c.slice(g+1).trim()}else p="them",h=c}let f=s.getBoundingClientRect();n.push({name:i,lastMessagePreview:h,lastMessageTime:u,unread:m,lastMessageBy:p,x:f.x+f.width/2,y:f.y+f.height/2})}return n});for(let o of t)o.lastMessageTime=_e(o.lastMessageTime)||o.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 n of t){let s=document.querySelector(n);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let o=document.querySelector(".msg-conversation-listitem");if(o){let n=o.parentElement;for(;n;){if(n.scrollHeight>n.clientHeight+10)return n.scrollBy(0,600),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight};n=n.parentElement}}return null})}async function jo(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,o=['.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 o){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 n=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of n){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 It(e,t){let o=await jo(e);if(!o)return{match:!1,headerName:null};let n=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=o.toLowerCase();return{match:r.includes(n)||s.some(l=>r.includes(l)),headerName:o}}async function Fe(e,t){let o=t.split(" ")[0],n=8e3,s=500,r=0;for(;r<n;){let{match:c,headerName:d}=await It(e,t);if(c)return await E(500),{verified:!0,headerName:d};let u=await e.evaluate(()=>{let m=document.querySelectorAll(".msg-s-message-group__name"),p=Array.from(m).map(f=>f.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(o.toLowerCase())))return await E(300),{verified:!0,headerName:o};await E(s),r+=s}let{match:i,headerName:l}=await It(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function No(e){let o=0,n=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 d=document.querySelector(".msg-overlay-conversation-bubble");d&&(i=d.querySelector(".msg-s-message-list-container")||d.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 E(800),r.msgCount===o){if(n++,n>=3)break}else n=0;o=r.msgCount}}async function oe(e,{scrollUp:t=!0}={}){t&&await No(e);let o=await e.evaluate(()=>{let n=[],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 n;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 f=atob(p[1]).match(/^(\d{13})/);if(!f)return null;let a=Number(f[1]);if(a>14200704e5&&a<20512224e5)return a}catch{}return null}let c="";function d(u,m,p){let h=l(u),a=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} ${a}`.trim():a;return{sender:m,text:y,time:v}}for(let u of i){let m=u.querySelector("time.msg-s-message-list__time-heading");m&&(c=m.textContent?.trim()||c);let p=u.querySelectorAll(".msg-s-message-group");if(p.length>0)for(let h of p){let f=h.querySelector(".msg-s-message-group__name");f&&(s=f.textContent?.trim()||s);let a=s||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let v=d(y,a,c);v&&n.push(v)}}else{let h=u.querySelectorAll(".msg-s-event-listitem");for(let f of h){let a=f.querySelector(".msg-s-message-group__name");a&&(s=a.textContent?.trim()||s);let y=d(f,s||"Unknown",c);y&&n.push(y)}}}if(n.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let m of u){let p=m.textContent?.trim();p&&n.push({sender:"",text:p,time:""})}}return n});for(let n of o)(!n.time||!/^\d{4}-\d{2}-\d{2}T/.test(n.time))&&(n.time=_e(n.time)||n.time);return o}function ae(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function ge(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let o=p=>ae(p.sender)+"||"+ae(p.text),n=new Set(t.map(o)),s=new Set(e.map(o)),r=e.filter(p=>ee.has(p.status)?!1:!n.has(o(p))),i=t.filter(p=>!s.has(o(p))),l=t.filter(p=>s.has(o(p))),c=e.filter(p=>ee.has(p.status)),d=[...r,...l,...i],u=[];for(let p of d){let h=ae(p.text),f=ae(p.sender),a=!1;for(let g=0;g<u.length;g++){let y=u[g];if(ae(y.sender)!==f)continue;let v=ae(y.text);if(h.length>v.length&&h.endsWith(v)){a=!0;break}if(v.length>h.length&&v.endsWith(h)){u[g]=p,a=!0;break}}a||u.push(p)}return[...u,...c]}async function ke(e,t){let o=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let c of l)if(c.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let m=c.getBoundingClientRect();if(m.height>0)return{x:m.x+m.width/2,y:m.y+m.height/2}}return null},t);if(o){await e.mouse.click(o.x,o.y),await E(3e3);let i=await Fe(e,t);if(i.verified)return i}let n=ot(t),s=n!==t?[t,n]:[t];for(let i of s)if(await Rt(e,i,t)){let c=await Fe(e,t);if(c.verified)return c}let r=nt(n);if(r!==n&&r.length>0&&await Rt(e,r,t,{requireUnique:!0})){let l=await Fe(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Rt(e,t,o,n={}){let{requireUnique:s=!1}=n,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await E(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await E(300),await r.type(t,{delay:30}),await E(500),await e.keyboard.press("Enter"),await E(3500);let i=await e.evaluate((l,c)=>{let d=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),m=document.querySelectorAll(".msg-conversation-listitem"),p=[],h=[];for(let a of m){let y=a.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",v=y.toLowerCase();if(v.includes(d)){let C=a.getBoundingClientRect();if(C.height>0){let b=y.includes(",")||/\d+ other/.test(y),A=v===u?3:v.includes(u)?2:1,D={text:y,isGroup:b,score:A,x:C.x+C.width/2,y:C.y+C.height/2};b?h.push(D):p.push(D)}}}p.sort((a,g)=>g.score-a.score);let f=[...p,...h];return c&&f.length!==1?null:p[0]||h[0]||null},o,s);return i?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function Mt(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await E(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 E(1e3))}import"dotenv/config";import*as S from"fs";import*as Ve from"os";import*as _ from"path";import{fileURLToPath as mn}from"url";var Be={};ye(Be,{NAME:()=>Fo,VERSION:()=>Mo,up:()=>Uo});import*as q from"fs";import*as Ae from"path";var Mo=1,Fo="normalize-jobs-and-questions",Po=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Lo=50;function Le(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function Ue(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{q.writeFileSync(n,o)}catch(s){try{q.unlinkSync(n)}catch{}throw s}try{q.renameSync(n,e)}catch(s){try{q.unlinkSync(n)}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 Uo(e,t){let o=Ae.join(e,"jobs.json"),n=Ae.join(t,"scouted-jobs.json"),s=Ae.join(e,"application-questions.json"),r=Le(o)||{},i=Le(n)||{},l=0,c=[];for(let u of Object.keys(r)){if(!i[u])continue;let m=i[u],p=r[u];for(let h of Po)m[h]!=null&&p[h]==null&&(p[h]=m[h]);c.push(u),l++}l>0?(Ue(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let d=Le(s);if(d&&Array.isArray(d.applications)){let u={},m=0;for(let p of d.applications){let h=p.jobId||"unknown";u[h]||(u[h]={applications:[]});let f=(p.questions||[]).map(a=>{let g={type:a.type||"input",question:a.question||"",answer:a.answer||""};return a.options&&(a.options.length<=Lo?g.options=a.options:(g.optionsOmitted=!0,m++)),a.page&&(g.page=a.page),a.wasPreFilled&&(g.wasPreFilled=!0),a.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||f.length,questions:f})}Ue(s,u),console.log(` Phase 2: Rekeyed ${d.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} questions`)}else d&&!d.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let u of c)delete i[u];Ue(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var qe={};ye(qe,{NAME:()=>qo,VERSION:()=>Bo,up:()=>Ho});import*as J from"fs";import*as Ft from"path";var Bo=2,qo="reset-unread-flags";function Jo(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function Wo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{J.writeFileSync(n,o)}catch(s){try{J.unlinkSync(n)}catch{}throw s}try{J.renameSync(n,e)}catch(s){try{J.unlinkSync(n)}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 Ho(e){let t=Ft.join(e,"conversations.json"),o=Jo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let s of Object.keys(o))o[s].unread===!0&&(o[s].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Wo(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Je={};ye(Je,{NAME:()=>Go,VERSION:()=>Vo,up:()=>Zo});import*as W from"fs";import*as Pt from"path";var Vo=3,Go="recompute-last-message-by",Yo=new Set(["draft","confirmed","rejected","needs_review"]);function zo(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function Ko(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{W.writeFileSync(n,o)}catch(s){try{W.unlinkSync(n)}catch{}throw s}try{W.renameSync(n,e)}catch(s){try{W.unlinkSync(n)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Qo(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!Yo.has(r.status));if(o.length===0)return"them";let n=o.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=n.length>0?n:[...o].reverse();for(let r of s){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Zo(e){let t=Pt.join(e,"conversations.json"),o=zo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let l of Object.keys(o)){let c=o[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,r++);let d=Array.isArray(c.messages)?c.messages:[],u=Qo(d,n),m=u==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==u&&i++,c.lastMessageBy=u,c.conversationStatus=m,s++}if(s===0){console.log(" No conversations to recompute.");return}Ko(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var We={};ye(We,{NAME:()=>en,VERSION:()=>Xo,up:()=>sn});import*as H from"fs";import*as Lt from"path";var Xo=4,en="split-connection-timestamps",tn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function on(e){if(!H.existsSync(e))return null;let t=H.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function nn(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{H.writeFileSync(n,o)}catch(s){try{H.unlinkSync(n)}catch{}throw s}try{H.renameSync(n,e)}catch(s){try{H.unlinkSync(n)}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 sn(e){let t=Lt.join(e,"people.json"),o=on(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,s=0;for(let r of Object.keys(o)){let i=o[r];!i||typeof i!="object"||(s++,tn.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}nn(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as U from"path";import{fileURLToPath as rn}from"url";var ln=rn(import.meta.url),cn=U.dirname(U.dirname(ln)),he=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(cn,"market-research"),Ls=U.join(he,"scouted-jobs.json"),Us=U.join(he,"discovered-people.json"),Bs=U.join(he,"visit-log.json"),qs=U.join(he,"companies.json"),Js=U.join(he,"job-decisions.json");function Ut(){an=null,un=null,fn=null,dn=null,pn=null}var an=null;var un=null;var fn=null;var dn=null;var pn=null;var gn=mn(import.meta.url),hn=_.dirname(gn),yn=_.dirname(_.dirname(hn));function wn(e){return e&&(e==="~"?Ve.homedir():e.startsWith("~/")||e.startsWith("~\\")?_.join(Ve.homedir(),e.slice(2)):e)}var Y=process.env.DATA_DIR?_.resolve(wn(process.env.DATA_DIR)):yn,se=_.join(Y,"collected-profiles"),re=_.join(Y,"market-research"),F=_.join(Y,".schema-version"),Bt=[_.join(se,".schema-version"),_.join(re,".schema-version")],X=4,K=[{version:1,module:Be},{version:2,module:qe},{version:3,module:Je},{version:4,module:We}];(function(){K.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of K){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let s=n.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=K.length?K[K.length-1].version:0;if(o!==X)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${X}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<K.length;n++){let s=n+1;if(K[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${K[n].version}`)}})();function Ht(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
10
9
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
11
|
-
`),process.exit(1));try{
|
|
12
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
13
|
-
`),process.exit(1))}let e;try{e=
|
|
14
|
-
[FATAL] DATA_DIR (${
|
|
10
|
+
`),process.exit(1));try{S.mkdirSync(Y,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
11
|
+
[FATAL] Cannot create DATA_DIR (${Y}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
12
|
+
`),process.exit(1))}let e;try{e=S.statSync(Y)}catch(t){console.error(`
|
|
13
|
+
[FATAL] DATA_DIR (${Y}) is not accessible: ${t.message}
|
|
15
14
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
16
|
-
[FATAL] DATA_DIR (${
|
|
17
|
-
`),process.exit(1));for(let t of[se,re]){let
|
|
15
|
+
[FATAL] DATA_DIR (${Y}) 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.
|
|
16
|
+
`),process.exit(1));for(let t of[se,re]){let o;try{o=S.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
|
|
18
17
|
[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.
|
|
19
|
-
`),process.exit(1))}}var ne=_.join(
|
|
18
|
+
`),process.exit(1))}}var ne=_.join(Y,".migration-lock");function Sn(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return S.writeFileSync(ne,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(S.readFileSync(ne,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let n=!1;try{process.kill(t.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!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)}n&&r<s&&(console.error(`
|
|
20
19
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${ne}
|
|
21
20
|
`),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.
|
|
22
|
-
`),process.exit(1)),n&&r>=
|
|
21
|
+
`),process.exit(1)),n&&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 o=ne+".tmp";try{return S.writeFileSync(o,e),S.renameSync(o,ne),!0}catch(n){try{S.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function Ge(){try{if(JSON.parse(S.readFileSync(ne,"utf-8")).pid!==process.pid)return;S.unlinkSync(ne)}catch{}}var qt=!1;function vn(){if(qt)return;qt=!0;let e=()=>{try{Ge()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function bn(){if(S.existsSync(F))return;let e=[],t=[];for(let r of Bt)if(S.existsSync(r))try{e.push({file:r,schema:Ce(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
|
|
23
22
|
[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(`
|
|
24
23
|
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.
|
|
25
|
-
`),process.exit(1)}if(e.length===0)return;let
|
|
24
|
+
`),process.exit(1)}if(e.length===0)return;let o=e.map(r=>r.schema.version);if(new Set(o).size>1){console.error(`
|
|
26
25
|
[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.
|
|
27
|
-
`),process.exit(1)}let n=e[0].schema,
|
|
28
|
-
[FATAL] ${F} is not valid JSON: ${
|
|
29
|
-
`),process.exit(1)}let t
|
|
26
|
+
`),process.exit(1)}let n=e[0].schema,s=F+".tmp";try{S.writeFileSync(s,JSON.stringify(n,null,2)),S.renameSync(s,F)}catch(r){try{S.unlinkSync(s)}catch{}throw r}for(let r of Bt)if(S.existsSync(r))try{S.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${F}`)}function $n(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 Ce(e){let t=S.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Jt(){if(bn(),!S.existsSync(F))return{version:0,migrations:[]};let e;try{e=Ce(F)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
27
|
+
[FATAL] ${F} is not valid JSON: ${o.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.
|
|
28
|
+
`),process.exit(1)}let t=$n(e);return t===null&&(console.error(`
|
|
30
29
|
[FATAL] ${F} 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.
|
|
31
|
-
`),process.exit(1)),t}function
|
|
30
|
+
`),process.exit(1)),t}function Vt(e){try{S.chmodSync(e,384)}catch{}}function kn(e){if(Ht(),S.existsSync(F))try{if(S.lstatSync(F).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${F}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=F+".tmp";try{S.writeFileSync(t,JSON.stringify(e,null,2)),Vt(t),S.renameSync(t,F)}catch(o){try{S.unlinkSync(t)}catch{}throw o}}function Wt(e,t){if(!S.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=S.readdirSync(e).filter(l=>{let c=l.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return S.statSync(_.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let c=_.join(e,l),d=_.join(e,l+o);if(S.existsSync(d)){r++;continue}try{Yt(c,d),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 ${_.basename(e)}/: `+i.map(c=>`${c.file} (${c.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 ${_.basename(e)}/ (${o})${l}`)}}var He=!1;async function Gt(){if(He)return;Ht(),Dn();let t=Jt().version;if(t===X){He=!0;return}vn(),Sn(),process.on("exit",Ge),t>X&&(console.error(`
|
|
32
31
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${X}.`),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.
|
|
33
32
|
`),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${X}.
|
|
34
33
|
`),process.exit(1)),console.log(`
|
|
35
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${X}`);let
|
|
36
|
-
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let
|
|
34
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${X}`);let o=_n();if(!o.ok){console.error(`
|
|
35
|
+
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of o.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
37
36
|
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'.
|
|
38
|
-
`),process.exit(1)}let n=K.filter(
|
|
39
|
-
Running migration v${String(
|
|
37
|
+
`),process.exit(1)}let n=K.filter(s=>s.version>t);for(let s of n){console.log(`
|
|
38
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{Wt(se,s.version),Wt(re,s.version)}catch(c){console.error(`
|
|
40
39
|
[FATAL] Pre-migration backup failed for ${r}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
41
|
-
`),process.exit(1)}let l=
|
|
42
|
-
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let
|
|
43
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${
|
|
44
|
-
`))}catch(
|
|
45
|
-
`)}process.exit(1)}try{let c=new Date().toISOString(),
|
|
46
|
-
[FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${
|
|
47
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{
|
|
40
|
+
`),process.exit(1)}let l=s.module;try{await l.up(se,re)}catch(c){console.error(`
|
|
41
|
+
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let d=In(i);d.ok?(console.error(` \u2713 Auto-rollback restored ${d.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
42
|
+
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${d.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
43
|
+
`))}catch(d){console.error(` [!] Auto-rollback CRASHED while restoring: ${d.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
44
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),d={version:s.version,name:l.NAME||r,appliedAt:c},u=Jt();u.version=s.version,u.migratedAt=c,u.migrations=u.migrations||[],u.migrations.push(d),kn(u)}catch(c){console.error(`
|
|
45
|
+
[FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${c.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.
|
|
46
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{rt()}catch{}try{Ut()}catch{}He=!0,Ge(),console.log(`
|
|
48
47
|
\u2713 Schema is now at v${X}
|
|
49
|
-
`)}var
|
|
48
|
+
`)}var An=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Cn(e){let t=e.toLowerCase();return An.some(o=>o.test(t))}var En=6e4;function xn(){let e=Date.now(),t=[];for(let o of[Y,se,re]){if(!S.existsSync(o))continue;let n;try{n=S.readdirSync(o)}catch{continue}for(let s of n){if(!Cn(s))continue;let r=_.join(o,s);try{let i=S.statSync(r);if(!i.isFile()||e-i.mtimeMs<En)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function Dn({verbose:e=!1}={}){let t=xn();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{S.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${_.basename(n.dir)}/${n.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${s.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function _n(){let e=[];for(let t of[se,re]){if(!S.existsSync(t))continue;let o=S.readdirSync(t).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of o){let s=_.join(t,n);try{Ce(s)}catch(r){e.push({dir:_.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function In(e){let t=[],o=[];for(let r of[se,re]){if(!S.existsSync(r))continue;let i=S.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let c=_.join(r,l),d=l.slice(0,-e.length),u=_.join(r,d);try{d.toLowerCase().endsWith(".json")?Ce(c):S.accessSync(c,S.constants.R_OK),t.push({backupPath:c,originalPath:u,fileName:l,dir:r})}catch(m){o.push(`${_.basename(r)}/${l}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let n=0,s=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:c}of t)try{Yt(r,i),n++}catch(d){s.push(`${_.basename(c)}/${l}: ${d.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function Yt(e,t){let o=t+".tmp";try{S.copyFileSync(e,o),Vt(o)}catch(n){try{S.unlinkSync(o)}catch{}throw n}try{S.renameSync(o,t)}catch(n){try{S.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let s=new Error(`File locked: ${t} (${n.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=n.code,s}throw n}}await Gt();var Rn=le.toLowerCase().split(/\s+/).filter(e=>e.length>1);function Qe(e){if(!e)return!1;if(e===le)return!0;let t=e.toLowerCase();return Rn.some(o=>t.includes(o))}function Ye(e){return(e.messages||[]).find(t=>de.has(t.status))}function P(e){return(e.messages||[]).find(t=>ee.has(t.status))}function ze(e){return Ye(e)?.text||null}function Ke(e){return(e.messages||[]).some(t=>de.has(t.status))}function Tn(e){return(e.messages||[]).some(t=>ee.has(t.status))}function On(e,t){let o=P(e);o&&(o.text=t)}function Ee(e,t){if(!e||typeof t!="string")return{ok:!0};let o=t.match(/^\s*(?:hi|hello|hey)[,\s\-—]+([A-Z][A-Za-z'\-]*)/i);if(!o)return{ok:!0};let n=o[1],s=e.split(/[\s,]+/)[0],r=n.toLowerCase(),i=s.toLowerCase();return i.startsWith(r)||r.startsWith(i)?{ok:!0}:{ok:!1,greeted:n,convFirstWord:s,reason:`message opens with "Hi ${n}" but conv key's first word is "${s}"`}}function xe(e,t){console.error(`
|
|
50
49
|
\u2717 ABORT for "${e}": ${t.reason}.`),console.error(" This is almost certainly a mis-routed message (e.g. the body refers to a forwarded contact, not the conversation owner)."),console.error(` Fix the recipient name or the salutation in the body. Override with skipSalutationCheck=true if you really mean to address a different person.
|
|
51
|
-
`)}function
|
|
50
|
+
`)}function jn(){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 o=0;o<t.length;o++){let n=t[o];if(n==="--list")e.list=!0;else if(n==="--full")e.full=!0;else if(n==="--dry-run")e.dryRun=!0;else if(n==="--verbose")e.verbose=!0;else if(n.startsWith("--max="))e.max=parseInt(n.split("=")[1],10);else if(n==="--read")e.read=t[++o]||null;else if(n==="--send"){let s=t[++o],r=t[++o]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=ie.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.send={target:s,text:r}}else if(n==="--draft"){let s=t[++o],r=t[++o]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=ie.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.draft={target:s,text:r}}else if(n==="--push-drafts")e.pushDrafts=!0;else if(n==="--review-drafts")e.reviewDrafts=!0;else if(n==="--follow-up"){let s=t[++o],r=t[++o]||"",i=t[++o]||null;e.followUp={target:s,note:r,date:i}}else if(n==="--follow-up-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.followUpBatch=JSON.parse(ie.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read follow-up batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(n==="--clear-follow-up")e.clearFollowUp=t[++o]||null;else if(n==="--review")e.review=t[++o]||null;else if(n==="--review-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.reviewBatch=JSON.parse(ie.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read review batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(n==="--draft-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.draftBatch=JSON.parse(ie.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read draft batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}else if(n==="--send-batch"){let s=t[++o]||"";s.startsWith("@")&&(s=s.slice(1));try{e.sendBatch=JSON.parse(ie.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}}return e}function Nn(){let e=M(),t=Object.entries(e),o=t.length;if(o===0){console.log(`
|
|
52
51
|
No conversations synced yet. Run: npm run messages
|
|
53
|
-
`);return}let n={};for(let[,
|
|
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: ${
|
|
55
|
-
By status:`);for(let[
|
|
56
|
-
By category (${i} categorized):`);for(let[
|
|
52
|
+
`);return}let n={};for(let[,f]of t){let a=f.conversationStatus||"(none)";n[a]=(n[a]||0)+1}let s=t.filter(([,f])=>f.conversationStatus==="unanswered_by_us").sort((f,a)=>{let g=f[1].lastSynced||"";return(a[1].lastSynced||"").localeCompare(g)});console.log(`
|
|
53
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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: ${o} 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(`
|
|
54
|
+
By status:`);for(let[f,a]of Object.entries(n).sort((g,y)=>y[1]-g[1]))console.log(` ${f.padEnd(25)} ${a}`);let r={};for(let[,f]of t){let a=f.category||"(none)";r[a]=(r[a]||0)+1}let i=t.filter(([,f])=>f.category).length;if(i>0){console.log(`
|
|
55
|
+
By category (${i} categorized):`);for(let[f,a]of Object.entries(r).sort((g,y)=>y[1]-g[1]))console.log(` ${f.padEnd(25)} ${a}`)}let l=t.filter(([,f])=>Ke(f));if(l.length>0){let f=l.filter(([,b])=>b.conversationStatus==="unanswered_by_us"),a=l.filter(([,b])=>b.conversationStatus==="awaiting_reply"),g=l.filter(([,b])=>b.conversationStatus!=="unanswered_by_us"&&b.conversationStatus!=="awaiting_reply");console.log(`
|
|
57
56
|
\u{1F4DD} DRAFTS READY TO PUSH \u2014 ${l.length} total:
|
|
58
|
-
`);let y=([
|
|
59
|
-
\u{1F514} FOLLOW-UP NEEDED \u2014 ${
|
|
60
|
-
`);for(let[
|
|
61
|
-
`);for(let[
|
|
62
|
-
All caught up \u2014 no unanswered messages.`);let u=V(),
|
|
57
|
+
`);let y=([b,A])=>{let D=A.priority?` [${A.priority.toUpperCase()}]`:"",R=P(A),O=R?.status||$.DRAFT,w={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[O]||"",k=R?.text||"";console.log(` ${w} ${b}${D}`),console.log(` "${k.slice(0,80)}${k.length>80?"...":""}"`)};f.length>0&&(console.log(` \u2500\u2500 Replies (they wrote last) \u2014 ${f.length}:`),f.forEach(y),console.log()),a.length>0&&(console.log(` \u2500\u2500 Re-engagement (we wrote last, following up) \u2014 ${a.length}:`),a.forEach(y),console.log()),g.length>0&&(console.log(` \u2500\u2500 Other \u2014 ${g.length}:`),g.forEach(y),console.log());let v=l.filter(([,b])=>P(b)?.status===$.CONFIRMED).length,C=l.filter(([,b])=>{let A=P(b)?.status;return A===$.DRAFT||A===$.NEEDS_REVIEW}).length;console.log(` ${v} confirmed, ${C} pending review`),C>0&&console.log(" Review: npm run messages -- --review-drafts"),v>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let c=new Date,d=t.filter(([,f])=>f.priority&&f.conversationStatus==="awaiting_reply").filter(([,f])=>f.followUpAfter?new Date(f.followUpAfter)<=c:!0).sort((f,a)=>{let g={high:0,medium:1,low:2}[f[1].priority]??3,y={high:0,medium:1,low:2}[a[1].priority]??3;return g-y});if(d.length>0){console.log(`
|
|
58
|
+
\u{1F514} FOLLOW-UP NEEDED \u2014 ${d.length} priority contacts waiting:
|
|
59
|
+
`);for(let[f,a]of d){let g=a.priority.toUpperCase(),y=a.lastSynced?Math.floor((c-new Date(a.lastSynced))/864e5):"?",v=a.lastMessagePreview?.slice(0,50)||"";console.log(` [${g}] ${f} \u2014 ${y}d ago`),a.notes&&console.log(` \u{1F4CC} ${a.notes}`),console.log(` ${v}`),console.log()}}if(s.length>0){console.log(`\u26A1 ACTION NEEDED \u2014 ${s.length} unanswered messages:
|
|
60
|
+
`);for(let[f,a]of s){let g=Ke(a)?" [DRAFT READY]":"",y=a.priority?` [${a.priority.toUpperCase()}]`:a.suggestedPriority?` [${a.suggestedPriority}]`:"",v=a.category?` (${a.category})`:"",C=a.actionNeeded&&a.actionNeeded!=="none"?` \u2192 ${a.actionNeeded}`:"",b=a.lastMessageTime||"",A=(a.autoTags||[]).slice(0,4).join(", ");if(console.log(` ${f}${v}${y}${g}${C}`),a.summary)console.log(` ${a.summary}`);else{let D=a.lastMessagePreview?a.lastMessagePreview.slice(0,60)+(a.lastMessagePreview.length>60?"...":""):"";console.log(` ${b} | ${D}`)}A&&console.log(` #${A.replace(/, /g," #")}`),a.notes&&console.log(` \u{1F4CC} ${a.notes}`),a.profileUrl&&console.log(` ${a.profileUrl}`),console.log()}}else console.log(`
|
|
61
|
+
All caught up \u2014 no unanswered messages.`);let u=V(),m=new Set(Object.keys(e)),p=new Set(Object.values(e).map(f=>f.profileUrl).filter(Boolean)),h=Object.entries(u).filter(([f,a])=>a.connectionStatus==="connected"&&a.personActionNeeded==="initiate_contact"&&!p.has(f)&&!(a.name&&m.has(a.name))).sort((f,a)=>{let g={high:0,medium:1,low:2}[f[1].personPriority]??3,y={high:0,medium:1,low:2}[a[1].personPriority]??3;return g!==y?g-y:(a[1].connectionDate||"").localeCompare(f[1].connectionDate||"")});if(h.length>0){console.log(`
|
|
63
62
|
\u2709\uFE0F NEW CONNECTIONS TO MESSAGE \u2014 ${h.length} total:
|
|
64
|
-
`);let
|
|
65
|
-
`)}console.log()}function
|
|
63
|
+
`);let f=15;for(let[a,g]of h.slice(0,f)){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}`),a&&console.log(` ${a}`),console.log()}h.length>f&&console.log(` ... and ${h.length-f} more. Run: npm run today
|
|
64
|
+
`)}console.log()}function zt(e,t){return new Promise(o=>e.question(t,o))}async function Mn(){let e=M(),t=V(),o={};for(let u of Object.values(t))u.name&&u.title&&(o[u.name]=u.title);let n={draft:0,needs_review:0,confirmed:1,rejected:2},s=Object.entries(e).filter(([,u])=>Tn(u)).sort((u,m)=>{let p=n[P(u[1])?.status]??0,h=n[P(m[1])?.status]??0;if(p!==h)return p-h;let f={high:0,medium:1,low:2}[u[1].priority]??3,a={high:0,medium:1,low:2}[m[1].priority]??3;return f-a});if(s.length===0){console.log(`
|
|
66
65
|
No drafts to review.
|
|
67
|
-
`);return}let r=
|
|
68
|
-
\u2550\u2550 Draft Review \u2550\u2550`),console.log(` Total: ${
|
|
66
|
+
`);return}let r=s.filter(([,u])=>{let m=P(u)?.status;return m===$.DRAFT||m===$.NEEDS_REVIEW}),i=s.filter(([,u])=>P(u)?.status===$.CONFIRMED),l=s.filter(([,u])=>P(u)?.status===$.REJECTED);console.log(`
|
|
67
|
+
\u2550\u2550 Draft Review \u2550\u2550`),console.log(` Total: ${s.length} drafts (${r.length} pending, ${i.length} confirmed, ${l.length} rejected)
|
|
69
68
|
`),console.log(` Commands: [c]onfirm [r]eject [e]dit [s]kip [q]uit
|
|
70
|
-
`);let c=
|
|
71
|
-
${"\u2550".repeat(60)}`),console.log(` ${u+1}/${
|
|
72
|
-
`)),h.status=$.CONFIRMED,
|
|
73
|
-
Saved. ${u} confirmed, ${
|
|
74
|
-
Reached --max=${n}, stopping.`);break}if(
|
|
75
|
-
${
|
|
76
|
-
${
|
|
77
|
-
`);let a=Array.from(
|
|
78
|
-
Extracted ${a.length} conversations.`);let g=
|
|
69
|
+
`);let c=Qt.createInterface({input:process.stdin,output:process.stdout}),d=0;for(let u=0;u<s.length;u++){let[m,p]=s[u],h=P(p),f=h?.status||$.DRAFT,a={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[f]||"?",g={high:"\u{1F534}",medium:"\u{1F7E1}",low:"\u26AA"}[p.priority]||"",y=o[m]||"",v=p.messages||[],C=p.conversationStatus||"?";if(console.log(`
|
|
70
|
+
${"\u2550".repeat(60)}`),console.log(` ${u+1}/${s.length} ${a} ${m} ${g} ${(p.priority||"").toUpperCase()}`),y&&console.log(` ${y}`),console.log(` Status: ${C} | ${v.length} msgs synced`),p.notes&&console.log(` Notes: ${p.notes}`),console.log(`${"\u2500".repeat(60)}`),v.length>0){console.log(" Conversation:");let O=v.slice(-4);v.length>4&&console.log(` ... (${v.length-4} earlier messages)`);for(let w of O){let k=w.sender||"Unknown",I=(w.text||"").replace(/\n/g," ").substring(0,120),x=Qe(k)?" \u2192":" \u2190";console.log(` ${x} [${k}] ${I}`)}}else p.lastMessagePreview&&console.log(` Preview: "${p.lastMessagePreview}"`);console.log(`${"\u2500".repeat(60)}`),console.log(" Draft:");let b=ze(p)||"",A=b.match(/.{1,80}/g)||[b];for(let O of A)console.log(` ${O}`);console.log(`${"\u2500".repeat(60)}`);let R=(await zt(c," [c]onfirm [r]eject [e]dit [s]kip [q]uit > ")).trim().toLowerCase();if(R==="c"||R==="confirm"||R==="y"||R==="yes")h.status=$.CONFIRMED,d++,console.log(" \u2705 Confirmed");else if(R==="r"||R==="reject"||R==="n"||R==="no")h.status=$.REJECTED,d++,console.log(" \u274C Rejected");else if(R==="e"||R==="edit"){console.log(" Enter new draft text (end with empty line):");let O=[];for(;;){let w=await zt(c," ");if(w.trim()==="")break;O.push(w)}O.length>0?(On(p,O.join(`
|
|
71
|
+
`)),h.status=$.CONFIRMED,d++,console.log(" \u2705 Edited & Confirmed")):console.log(" (no changes)")}else if(R==="q"||R==="quit"){console.log(" Quitting review...");break}else console.log(" \u23ED Skipped")}if(c.close(),d>0){L(e);let u=Object.values(e).filter(h=>P(h)?.status===$.CONFIRMED).length,m=Object.values(e).filter(h=>P(h)?.status===$.REJECTED).length,p=Object.values(e).filter(h=>{let f=P(h)?.status;return f===$.DRAFT||f===$.NEEDS_REVIEW}).length;console.log(`
|
|
72
|
+
Saved. ${u} confirmed, ${p} pending, ${m} rejected.`),u>0&&console.log(" Ready to send: npm run messages -- --push-drafts")}console.log()}async function Zt(e){try{await Mt(e)}catch{}}async function Fn(e,t){let{full:o,max:n,verbose:s,dryRun:r}=t,i=o?"full":"incremental",l=M(),c=new Set(Object.keys(l)),d=new Map,u=0,m=0,p=3,h=0,f=3;for(;;){u++;let y=await jt(e),v=0,C=0;for(let b of y)b.name&&(d.has(b.name)||(d.set(b.name,b),c.has(b.name)?C++:v++));if(s?console.log(` Round #${u}: ${v} new, ${C} known | Total: ${d.size}`):process.stdout.write(`\r Conversations found: ${d.size} (page #${u})`),d.size>=n){console.log(`
|
|
73
|
+
Reached --max=${n}, stopping.`);break}if(v===0&&C===0){if(h++,h>=f){console.log(`
|
|
74
|
+
${f} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!o&&v===0&&C>0){if(m++,m>=p){console.log(`
|
|
75
|
+
${p} pages of already-synced conversations \u2014 caught up.`);break}}else v>0&&(m=0);await Nt(e),await E(2e3)}s||process.stdout.write(`
|
|
76
|
+
`);let a=Array.from(d.values());console.log(`
|
|
77
|
+
Extracted ${a.length} conversations.`);let g=Jn(a,r);Wn(a,g,r,i)}async function Pn(e,t,o){let n=V(),s=M(),r;if(t.startsWith("http")){let d=n[t],u=Object.entries(s).find(([,m])=>m.profileUrl===t);r=d?.name||u?.[0]}else r=t;if(!r){console.error(` Cannot find name for "${t}". Run inbox scan first.`);return}console.log(`
|
|
79
78
|
Reading conversation with: ${r}
|
|
80
|
-
`),await
|
|
81
|
-
`);for(let f of l){let u=f.time?` (${f.time})`:"";console.log(` [${f.sender}]${u}`),console.log(` ${f.text}`),console.log()}}let c=r;o[c]||(o[c]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),o[c].messages=de(o[c].messages,l),o[c].lastSynced=new Date().toISOString(),L(o),console.log(` Saved ${o[c].messages.length} messages to conversations.json ["${c}"]`)}function He(e){let t=V(),s=e,n=null;if(e.startsWith("http")){let o=t[e];if(o?.name)s=o.name,n=e;else return null}else{let o=Object.entries(t).find(([,i])=>i.name===e);o&&(n=o[0]);let r=N();!n&&r[e]?.profileUrl&&(n=r[e].profileUrl)}return{personName:s,profileUrl:n}}async function Ve(e,t,s,n,o={}){try{let{verified:r}=await we(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await oe(e,{scrollUp:!1}),c=N()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages visible (saved: ${c})`),i.length>c&&c>0){let b=i.length-c,A=i[i.length-1];return console.error(` \u2717 ABORT: ${b} new message(s) since last sync!`),console.error(` Latest: [${A.sender}] ${A.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let b=i[i.length-1],A=null;for(let D=i.length-1;D>=0;D--)if(i[D].sender!=="Unknown"&&i[D].sender!==""){A=i[D].sender;break}if(A===le)if(o.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(` "${b.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let f=n.slice(0,50).toLowerCase();if(i.some(b=>b.text.toLowerCase().startsWith(f)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!o.allowDoubleMessage){let b=new Date().toISOString().slice(0,10);if(i.some(D=>{if(!We(D.sender))return!1;let M=D.time||"";return M.startsWith(b)||M.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 p=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!p)return console.error(" Message input not found in conversation."),!1;await p.click(),await E(300);let m=n.replace(/\\([!?#$])/g,"$1");m!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=m),await e.keyboard.type(n,{delay:20}),await E(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),d=b=>b.replace(/\s+/g," ").trim(),a=d(n),g=d(h);if(g!==a){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${a.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let b=0;b<Math.max(a.length,g.length);b++)if(a[b]!==g[b]){console.error(` First diff at position ${b}: expected '${a[b]||"EOF"}' got '${g[b]||"EOF"}'`),console.error(` Context: ...${a.slice(Math.max(0,b-10),b+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 E(2500);let S=await e.evaluate(()=>{let A=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),I=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(M=>(M.innerText||"").trim()).filter(Boolean).find(M=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(M))||null;return{inputText:A,error:I}});if(S.error)return console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${S.error.slice(0,140)}"`),!1;if(S.inputText&&d(S.inputText)===d(n))return console.error(" \u2717 NOT sent \u2014 the message is still in the composer (LinkedIn did not accept it)."),!1;console.log(" \u2713 Message sent (verified: composer cleared, no error toast)."),console.log(" Syncing conversation thread..."),await E(1e3);let C=await oe(e);console.log(` Synced ${C.length} messages from thread.`);let v=N(),x=new Date().toISOString(),R=t;v[R]?(v[R].lastMessageBy="me",v[R].lastMessagePreview=n.slice(0,100),v[R].lastMessageTime=x,v[R].conversationStatus="awaiting_reply",v[R].lastSynced=x,v[R].messages=de(v[R].messages,C)):v[R]={profileUrl:s,lastSynced:x,lastMessageBy:"me",lastMessagePreview:n.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:C},s&&(v[R].profileUrl=s),L(v);let T=V(),k=s?T[s]:null;return k&&(k.conversationStatus="awaiting_reply",k.lastMessageSent=x,k.lastUpdated=x,ye(T)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function Ft(e,t,s){if(t?.profileUrl)return t.profileUrl;let n=Object.entries(s).find(([,o])=>o.name===e);return n?n[0]:null}async function Ut(e,t,s,n){try{console.log(` \u2192 Profile fallback: navigating to ${s}`),await e.goto(s,{waitUntil:"domcontentloaded",timeout:3e4}),await E(3e3);let o=await e.evaluate(()=>{let k=0,b=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let D of b){if(D.offsetHeight===0)continue;let I=D.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(I||(I=D.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!I){let M=D.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");M.length>0&&(I=M[M.length-1])}I&&I.offsetHeight>0&&(I.click(),k++)}let A=document.querySelector(".msg-overlay-list-bubble");if(A&&!A.classList.contains("msg-overlay-list-bubble--is-minimized")){let D=A.querySelector(".msg-overlay-bubble-header__button");D&&D.offsetHeight>0&&(D.click(),k++)}return k});o>0&&(console.log(` Closed ${o} existing overlay(s)`),await E(1500));let r=await e.evaluate(()=>{let k=document.querySelectorAll(".msg-overlay-conversation-bubble"),b=Array.from(k).filter(I=>I.offsetHeight>0),A=document.querySelector(".msg-overlay-list-bubble"),D=A?A.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:b.length,trayMinimized:D,bubbleNames:b.map(I=>I.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=null;for(let k=0;k<8&&!i;k++)i=await e.evaluate(()=>{let b=document.querySelectorAll('a[href*="recipient="]');for(let A of b)try{let D=new URL(A.getAttribute("href"),location.origin).searchParams.get("recipient");if(D)return D}catch{}return null}),i||(k===0&&console.log(" \u2026waiting for the profile Message link to render"),await E(1300));if(!i)return console.error(" \u2717 Could not extract recipient URN from profile after retries (Message link never rendered)"),!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 E(3e3);let c=e.url();if(c.includes("/premium/")||c.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(k=>k.length>1),p=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(p){let k=p.toLowerCase();if(!(k.includes(f)||u.some(A=>k.includes(A))))return console.error(` \u2717 Recipient mismatch: compose shows "${p}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${p}"`)}else return console.error(" \u2717 Could not confirm the recipient (compose pill unreadable) \u2014 not sending on the direct path."),!1;let m=await oe(e,{scrollUp:!1});if(m.length>0){let k=n.slice(0,50).toLowerCase();if(m.some(I=>I.text.toLowerCase().startsWith(k)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let A=new Date().toISOString().slice(0,10);if(m.some(I=>{if(!We(I.sender))return!1;let Ye=I.time||"";return Ye.startsWith(A)||Ye.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 E(300);let d=n.replace(/\\([!?#$])/g,"$1");d!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=d),await e.keyboard.type(n,{delay:20}),await E(500);let a=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),g=k=>k.replace(/\s+/g," ").trim();if(g(a)!==g(n))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${g(n).slice(0,100)}..."`),console.error(` Actual: "${g(a).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 E(2500);let S=await e.evaluate(()=>{let b=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),D=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(I=>(I.innerText||"").trim()).filter(Boolean).find(I=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(I))||null;return{inputText:b,error:D}});if(S.error)return console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${S.error.slice(0,140)}"`),!1;if(S.inputText&&g(S.inputText)===g(n))return console.error(" \u2717 NOT sent \u2014 the message is still in the composer (LinkedIn did not accept it)."),!1;console.log(" \u2713 Message sent via profile (verified: composer cleared, no error toast)."),console.log(" Syncing conversation thread..."),await E(1e3);let C=await oe(e);console.log(` Synced ${C.length} messages from thread.`);let v=N(),x=new Date().toISOString();v[t]?(v[t].lastMessageBy="me",v[t].lastMessagePreview=n.slice(0,100),v[t].lastMessageTime=x,v[t].conversationStatus="awaiting_reply",v[t].lastSynced=x,v[t].messages=de(v[t].messages,C)):v[t]={profileUrl:s,lastSynced:x,lastMessageBy:"me",lastMessagePreview:n.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:C},s&&(v[t].profileUrl=s),L(v);let R=V(),T=R[s];return T&&(T.conversationStatus="awaiting_reply",T.lastMessageSent=x,T.lastUpdated=x,ye(R)),!0}catch(o){return console.error(" \u2717 Profile send error:",o.message),!1}}async function bn(e,t,s,n){if(!t||!s)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let o=He(t);if(!o)return console.error(` Person not found: ${t}`),!1;let r=be(o.personName,s);if(!r.ok)return $e(o.personName,r),!1;if(console.log(`
|
|
82
|
-
Sending message to: ${
|
|
83
|
-
[DRY RUN \u2014 message not sent]`),!1;if(
|
|
79
|
+
`),await Pe(e);let{verified:i}=await ke(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await oe(e);if(l.length===0){if(console.log(" No messages extracted (DOM may have changed)."),o){let d=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:",d)}}else{console.log(` ${l.length} messages:
|
|
80
|
+
`);for(let d of l){let u=d.time?` (${d.time})`:"";console.log(` [${d.sender}]${u}`),console.log(` ${d.text}`),console.log()}}let c=r;s[c]||(s[c]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),s[c].messages=ge(s[c].messages,l),s[c].lastSynced=new Date().toISOString(),L(s),console.log(` Saved ${s[c].messages.length} messages to conversations.json ["${c}"]`)}function Ze(e){let t=V(),o=e,n=null;if(e.startsWith("http")){let s=t[e];if(s?.name)o=s.name,n=e;else return null}else{let s=Object.entries(t).find(([,i])=>i.name===e);s&&(n=s[0]);let r=M();!n&&r[e]?.profileUrl&&(n=r[e].profileUrl)}return{personName:o,profileUrl:n}}async function Xe(e,t,o,n,s={}){try{let{verified:r}=await ke(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await oe(e,{scrollUp:!1}),c=M()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages visible (saved: ${c})`),i.length>c&&c>0){let w=i.length-c,k=i[i.length-1];return console.error(` \u2717 ABORT: ${w} new message(s) since last sync!`),console.error(` Latest: [${k.sender}] ${k.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let w=i[i.length-1],k=null;for(let I=i.length-1;I>=0;I--)if(i[I].sender!=="Unknown"&&i[I].sender!==""){k=i[I].sender;break}if(k===le)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(` "${w.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let d=n.slice(0,50).toLowerCase();if(i.some(w=>w.text.toLowerCase().startsWith(d)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!s.allowDoubleMessage){let w=new Date().toISOString().slice(0,10);if(i.some(I=>{if(!Qe(I.sender))return!1;let x=I.time||"";return x.startsWith(w)||x.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 E(300);let p=n.replace(/\\([!?#$])/g,"$1");p!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=p),await e.keyboard.type(n,{delay:20}),await E(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),f=w=>w.replace(/\s+/g," ").trim(),a=f(n),g=f(h);if(g!==a){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${a.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let w=0;w<Math.max(a.length,g.length);w++)if(a[w]!==g[w]){console.error(` First diff at position ${w}: expected '${a[w]||"EOF"}' got '${g[w]||"EOF"}'`),console.error(` Context: ...${a.slice(Math.max(0,w-10),w+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 E(2500);let v=await e.evaluate(()=>{let k=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),T=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(x=>(x.innerText||"").trim()).filter(Boolean).find(x=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(x))||null;return{inputText:k,error:T}});if(v.error)return console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${v.error.slice(0,140)}"`),!1;if(v.inputText&&f(v.inputText)===f(n))return console.error(" \u2717 NOT sent \u2014 the message is still in the composer (LinkedIn did not accept it)."),!1;console.log(" \u2713 Message sent (verified: composer cleared, no error toast)."),console.log(" Syncing conversation thread..."),await E(1e3);let C=await oe(e);console.log(` Synced ${C.length} messages from thread.`);let b=M(),A=new Date().toISOString(),D=t;b[D]?(b[D].lastMessageBy="me",b[D].lastMessagePreview=n.slice(0,100),b[D].lastMessageTime=A,b[D].conversationStatus="awaiting_reply",b[D].lastSynced=A,b[D].messages=ge(b[D].messages,C)):b[D]={profileUrl:o,lastSynced:A,lastMessageBy:"me",lastMessagePreview:n.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:C},o&&(b[D].profileUrl=o),L(b);let R=V(),O=o?R[o]:null;return O&&(O.conversationStatus="awaiting_reply",O.lastMessageSent=A,O.lastUpdated=A,be(R)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function Kt(e,t,o){if(t?.profileUrl)return t.profileUrl;let n=Object.entries(o).find(([,s])=>s.name===e);return n?n[0]:null}async function Xt(e,t,o,n){try{console.log(` \u2192 Profile fallback: navigating to ${o}`),await e.goto(o,{waitUntil:"domcontentloaded",timeout:3e4}),await E(3e3);let s=await e.evaluate(()=>{let w=0,k=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let T of k){if(T.offsetHeight===0)continue;let x=T.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(x||(x=T.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!x){let ue=T.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");ue.length>0&&(x=ue[ue.length-1])}x&&x.offsetHeight>0&&(x.click(),w++)}let I=document.querySelector(".msg-overlay-list-bubble");if(I&&!I.classList.contains("msg-overlay-list-bubble--is-minimized")){let T=I.querySelector(".msg-overlay-bubble-header__button");T&&T.offsetHeight>0&&(T.click(),w++)}return w});s>0&&(console.log(` Closed ${s} existing overlay(s)`),await E(1500));let r=await e.evaluate(()=>{let w=document.querySelectorAll(".msg-overlay-conversation-bubble"),k=Array.from(w).filter(x=>x.offsetHeight>0),I=document.querySelector(".msg-overlay-list-bubble"),T=I?I.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:k.length,trayMinimized:T,bubbleNames:k.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=null;for(let w=0;w<8&&!i;w++)i=await e.evaluate(()=>{let k=document.querySelectorAll('a[href*="recipient="]');for(let I of k)try{let T=new URL(I.getAttribute("href"),location.origin).searchParams.get("recipient");if(T)return T}catch{}return null}),i||(w===0&&console.log(" \u2026waiting for the profile Message link to render"),await E(1300));if(!i)return console.error(" \u2717 Could not extract recipient URN from profile after retries (Message link never rendered)"),!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 E(3e3);let c=e.url();if(c.includes("/premium/")||c.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;if(!await we(e,'div.msg-form__contenteditable, div[contenteditable="true"][role="textbox"]',{timeout:45e3,label:"compose box"})){let w=e.url(),k=/\/premium\/|\/checkpoint\/|\/login|\/authwall/.test(w)?" \u2014 looks like a gate (premium/checkpoint/login)":"";return console.error(` \u2717 Message composer never appeared after 45s. URL: ${w.slice(0,120)}${k}`),!1}console.log(" \u2713 Compose page loaded, message form ready");let u=t.split(" ")[0].toLowerCase(),m=t.toLowerCase().split(/[\s,]+/).filter(w=>w.length>1),p=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(p){let w=p.toLowerCase();if(!(w.includes(u)||m.some(I=>w.includes(I))))return console.error(` \u2717 Recipient mismatch: compose shows "${p}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${p}"`)}else return console.error(" \u2717 Could not confirm the recipient (compose pill unreadable) \u2014 not sending on the direct path."),!1;let h=await oe(e,{scrollUp:!1});if(h.length>0){let w=n.slice(0,50).toLowerCase();if(h.some(x=>x.text.toLowerCase().startsWith(w)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let I=new Date().toISOString().slice(0,10);if(h.some(x=>{if(!Qe(x.sender))return!1;let et=x.time||"";return et.startsWith(I)||et.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let f=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!f)return console.error(" Message input not found in overlay."),!1;await f.click(),await E(300);let a=n.replace(/\\([!?#$])/g,"$1");a!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=a),await e.keyboard.type(n,{delay:20}),await E(500);let g=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),y=w=>w.replace(/\s+/g," ").trim();if(y(g)!==y(n))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${y(n).slice(0,100)}..."`),console.error(` Actual: "${y(g).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 v=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!v)return console.error(" Send button not found in overlay."),!1;await v.click(),await E(2500);let C=await e.evaluate(()=>{let k=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),T=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(x=>(x.innerText||"").trim()).filter(Boolean).find(x=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(x))||null;return{inputText:k,error:T}});if(C.error)return console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${C.error.slice(0,140)}"`),!1;if(C.inputText&&y(C.inputText)===y(n))return console.error(" \u2717 NOT sent \u2014 the message is still in the composer (LinkedIn did not accept it)."),!1;console.log(" \u2713 Message sent via profile (verified: composer cleared, no error toast)."),console.log(" Syncing conversation thread..."),await E(1e3);let b=await oe(e);console.log(` Synced ${b.length} messages from thread.`);let A=M(),D=new Date().toISOString();A[t]?(A[t].lastMessageBy="me",A[t].lastMessagePreview=n.slice(0,100),A[t].lastMessageTime=D,A[t].conversationStatus="awaiting_reply",A[t].lastSynced=D,A[t].messages=ge(A[t].messages,b)):A[t]={profileUrl:o,lastSynced:D,lastMessageBy:"me",lastMessagePreview:n.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:b},o&&(A[t].profileUrl=o),L(A);let R=V(),O=R[o];return O&&(O.conversationStatus="awaiting_reply",O.lastMessageSent=D,O.lastUpdated=D,be(R)),!0}catch(s){return console.error(" \u2717 Profile send error:",s.message),!1}}async function Ln(e,t,o,n){if(!t||!o)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let s=Ze(t);if(!s)return console.error(` Person not found: ${t}`),!1;let r=Ee(s.personName,o);if(!r.ok)return xe(s.personName,r),!1;if(console.log(`
|
|
81
|
+
Sending message to: ${s.personName}`),console.log(` Text: "${o.slice(0,150)}${o.length>150?"...":""}"`),n)return console.log(`
|
|
82
|
+
[DRY RUN \u2014 message not sent]`),!1;if(s.profileUrl){if(await Xt(e,s.personName,s.profileUrl,o))return!0;console.log(" Direct profile-URL send did not complete \u2014 falling back to name search\u2026")}return await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await E(4e3),Xe(e,s.personName,s.profileUrl,o)}async function Un(e,t,o){if(console.log(`
|
|
84
83
|
\u2550\u2550 Batch send: ${t.length} messages \u2550\u2550
|
|
85
|
-
`),
|
|
86
|
-
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`);let
|
|
84
|
+
`),o){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 E(4e3);let n=[];for(let i=0;i<t.length;i++){let{name:l,message:c}=t[i];console.log(`
|
|
85
|
+
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`);let d=Ze(l);if(!d){console.error(` \u2717 Cannot resolve: ${l}`),n.push({name:l,status:"not_found"});continue}if(!t[i].skipSalutationCheck){let m=Ee(d.personName,c);if(!m.ok){xe(d.personName,m),n.push({name:l,status:"aborted_salutation"});continue}}console.log(` Text: "${c.slice(0,100)}${c.length>100?"...":""}"`);let u=await Xe(e,d.personName,d.profileUrl,c);n.push({name:l,status:u?"sent":"failed"}),await Zt(e)}console.log(`
|
|
87
86
|
\u2550\u2550 Batch results \u2550\u2550
|
|
88
|
-
`);let
|
|
89
|
-
Total: ${
|
|
87
|
+
`);let s=n.filter(i=>i.status===$.SENT),r=n.filter(i=>i.status!==$.SENT);for(let i of n){let l=i.status===$.SENT?"\u2713":"\u2717";console.log(` ${l} ${i.name} \u2014 ${i.status}`)}console.log(`
|
|
88
|
+
Total: ${s.length} sent, ${r.length} failed/skipped`)}async function Bn(e,t){let o=M(),n=V(),s=Object.entries(o).filter(([,f])=>Ke(f)),r=s.filter(([,f])=>Ye(f)?.status===$.CONFIRMED),i=s.filter(([,f])=>{let a=Ye(f)?.status;return a===$.DRAFT||a===$.NEEDS_REVIEW}).length;if(s.length===0){console.log(`
|
|
90
89
|
No drafts to push. Prepare drafts in conversations.json first.
|
|
91
90
|
`);return}if(r.length===0){console.log(`
|
|
92
91
|
No confirmed drafts to push (${i} pending, need review).`),console.log(` Run: npm run messages -- --review-drafts
|
|
93
92
|
`);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[
|
|
95
|
-
`),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await E(4e3);let l=[],c=[];for(let
|
|
96
|
-
\u2500\u2500 [${
|
|
93
|
+
\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[f,a]of r){let g=Kt(f,a,n),y=a.messages?.some(C=>!de.has(C.status)&&C.status!==$.REJECTED)?"inbox":g?"profile":"no profileUrl";console.log(` [DRY RUN] ${f} (${y}):`);let v=ze(a)||"";console.log(` "${v.slice(0,100)}${v.length>100?"...":""}"`),console.log()}return}console.log(`\u2500\u2500 Pass 1: Inbox search \u2500\u2500
|
|
94
|
+
`),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await E(4e3);let l=[],c=[];for(let f=0;f<r.length;f++){let[a,g]=r[f],y=ze(g);console.log(`
|
|
95
|
+
\u2500\u2500 [${f+1}/${r.length}] ${a} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let v=Ze(a),C=v?.personName||a,b=v?.profileUrl||g.profileUrl||null;if(!g.skipSalutationCheck){let w=Ee(a,y);if(!w.ok){xe(a,w),l.push({name:a,status:"aborted_salutation"});continue}}let D=(g.messages||[]).filter(w=>!ee.has(w.status)).length,R=!1,O=!1;try{await tt(e);let{verified:w}=await ke(e,C);if(w){O=!0;let k=await oe(e);if(k.length>D&&D>0){let I=k.length-D;R=!0,g.messages=ge(g.messages,k),console.log(` \u26A0 ${I} new message(s) since draft was created!`);let T=k[k.length-1];console.log(` Latest: [${T.sender}] ${T.text.slice(0,80)}`)}}else console.log(" Not found or wrong thread in inbox search")}catch(w){console.log(` Pre-send sync error: ${w.message}`)}if(R){for(let w of g.messages||[])w.status===$.CONFIRMED&&(w.status=$.NEEDS_REVIEW);l.push({name:a,status:$.NEEDS_REVIEW}),console.log(" \u2192 Skipped \u2014 draft needs review (new messages from them)")}else if(O)if(await Xe(e,C,b,y,{allowDoubleMessage:!0})){for(let k of g.messages||[])k.status===$.CONFIRMED&&k.text===y&&(k.status=$.SENT,k.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",L(o),l.push({name:a,status:"sent",method:"inbox"})}else l.push({name:a,status:"failed",method:"inbox"});else c.push({name:a,conv:g,message:y,personName:C}),console.log(" \u2192 Queued for profile fallback");R&&L(o),await Zt(e)}if(c.length>0){console.log(`
|
|
97
96
|
\u2500\u2500 Pass 2: Profile fallback (${c.length} remaining) \u2500\u2500
|
|
98
|
-
`);for(let
|
|
99
|
-
\u2500\u2500 [profile ${
|
|
97
|
+
`);for(let f=0;f<c.length;f++){let{name:a,conv:g,message:y,personName:v}=c[f];console.log(`
|
|
98
|
+
\u2500\u2500 [profile ${f+1}/${c.length}] ${a} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let C=Kt(a,g,n);if(!C){console.error(" \u2717 No profileUrl found \u2014 cannot send via profile"),l.push({name:a,status:"failed",method:"no_url"});continue}if(await Xt(e,v,C,y)){for(let A of g.messages||[])A.status===$.CONFIRMED&&A.text===y&&(A.status=$.SENT,A.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",L(o),l.push({name:a,status:"sent",method:"profile"})}else l.push({name:a,status:"failed",method:"profile"})}}console.log(`
|
|
100
99
|
\u2550\u2550 Push results \u2550\u2550
|
|
101
|
-
`);let
|
|
102
|
-
Total: ${
|
|
100
|
+
`);let d=l.filter(f=>f.status===$.SENT),u=l.filter(f=>f.status===$.NEEDS_REVIEW),m=l.filter(f=>f.status==="failed");for(let f of l){let a={sent:"\u2713",needs_review:"\u26A0",failed:"\u2717"}[f.status]||"?",g=f.method?` (${f.method})`:"";console.log(` ${a} ${f.name} \u2014 ${f.status}${g}`)}let p=d.filter(f=>f.method==="inbox").length,h=d.filter(f=>f.method==="profile").length;console.log(`
|
|
101
|
+
Total: ${d.length} sent (${p} inbox, ${h} profile), ${u.length} need review, ${m.length} failed`)}function qn(e){let t={};for(let[o,n]of Object.entries(e)){let s=n.name;s&&(t[s]?n.connectionStatus==="connected"&&t[s].connectionStatus!=="connected"&&(t[s]={url:o,...n}):t[s]={url:o,...n})}return t}function Jn(e,t){let o=M(),n=V(),s=qn(n),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 c;l.lastMessageBy==="them"?(c="unanswered_by_us",i.unansweredByUs++):l.lastMessageBy==="me"?(c="awaiting_reply",i.awaitingReply++):c="mutual_silence";let u=s[l.name]?.url||null,m=o[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=c),u&&!m.profileUrl&&(m.profileUrl=u),i.updatedConversations++):(o[l.name]={profileUrl:u,lastSynced:r,lastMessageBy:l.lastMessageBy,lastMessagePreview:l.lastMessagePreview||"",lastMessageTime:l.lastMessageTime||"",unread:l.unread||!1,conversationStatus:c,messages:[]},i.newConversations++),u){let p=n[u];p.conversationStatus=c,l.lastMessageBy==="them"&&(p.lastMessageReceived=p.lastMessageReceived||r),l.lastMessageBy==="me"&&(p.lastMessageSent=p.lastMessageSent||r),p.lastUpdated=r,i.peopleLinked++}}return t||(L(o),be(n)),i}function Wn(e,t,o,n){let s=M(),r=Object.entries(s),i=r.filter(([,l])=>l.conversationStatus==="unanswered_by_us").sort((l,c)=>{let d=l[1].lastSynced||"";return(c[1].lastSynced||"").localeCompare(d)});if(console.log(`
|
|
103
102
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 (${n})`),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 c=i.slice(0,15);console.log(`
|
|
104
103
|
\u26A1 ACTION NEEDED \u2014 ${i.length} unanswered messages:
|
|
105
|
-
`);for(let[
|
|
104
|
+
`);for(let[d,u]of c){let m=d.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
105
|
... and ${i.length-15} more. Use --list for full list.`)}else console.log(`
|
|
107
|
-
All caught up \u2014 no unanswered messages.`);
|
|
106
|
+
All caught up \u2014 no unanswered messages.`);o&&console.log(`
|
|
108
107
|
[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
|
|
108
|
+
`)}async function Hn(){let e=jn();if(e.list){Nn();return}if(e.reviewDrafts){await Mn();return}if(e.followUp||e.followUpBatch||e.clearFollowUp){let r=M(),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 c of l){let d=c.target||c.name,u=c.note||c.text||"",m=c.date||null,p=r[d];p?(p.followUpNote=u,m&&(p.followUpDate=m),i++,console.log(` + ${d} \u2014 follow-up set${m?` for ${m}`:""}: ${u.slice(0,60)}`)):(r[d]={profileUrl:null,lastSynced:new Date().toISOString(),followUpNote:u,followUpDate:m||null,messages:[]},i++,console.log(` + ${d} \u2014 new entry with follow-up${m?` for ${m}`:""}`))}}i>0&&(L(r),console.log(`
|
|
110
109
|
${i} follow-up(s) updated.
|
|
111
|
-
`));return}if(e.review||e.reviewBatch){let r=e.reviewBatch||[e.review],i=
|
|
110
|
+
`));return}if(e.review||e.reviewBatch){let r=e.reviewBatch||[e.review],i=M(),l=0;for(let c of r){let d=i[c];d?(d.reviewedAtPreview=d.lastMessagePreview||"",l++,console.log(` + ${c} \u2014 marked as reviewed`)):console.log(` ? ${c} \u2014 not found in conversations`)}l>0?(L(i),console.log(`
|
|
112
111
|
${l} conversation(s) marked as reviewed.
|
|
113
112
|
`)):console.log(`
|
|
114
113
|
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=
|
|
114
|
+
`);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=M(),l=V(),c=0;for(let{name:d,text:u,profileUrl:m,skipSalutationCheck:p}of r){if(!d||!u){console.error(` Skipping invalid draft: name=${d}`);continue}let h=e.draft?u.replace(/\\([!?#$])/g,"$1"):u;if(!p){let g=Ee(d,h);if(!g.ok){xe(d,g);continue}}if(!i[d]){let g=m||null;if(!g){let y=Object.entries(l).filter(([,v])=>v.name===d);y.length===1?g=y[0][0]:y.length>1&&console.warn(` \u26A0 Multiple people named "${d}" \u2014 pass profileUrl in draft JSON to disambiguate`)}i[d]={profileUrl:g,lastSynced:new Date().toISOString(),conversationStatus:null,messages:[]},g?console.log(` New conversation \u2014 linked to ${g}`):console.warn(" \u26A0 New conversation \u2014 no profileUrl found (push will need inbox search)")}let f=i[d];f.messages||(f.messages=[]),f.messages.push({sender:le,text:h,time:new Date().toISOString(),status:$.CONFIRMED,draftedAt:new Date().toISOString()}),f.reviewedAtPreview=f.lastMessagePreview||"";let a=f.messages.filter(g=>!de.has(g.status)&&g.status!==$.REJECTED);console.log(` Draft added for ${d}`),console.log(` Thread: ${a.length} messages + 1 draft`),console.log(` "${h.slice(0,100)}${h.length>100?"...":""}"`),console.log(),c++}L(i),console.log(` ${c} draft(s) saved. Send all: npm run messages -- --push-drafts
|
|
116
115
|
`);return}console.log(`
|
|
117
116
|
\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",
|
|
119
|
-
`),await
|
|
120
|
-
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),
|
|
117
|
+
`),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",o=dt("messages",t),{browser:n,page:s}=await Ot();try{if(e.read)await Pn(s,e.read,e.verbose);else if(e.pushDrafts)await Bn(s,e.dryRun);else if(e.sendBatch)await Un(s,e.sendBatch,e.dryRun);else if(e.send)await Ln(s,e.send.target,e.send.text,e.dryRun);else{let r=e.full?"full":"incremental";console.log(`Mode: ${r} inbox scan
|
|
118
|
+
`),await Pe(s),await Fn(s,{full:e.full,max:e.max,verbose:e.verbose,dryRun:e.dryRun})}je(o,"success")}catch(r){console.error(`
|
|
119
|
+
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),je(o,"error",null,r.message)}finally{await n.close()}}Hn();
|