ilml-plugin-linkedin 1.20.6 → 1.20.8
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 +6 -0
- package/dist/messageBot.mjs +71 -71
- package/dist/syncAll.mjs +1 -1
- package/dist/version.mjs +1 -1
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.20.8
|
|
4
|
+
- **Fixed: `messages --push-drafts` no longer leaves a duplicate copy of the sent message in your local conversation history.** When a draft was sent, the plugin could record the message twice — once as the draft-turned-sent and once from re-reading the thread afterwards — because the two copies differed only by the paragraph breaks (`\n\n`) that LinkedIn strips when it re-extracts a thread, so they weren't recognised as the same message. Two fixes: (1) message de-duplication is now whitespace-insensitive, so any two messages that differ only in spacing/line-breaks collapse into one; (2) the send flow now writes your conversations file through a single owner instead of two competing writers that could overwrite each other. If extraction ever misses the just-sent message on a very long thread, the draft is kept (marked sent) rather than dropped, so a sent message is never lost from the record. Recognising your own sent message now tolerates the small differences LinkedIn introduces in the displayed sender name (case, spacing, an appended credential), so it can't accidentally leave a second copy. Message de-duplication is also now robust to unexpected non-text values in stored data — a single corrupted entry can no longer abort a whole sync. Existing duplicates tidy themselves up the next time that thread is synced. No schema change — your messages, contacts and drafts are otherwise untouched.
|
|
5
|
+
|
|
6
|
+
## 1.20.7
|
|
7
|
+
- **Fixed: `messages --send-batch` crashed instead of sending.** The batch JSON's message body can now be either `text` or `message` — the `--draft-batch` command uses `text`, but `--send-batch` previously required `message` and, if you passed `text`, crashed with an unhelpful "Cannot read properties of undefined" instead of sending. Both batch commands now accept the same shape (`[{ "name": "...", "text": "..." }]`). An entry that's missing its message body is now reported as a clear per-entry error and skipped, instead of aborting the whole batch. No schema change.
|
|
8
|
+
|
|
3
9
|
## 1.20.6
|
|
4
10
|
- **Every command that opens LinkedIn now waits through the ~30-second "signing you back in" screen — not just `apply`, `connect` and `sync`.** 1.20.4–1.20.5 taught those commands to wait through LinkedIn's re-verification screen (the one that shows up when you've recently signed in from another location or device) instead of mistaking it for a logout. This release extends the same handling to the rest of the commands that load a page: `sync-connections`, `viewers`, `read-post`, `enrich --with-experience`, and the profile fallback used when sending a message. Before, these could fail or come back empty during that screen — `sync-connections` in particular looked for a login redirect too early (after about 3 seconds) and then waited only 15, so a slow re-verify looked like "not logged in". Now they all wait up to 45 seconds and only report a session problem if a real login page is still showing afterwards. Under the hood this is now one shared piece of logic rather than the same sequence repeated in each command, so coverage stays consistent as new commands are added. No schema change.
|
|
5
11
|
|
package/dist/messageBot.mjs
CHANGED
|
@@ -1,119 +1,119 @@
|
|
|
1
|
-
var to=Object.defineProperty;var
|
|
1
|
+
var to=Object.defineProperty;var pe=(e,t)=>{for(var o in t)to(e,o,{get:t[o],enumerable:!0})};import*as oe from"fs";import*as Kt from"readline";var Ee={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},oo={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function ce(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 xe(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=ce(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=oo[n[1].toLowerCase()],c=ce(n[2]||""),a=new Date(t),p=a.getDay()-l;return p<=0&&(p+=7),a.setDate(a.getDate()-p),c?a.setHours(c.hours,c.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let s=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(s){let l=Ee[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(s[2],10),a=parseInt(s[3],10),f=ce(s[4]||"");return new Date(a,l,c,f?.hours||0,f?.minutes||0,0,0).toISOString()}let r=o.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=Ee[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(r[2],10),a=ce(r[3]||""),f=t.getFullYear(),p=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return p>t&&p.setFullYear(f-1),p.toISOString()}let i=o.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=Ee[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(i[2],10),a=ce(i[3]||""),f=t.getFullYear(),p=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return p>t&&p.setFullYear(f-1),p.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 De(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}var no=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function so(e){return no.test(e||"")}async function ro(e,{readySelector:t,label:o="page",timeout:n=45e3}={}){let s=await De(e,t,{timeout:n,label:o});if(!s&&so(e.url())){let r=new Error(`Session expired (${o}) \u2014 redirected to login. Run: ilml linkedin login`);throw r.code="SESSION_EXPIRED",r}return s}async function me(e,t,{readySelector:o,label:n="page",timeout:s=45e3,gotoTimeout:r=6e4}={}){return await e.goto(t,{waitUntil:"domcontentloaded",timeout:r}),ro(e,{readySelector:o,label:n,timeout:s})}async function Ze(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 et(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 tt(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 io}from"@ilivemylife/graph-sdk";var lo=await io();for(let[e,t]of Object.entries(lo))process.env[e]===void 0&&(process.env[e]=t);var se=process.env.LINKEDIN_NAME,A=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ae=Object.freeze(new Set([A.DRAFT,A.CONFIRMED,A.NEEDS_REVIEW])),Y=Object.freeze(new Set([A.DRAFT,A.CONFIRMED,A.REJECTED,A.NEEDS_REVIEW]));import"dotenv/config";import*as R from"fs";import*as T from"path";import{fileURLToPath as co}from"url";var ao=co(import.meta.url),uo=T.dirname(T.dirname(ao)),H=process.env.DATA_DIR?T.resolve(process.env.DATA_DIR,"collected-profiles"):T.join(uo,"collected-profiles"),_e=T.join(H,"people.json"),ns=T.join(H,"jobs.json"),ss=T.join(H,"quota.json"),ge=T.join(H,"conversations.json"),rs=T.join(H,"sync-state.json"),is=T.join(H,"application-questions.json"),ls=T.join(H,"profile-history"),ot=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},cs=ot(process.env.CONNECT_MAX_DAILY,20),as=ot(process.env.CONNECT_MAX_WEEKLY,100),re=null,fo=null,po=null,X=null,mo=null,go=null;function nt(){re=null,fo=null,po=null,X=null,mo=null,go=null}function he(){R.existsSync(H)||R.mkdirSync(H,{recursive:!0})}function Re(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";R.writeFileSync(n,o);for(let s=0;s<3;s++)try{R.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 st(e,t){if(!R.existsSync(e))return null;try{let o=JSON.parse(R.readFileSync(e,"utf-8"));try{R.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${T.resolve(e)}`);let n=e+".backup";if(R.existsSync(n))try{let s=JSON.parse(R.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{R.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{R.copyFileSync(e,e+".corrupted")}catch{}return null}}function V(){return re||(he(),re=st(_e,"people.json")||{},re)}function Ie(e){he(),re=e;try{Re(_e,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${T.resolve(_e)}`)}}function O(){return X||(he(),X=st(ge,"conversations.json")||{},ho(X),X)}function ho(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(ge,e)}catch{}}}function F(e){he(),X=e;try{Re(ge,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${T.resolve(ge)}`)}}import"dotenv/config";import*as P from"fs";import*as z from"path";import{fileURLToPath as $o}from"url";import"dotenv/config";import{createGraphClient as yo,resolveToken as wo}from"@ilivemylife/graph-sdk";import{config as So}from"dotenv";So();var rt=wo()||process.env.TOKEN;rt||(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 it=yo({token:rt});function vo(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 bo({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?` ${vo(s)}`:"",c=o==="error"?`error${n?`: ${String(n).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${a} \u2014 ${c} \u2014 ${i}${l}`}async function lt({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=`**${bo({scriptName:e,mode:t,status:o,error:s,duration:r})}**
|
|
6
6
|
|
|
7
7
|
${n.join(`
|
|
8
|
-
`)}`;try{await at.addMessage(i,c)}catch(d){console.error(`[runReport] Failed to post end-of-session message: ${d.message}`)}}var ko=$o(import.meta.url),Ao=Q.dirname(Q.dirname(ko)),Oe=process.env.DATA_DIR?Q.resolve(process.env.DATA_DIR,"collected-profiles"):Q.join(Ao,"collected-profiles"),Ne=Q.join(Oe,"run-log.json");function Co(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 ft(){try{if(!B.existsSync(Ne))return{runs:[]};let e=JSON.parse(B.readFileSync(Ne,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function dt(e){B.existsSync(Oe)||B.mkdirSync(Oe,{recursive:!0});try{Co(Ne,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function pt(e,t="default"){let o=ft();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),dt(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=ft(),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)}dt(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";ut({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 jo from"puppeteer";import{addExtra as Mo}from"puppeteer-extra";import Po from"puppeteer-extra-plugin-stealth";import G from"fs";import X from"path";var Eo="cookies.json";function mt(){let e=process.env.ILML_SCOPE_DIR;return e?X.join(e,"plugins-state","linkedin","cookies.json"):Eo}function gt(){let e=mt();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 ht(){return G.existsSync(mt())}function xo(){let e=process.env.ILML_SCOPE_DIR;return e?X.join(e,"plugins-state","linkedin"):"."}function yt(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Do(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?yt(t[1]):"default"}function wt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return G.existsSync(t)||G.mkdirSync(t,{recursive:!0}),X.resolve(t);let o=yt(e||Do()),n=X.join(xo(),"chrome-profile",o);return G.existsSync(n)||G.mkdirSync(n,{recursive:!0}),X.resolve(n)}var St=".ilml-seeded";function vt(e){return!G.existsSync(X.join(e,St))}function bt(e){try{G.writeFileSync(X.join(e,St),new Date().toISOString())}catch{}}function $t(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{G.rmSync(X.join(e,o),{force:!0}),t++}catch{}return t}import Me from"fs";import _o from"path";var Ro={headless:!1,defaultViewport:null,protocolTimeout:3e5},me=new Set,kt=!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 Io(){if(kt)return;kt=!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 Pe(e){return _o.join(e,".ilml-browser-session.json")}function xt(e,t={}){try{Me.writeFileSync(Pe(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function To(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();xt(e,o?{wsEndpoint:o}:{})}catch{}}function Oo(e){let t=Dt(e);t&&t.ownerPid===process.pid&&pe(e)}function pe(e){try{Me.rmSync(Pe(e),{force:!0})}catch{}}function Dt(e){try{return JSON.parse(Me.readFileSync(Pe(e),"utf-8"))}catch{return null}}function At(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Ct(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 Et(e,t,{probeTimeoutMs:o=4e3}={}){let n=Dt(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&At(n.ownerPid)?"live":(pe(t),"free");let s=Symbol("timeout"),r=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Ct(r,o,s);if(i===s)return r.then(c=>{if(c)try{c.disconnect()}catch{}}),"live";if(!i)return pe(t),"free";if(At(n.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Ct(i.close().then(()=>!0).catch(()=>!1),o,!1))return pe(t),"free";try{i.disconnect()}catch{}return"live"}function No(e,t){e&&(Io(),me.add(e),e.on("disconnected",()=>{me.delete(e),t&&pe(t)}))}async function _t(e,t={}){let o=wt(),n={...Ro,...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 Et(e,o)==="live")throw new Error(s);xt(o);let r;try{r=await e.launch(n)}catch{if(await Et(e,o)==="live")throw new Error(s);$t(o);try{r=await e.launch(n)}catch(l){throw Oo(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 No(r,o),To(o,r),{browser:r,profileDir:o,needsSeed:vt(o)}}async function Rt(e,t){if(!t||!t.needsSeed)return!1;if(!ht())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(...gt()),bt(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Ot=Mo(jo);Ot.use(Po());async function Nt(){let{browser:e,profileDir:t,needsSeed:o}=await _t(Ot),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Rt(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}async function Le(e){await we(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(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 Mt(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 Fo(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 Fo(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 Lo(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 Lo(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 w=g.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!w)return null;let v=h?new Date(h).toISOString():p?`${p} ${a}`.trim():a;return{sender:m,text:w,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 w of g){let v=d(w,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 w=d(f,s||"Unknown",c);w&&n.push(w)}}}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 w=u[g];if(ae(w.sender)!==f)continue;let v=ae(w.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=nt(t),s=n!==t?[t,n]:[t];for(let i of s)if(await Tt(e,i,t)){let c=await Fe(e,t);if(c.verified)return c}let r=st(n);if(r!==n&&r.length>0&&await Tt(e,r,t,{requireUnique:!0})){let l=await Fe(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function Tt(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 w=a.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",v=w.toLowerCase();if(v.includes(d)){let C=a.getBoundingClientRect();if(C.height>0){let b=w.includes(",")||/\d+ other/.test(w),A=v===u?3:v.includes(u)?2:1,D={text:w,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 Pt(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 Ge from"os";import*as _ from"path";import{fileURLToPath as wn}from"url";var qe={};ye(qe,{NAME:()=>Bo,VERSION:()=>Uo,up:()=>Jo});import*as q from"fs";import*as Ae from"path";var Uo=1,Bo="normalize-jobs-and-questions",qo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Wo=50;function Ue(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function Be(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 Jo(e,t){let o=Ae.join(e,"jobs.json"),n=Ae.join(t,"scouted-jobs.json"),s=Ae.join(e,"application-questions.json"),r=Ue(o)||{},i=Ue(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 qo)m[h]!=null&&p[h]==null&&(p[h]=m[h]);c.push(u),l++}l>0?(Be(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let d=Ue(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<=Wo?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})}Be(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];Be(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 We={};ye(We,{NAME:()=>Vo,VERSION:()=>Ho,up:()=>zo});import*as W from"fs";import*as Ft from"path";var Ho=2,Vo="reset-unread-flags";function Go(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function Yo(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}}async function zo(e){let t=Ft.join(e,"conversations.json"),o=Go(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}Yo(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:()=>Qo,VERSION:()=>Ko,up:()=>on});import*as J from"fs";import*as Lt from"path";var Ko=3,Qo="recompute-last-message-by",Xo=new Set(["draft","confirmed","rejected","needs_review"]);function Zo(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function en(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}}function tn(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!Xo.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 on(e){let t=Lt.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=tn(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}en(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 He={};ye(He,{NAME:()=>sn,VERSION:()=>nn,up:()=>an});import*as H from"fs";import*as Ut from"path";var nn=4,sn="split-connection-timestamps",rn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ln(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 cn(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 an(e){let t=Ut.join(e,"people.json"),o=ln(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++,rn.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}cn(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 un}from"url";var fn=un(import.meta.url),dn=U.dirname(U.dirname(fn)),he=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(dn,"market-research"),Ws=U.join(he,"scouted-jobs.json"),Js=U.join(he,"discovered-people.json"),Hs=U.join(he,"visit-log.json"),Vs=U.join(he,"companies.json"),Gs=U.join(he,"job-decisions.json");function Bt(){pn=null,mn=null,gn=null,hn=null,yn=null}var pn=null;var mn=null;var gn=null;var hn=null;var yn=null;var Sn=wn(import.meta.url),vn=_.dirname(Sn),bn=_.dirname(_.dirname(vn));function $n(e){return e&&(e==="~"?Ge.homedir():e.startsWith("~/")||e.startsWith("~\\")?_.join(Ge.homedir(),e.slice(2)):e)}var Y=process.env.DATA_DIR?_.resolve($n(process.env.DATA_DIR)):bn,se=_.join(Y,"collected-profiles"),re=_.join(Y,"market-research"),P=_.join(Y,".schema-version"),qt=[_.join(se,".schema-version"),_.join(re,".schema-version")],Z=4,K=[{version:1,module:qe},{version:2,module:We},{version:3,module:Je},{version:4,module:He}];(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!==Z)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${Z}. 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 Vt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
8
|
+
`)}`;try{await it.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var ko=$o(import.meta.url),Ao=z.dirname(z.dirname(ko)),Te=process.env.DATA_DIR?z.resolve(process.env.DATA_DIR,"collected-profiles"):z.join(Ao,"collected-profiles"),Oe=z.join(Te,"run-log.json");function Co(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";P.writeFileSync(n,o);for(let s=0;s<3;s++)try{P.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 ct(){try{if(!P.existsSync(Oe))return{runs:[]};let e=JSON.parse(P.readFileSync(Oe,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function at(e){P.existsSync(Te)||P.mkdirSync(Te,{recursive:!0});try{Co(Oe,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function ut(e,t="default"){let o=ct();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),at(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function Ne(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=ct(),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(a=>a.script===e.script&&a.status==="running"&&a.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)}at(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";lt({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 jo from"puppeteer";import{addExtra as Mo}from"puppeteer-extra";import Fo from"puppeteer-extra-plugin-stealth";import W from"fs";import K from"path";var Eo="cookies.json";function ft(){let e=process.env.ILML_SCOPE_DIR;return e?K.join(e,"plugins-state","linkedin","cookies.json"):Eo}function dt(){let e=ft();if(!W.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=W.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 pt(){return W.existsSync(ft())}function xo(){let e=process.env.ILML_SCOPE_DIR;return e?K.join(e,"plugins-state","linkedin"):"."}function mt(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Do(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?mt(t[1]):"default"}function gt(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return W.existsSync(t)||W.mkdirSync(t,{recursive:!0}),K.resolve(t);let o=mt(e||Do()),n=K.join(xo(),"chrome-profile",o);return W.existsSync(n)||W.mkdirSync(n,{recursive:!0}),K.resolve(n)}var ht=".ilml-seeded";function yt(e){return!W.existsSync(K.join(e,ht))}function wt(e){try{W.writeFileSync(K.join(e,ht),new Date().toISOString())}catch{}}function St(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{W.rmSync(K.join(e,o),{force:!0}),t++}catch{}return t}import je from"fs";import _o from"path";var Ro={headless:!1,defaultViewport:null,protocolTimeout:3e5},fe=new Set,vt=!1;async function ye(){let e=[...fe].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});fe.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Io(){if(vt)return;vt=!0;let e=t=>async()=>{await ye(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await ye(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await ye(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await ye(),process.exit(0))}),process.on("exit",()=>{for(let t of fe)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function Me(e){return _o.join(e,".ilml-browser-session.json")}function At(e,t={}){try{je.writeFileSync(Me(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function To(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();At(e,o?{wsEndpoint:o}:{})}catch{}}function Oo(e){let t=Ct(e);t&&t.ownerPid===process.pid&&ue(e)}function ue(e){try{je.rmSync(Me(e),{force:!0})}catch{}}function Ct(e){try{return JSON.parse(je.readFileSync(Me(e),"utf-8"))}catch{return null}}function bt(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function $t(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 kt(e,t,{probeTimeoutMs:o=4e3}={}){let n=Ct(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&bt(n.ownerPid)?"live":(ue(t),"free");let s=Symbol("timeout"),r=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await $t(r,o,s);if(i===s)return r.then(c=>{if(c)try{c.disconnect()}catch{}}),"live";if(!i)return ue(t),"free";if(bt(n.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await $t(i.close().then(()=>!0).catch(()=>!1),o,!1))return ue(t),"free";try{i.disconnect()}catch{}return"live"}function No(e,t){e&&(Io(),fe.add(e),e.on("disconnected",()=>{fe.delete(e),t&&ue(t)}))}async function Et(e,t={}){let o=gt(),n={...Ro,...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 kt(e,o)==="live")throw new Error(s);At(o);let r;try{r=await e.launch(n)}catch{if(await kt(e,o)==="live")throw new Error(s);St(o);try{r=await e.launch(n)}catch(l){throw Oo(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 No(r,o),To(o,r),{browser:r,profileDir:o,needsSeed:yt(o)}}async function xt(e,t){if(!t||!t.needsSeed)return!1;if(!pt())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(...dt()),wt(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Rt=Mo(jo);Rt.use(Fo());async function It(){let{browser:e,profileDir:t,needsSeed:o}=await Et(Rt),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await xt(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}async function Pe(e){await me(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await E(3e3)),console.log(" Inbox loaded.")}async function Tt(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 f=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",p=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,m,h;if(c.startsWith("You:"))m="me",h=c.slice(4).trim();else{let u=i.split(" ")[0];if(c.startsWith(i+":")||c.startsWith(u+":")){m="them";let g=c.indexOf(":");h=c.slice(g+1).trim()}else m="them",h=c}let d=s.getBoundingClientRect();n.push({name:i,lastMessagePreview:h,lastMessageTime:f,unread:p,lastMessageBy:m,x:d.x+d.width/2,y:d.y+d.height/2})}return n});for(let o of t)o.lastMessageTime=xe(o.lastMessageTime)||o.lastMessageTime;return t}async function Ot(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 Po(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 Dt(e,t){let o=await Po(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:a}=await Dt(e,t);if(c)return await E(500),{verified:!0,headerName:a};let f=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(f.msgCount>0&&f.allSenders.some(m=>m.toLowerCase().includes(o.toLowerCase())))return await E(300),{verified:!0,headerName:o};await E(s),r+=s}let{match:i,headerName:l}=await Dt(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function Lo(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 a=document.querySelector(".msg-overlay-conversation-bubble");a&&(i=a.querySelector(".msg-s-message-list-container")||a.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 le(e,{scrollUp:t=!0}={}){t&&await Lo(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 f=document.querySelector(".msg-overlay-conversation-bubble");f&&(r=f.querySelector(".msg-s-message-list-container")||f.querySelector(".msg-s-message-list"))}if(!r)return n;let i=r.querySelectorAll("li.msg-s-message-list__event");if(i.length===0){let f=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");f&&(i=f.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(f){let p=f.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 u=Number(d[1]);if(u>14200704e5&&u<20512224e5)return u}catch{}return null}let c="";function a(f,p,m){let h=l(f),u=f.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",g=f.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 w=h?new Date(h).toISOString():m?`${m} ${u}`.trim():u;return{sender:p,text:y,time:w}}for(let f of i){let p=f.querySelector("time.msg-s-message-list__time-heading");p&&(c=p.textContent?.trim()||c);let m=f.querySelectorAll(".msg-s-message-group");if(m.length>0)for(let h of m){let d=h.querySelector(".msg-s-message-group__name");d&&(s=d.textContent?.trim()||s);let u=s||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let w=a(y,u,c);w&&n.push(w)}}else{let h=f.querySelectorAll(".msg-s-event-listitem");for(let d of h){let u=d.querySelector(".msg-s-message-group__name");u&&(s=u.textContent?.trim()||s);let y=a(d,s||"Unknown",c);y&&n.push(y)}}}if(n.length===0){let f=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let p of f){let m=p.textContent?.trim();m&&n.push({sender:"",text:m,time:""})}}return n});for(let n of o)(!n.time||!/^\d{4}-\d{2}-\d{2}T/.test(n.time))&&(n.time=xe(n.time)||n.time);return o}function ie(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function we(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let o=m=>ie(m.sender)+"||"+ie(m.text).replace(/\s+/g,""),n=new Set(t.map(o)),s=new Set(e.map(o)),r=e.filter(m=>Y.has(m.status)?!1:!n.has(o(m))),i=t.filter(m=>!s.has(o(m))),l=t.filter(m=>s.has(o(m))),c=e.filter(m=>Y.has(m.status)),a=[...r,...l,...i],f=[];for(let m of a){let h=ie(m.text),d=ie(m.sender),u=!1;for(let g=0;g<f.length;g++){let y=f[g];if(ie(y.sender)!==d)continue;let w=ie(y.text);if(h.length>w.length&&h.endsWith(w)){u=!0;break}if(w.length>h.length&&w.endsWith(h)){f[g]=m,u=!0;break}}u||f.push(m)}return[...f,...c]}async function Se(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 p=c.getBoundingClientRect();if(p.height>0)return{x:p.x+p.width/2,y:p.y+p.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=et(t),s=n!==t?[t,n]:[t];for(let i of s)if(await _t(e,i,t)){let c=await Fe(e,t);if(c.verified)return c}let r=tt(n);if(r!==n&&r.length>0&&await _t(e,r,t,{requireUnique:!0})){let l=await Fe(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function _t(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 a=l.split(" ")[0].toLowerCase(),f=l.toLowerCase(),p=document.querySelectorAll(".msg-conversation-listitem"),m=[],h=[];for(let u of p){let y=u.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",w=y.toLowerCase();if(w.includes(a)){let v=u.getBoundingClientRect();if(v.height>0){let $=y.includes(",")||/\d+ other/.test(y),b=w===f?3:w.includes(f)?2:1,_={text:y,isGroup:$,score:b,x:v.x+v.width/2,y:v.y+v.height/2};$?h.push(_):m.push(_)}}}m.sort((u,g)=>g.score-u.score);let d=[...m,...h];return c&&d.length!==1?null:m[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 Nt(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 D from"path";import{fileURLToPath as wn}from"url";var Be={};pe(Be,{NAME:()=>Bo,VERSION:()=>Uo,up:()=>Jo});import*as L from"fs";import*as ve from"path";var Uo=1,Bo="normalize-jobs-and-questions",qo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Wo=50;function Le(e){return L.existsSync(e)?JSON.parse(L.readFileSync(e,"utf-8")):null}function Ue(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{L.writeFileSync(n,o)}catch(s){try{L.unlinkSync(n)}catch{}throw s}try{L.renameSync(n,e)}catch(s){try{L.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 Jo(e,t){let o=ve.join(e,"jobs.json"),n=ve.join(t,"scouted-jobs.json"),s=ve.join(e,"application-questions.json"),r=Le(o)||{},i=Le(n)||{},l=0,c=[];for(let f of Object.keys(r)){if(!i[f])continue;let p=i[f],m=r[f];for(let h of qo)p[h]!=null&&m[h]==null&&(m[h]=p[h]);c.push(f),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 a=Le(s);if(a&&Array.isArray(a.applications)){let f={},p=0;for(let m of a.applications){let h=m.jobId||"unknown";f[h]||(f[h]={applications:[]});let d=(m.questions||[]).map(u=>{let g={type:u.type||"input",question:u.question||"",answer:u.answer||""};return u.options&&(u.options.length<=Wo?g.options=u.options:(g.optionsOmitted=!0,p++)),u.page&&(g.page=u.page),u.wasPreFilled&&(g.wasPreFilled=!0),u.wasRetry&&(g.wasRetry=!0),g});f[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})}Ue(s,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} questions`)}else a&&!a.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(c.length>0){for(let f of c)delete i[f];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={};pe(qe,{NAME:()=>Vo,VERSION:()=>Ho,up:()=>zo});import*as U from"fs";import*as jt from"path";var Ho=2,Vo="reset-unread-flags";function Go(e){return U.existsSync(e)?JSON.parse(U.readFileSync(e,"utf-8")):null}function Yo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{U.writeFileSync(n,o)}catch(s){try{U.unlinkSync(n)}catch{}throw s}try{U.renameSync(n,e)}catch(s){try{U.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 zo(e){let t=jt.join(e,"conversations.json"),o=Go(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}Yo(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var We={};pe(We,{NAME:()=>Qo,VERSION:()=>Ko,up:()=>on});import*as B from"fs";import*as Mt from"path";var Ko=3,Qo="recompute-last-message-by",Xo=new Set(["draft","confirmed","rejected","needs_review"]);function Zo(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function en(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{B.writeFileSync(n,o)}catch(s){try{B.unlinkSync(n)}catch{}throw s}try{B.renameSync(n,e)}catch(s){try{B.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 tn(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!Xo.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 on(e){let t=Mt.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 a=Array.isArray(c.messages)?c.messages:[],f=tn(a,n),p=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=p,s++}if(s===0){console.log(" No conversations to recompute.");return}en(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 Je={};pe(Je,{NAME:()=>sn,VERSION:()=>nn,up:()=>an});import*as q from"fs";import*as Ft from"path";var nn=4,sn="split-connection-timestamps",rn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function ln(e){if(!q.existsSync(e))return null;let t=q.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function cn(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 an(e){let t=Ft.join(e,"people.json"),o=ln(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++,rn.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}cn(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 M from"path";import{fileURLToPath as un}from"url";var fn=un(import.meta.url),dn=M.dirname(M.dirname(fn)),de=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"market-research"):M.join(dn,"market-research"),Ws=M.join(de,"scouted-jobs.json"),Js=M.join(de,"discovered-people.json"),Hs=M.join(de,"visit-log.json"),Vs=M.join(de,"companies.json"),Gs=M.join(de,"job-decisions.json");function Pt(){pn=null,mn=null,gn=null,hn=null,yn=null}var pn=null;var mn=null;var gn=null;var hn=null;var yn=null;var Sn=wn(import.meta.url),vn=D.dirname(Sn),bn=D.dirname(D.dirname(vn));function $n(e){return e&&(e==="~"?Ve.homedir():e.startsWith("~/")||e.startsWith("~\\")?D.join(Ve.homedir(),e.slice(2)):e)}var J=process.env.DATA_DIR?D.resolve($n(process.env.DATA_DIR)):bn,ee=D.join(J,"collected-profiles"),te=D.join(J,"market-research"),N=D.join(J,".schema-version"),Lt=[D.join(ee,".schema-version"),D.join(te,".schema-version")],Q=4,G=[{version:1,module:Be},{version:2,module:qe},{version:3,module:We},{version:4,module:Je}];(function(){G.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of G){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=G.length?G[G.length-1].version:0;if(o!==Q)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${Q}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<G.length;n++){let s=n+1;if(G[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${G[n].version}`)}})();function Wt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
9
9
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
10
|
-
`),process.exit(1));try{S.mkdirSync(
|
|
11
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
12
|
-
`),process.exit(1))}let e;try{e=S.statSync(
|
|
13
|
-
[FATAL] DATA_DIR (${
|
|
10
|
+
`),process.exit(1));try{S.mkdirSync(J,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
11
|
+
[FATAL] Cannot create DATA_DIR (${J}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
12
|
+
`),process.exit(1))}let e;try{e=S.statSync(J)}catch(t){console.error(`
|
|
13
|
+
[FATAL] DATA_DIR (${J}) is not accessible: ${t.message}
|
|
14
14
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
15
|
-
[FATAL] DATA_DIR (${
|
|
16
|
-
`),process.exit(1));for(let t of[
|
|
15
|
+
[FATAL] DATA_DIR (${J}) 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[ee,te]){let o;try{o=S.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
|
|
17
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.
|
|
18
|
-
`),process.exit(1))}}var
|
|
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: ${
|
|
18
|
+
`),process.exit(1))}}var Z=D.join(J,".migration-lock");function kn(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return S.writeFileSync(Z,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(S.readFileSync(Z,"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(`
|
|
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: ${Z}
|
|
20
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.
|
|
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=
|
|
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=Z+".tmp";try{return S.writeFileSync(o,e),S.renameSync(o,Z),!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(Z,"utf-8")).pid!==process.pid)return;S.unlinkSync(Z)}catch{}}var Ut=!1;function An(){if(Ut)return;Ut=!0;let e=()=>{try{Ge()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Cn(){if(S.existsSync(N))return;let e=[],t=[];for(let r of Lt)if(S.existsSync(r))try{e.push({file:r,schema:be(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
|
|
22
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(`
|
|
23
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.
|
|
24
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(`
|
|
25
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.
|
|
26
|
-
`),process.exit(1)}let n=e[0].schema,s=
|
|
27
|
-
[FATAL] ${
|
|
26
|
+
`),process.exit(1)}let n=e[0].schema,s=N+".tmp";try{S.writeFileSync(s,JSON.stringify(n,null,2)),S.renameSync(s,N)}catch(r){try{S.unlinkSync(s)}catch{}throw r}for(let r of Lt)if(S.existsSync(r))try{S.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${N}`)}function En(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 be(e){let t=S.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Bt(){if(Cn(),!S.existsSync(N))return{version:0,migrations:[]};let e;try{e=be(N)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
27
|
+
[FATAL] ${N} 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
28
|
`),process.exit(1)}let t=En(e);return t===null&&(console.error(`
|
|
29
|
-
[FATAL] ${
|
|
30
|
-
`),process.exit(1)),t}function
|
|
31
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
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${
|
|
29
|
+
[FATAL] ${N} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
30
|
+
`),process.exit(1)),t}function Jt(e){try{S.chmodSync(e,384)}catch{}}function xn(e){if(Wt(),S.existsSync(N))try{if(S.lstatSync(N).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${N}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=N+".tmp";try{S.writeFileSync(t,JSON.stringify(e,null,2)),Jt(t),S.renameSync(t,N)}catch(o){try{S.unlinkSync(t)}catch{}throw o}}function qt(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(D.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let c=D.join(e,l),a=D.join(e,l+o);if(S.existsSync(a)){r++;continue}try{Vt(c,a),s++}catch(f){i.push({file:l,err:f.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${D.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 ${D.basename(e)}/ (${o})${l}`)}}var He=!1;async function Ht(){if(He)return;Wt(),Tn();let t=Bt().version;if(t===Q){He=!0;return}An(),kn(),process.on("exit",Ge),t>Q&&(console.error(`
|
|
31
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${Q}.`),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.
|
|
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${Q}.
|
|
33
33
|
`),process.exit(1)),console.log(`
|
|
34
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
34
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${Q}`);let o=On();if(!o.ok){console.error(`
|
|
35
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(`
|
|
36
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'.
|
|
37
|
-
`),process.exit(1)}let n=
|
|
38
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{
|
|
37
|
+
`),process.exit(1)}let n=G.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{qt(ee,s.version),qt(te,s.version)}catch(c){console.error(`
|
|
39
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.
|
|
40
|
-
`),process.exit(1)}let l=s.module;try{await l.up(
|
|
41
|
-
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let
|
|
42
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${
|
|
43
|
-
`))}catch(
|
|
44
|
-
`)}process.exit(1)}try{let c=new Date().toISOString(),
|
|
40
|
+
`),process.exit(1)}let l=s.module;try{await l.up(ee,te)}catch(c){console.error(`
|
|
41
|
+
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=Nn(i);a.ok?(console.error(` \u2713 Auto-rollback restored ${a.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: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
43
|
+
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
44
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:s.version,name:l.NAME||r,appliedAt:c},f=Bt();f.version=s.version,f.migratedAt=c,f.migrations=f.migrations||[],f.migrations.push(a),xn(f)}catch(c){console.error(`
|
|
45
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{
|
|
47
|
-
\u2713 Schema is now at v${
|
|
48
|
-
`)}var Dn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function _n(e){let t=e.toLowerCase();return Dn.some(o=>o.test(t))}var Rn=6e4;function In(){let e=Date.now(),t=[];for(let o of[
|
|
46
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{nt()}catch{}try{Pt()}catch{}He=!0,Ge(),console.log(`
|
|
47
|
+
\u2713 Schema is now at v${Q}
|
|
48
|
+
`)}var Dn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function _n(e){let t=e.toLowerCase();return Dn.some(o=>o.test(t))}var Rn=6e4;function In(){let e=Date.now(),t=[];for(let o of[J,ee,te]){if(!S.existsSync(o))continue;let n;try{n=S.readdirSync(o)}catch{continue}for(let s of n){if(!_n(s))continue;let r=D.join(o,s);try{let i=S.statSync(r);if(!i.isFile()||e-i.mtimeMs<Rn)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function Tn({verbose:e=!1}={}){let t=In();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: ${D.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 On(){let e=[];for(let t of[ee,te]){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=D.join(t,n);try{be(s)}catch(r){e.push({dir:D.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Nn(e){let t=[],o=[];for(let r of[ee,te]){if(!S.existsSync(r))continue;let i=S.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let c=D.join(r,l),a=l.slice(0,-e.length),f=D.join(r,a);try{a.toLowerCase().endsWith(".json")?be(c):S.accessSync(c,S.constants.R_OK),t.push({backupPath:c,originalPath:f,fileName:l,dir:r})}catch(p){o.push(`${D.basename(r)}/${l}: ${p.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{Vt(r,i),n++}catch(a){s.push(`${D.basename(c)}/${l}: ${a.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function Vt(e,t){let o=t+".tmp";try{S.copyFileSync(e,o),Jt(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 Ht();var jn=se.toLowerCase().split(/\s+/).filter(e=>e.length>1);function $e(e){if(!e)return!1;if(e===se)return!0;let t=e.toLowerCase();return jn.some(o=>t.includes(o))}function Ye(e){return(e.messages||[]).find(t=>ae.has(t.status))}function j(e){return(e.messages||[]).find(t=>Y.has(t.status))}function ze(e){return Ye(e)?.text||null}function Ke(e){return(e.messages||[]).some(t=>ae.has(t.status))}function Mn(e){return(e.messages||[]).some(t=>Y.has(t.status))}function Fn(e,t){let o=j(e);o&&(o.text=t)}function ke(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 Ae(e,t){console.error(`
|
|
49
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.
|
|
50
|
-
`)}function
|
|
50
|
+
`)}function Pn(){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=oe.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=oe.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(oe.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(oe.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(oe.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(oe.readFileSync(s,"utf-8"))}catch(r){console.error(`Cannot read batch file: ${s} \u2014 ${r.message}`),process.exit(1)}}}return e}function Ln(){let e=O(),t=Object.entries(e),o=t.length;if(o===0){console.log(`
|
|
51
51
|
No conversations synced yet. Run: npm run messages
|
|
52
|
-
`);return}let n={};for(let[,
|
|
52
|
+
`);return}let n={};for(let[,d]of t){let u=d.conversationStatus||"(none)";n[u]=(n[u]||0)+1}let s=t.filter(([,d])=>d.conversationStatus==="unanswered_by_us").sort((d,u)=>{let g=d[1].lastSynced||"";return(u[1].lastSynced||"").localeCompare(g)});console.log(`
|
|
53
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[
|
|
55
|
-
By category (${i} categorized):`);for(let[
|
|
54
|
+
By status:`);for(let[d,u]of Object.entries(n).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${u}`);let r={};for(let[,d]of t){let u=d.category||"(none)";r[u]=(r[u]||0)+1}let i=t.filter(([,d])=>d.category).length;if(i>0){console.log(`
|
|
55
|
+
By category (${i} categorized):`);for(let[d,u]of Object.entries(r).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${u}`)}let l=t.filter(([,d])=>Ke(d));if(l.length>0){let d=l.filter(([,$])=>$.conversationStatus==="unanswered_by_us"),u=l.filter(([,$])=>$.conversationStatus==="awaiting_reply"),g=l.filter(([,$])=>$.conversationStatus!=="unanswered_by_us"&&$.conversationStatus!=="awaiting_reply");console.log(`
|
|
56
56
|
\u{1F4DD} DRAFTS READY TO PUSH \u2014 ${l.length} total:
|
|
57
|
-
`);let
|
|
58
|
-
\u{1F514} FOLLOW-UP NEEDED \u2014 ${
|
|
59
|
-
`);for(let[
|
|
60
|
-
`);for(let[
|
|
61
|
-
All caught up \u2014 no unanswered messages.`);let
|
|
57
|
+
`);let y=([$,b])=>{let _=b.priority?` [${b.priority.toUpperCase()}]`:"",C=j(b),x=C?.status||A.DRAFT,k={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[x]||"",I=C?.text||"";console.log(` ${k} ${$}${_}`),console.log(` "${I.slice(0,80)}${I.length>80?"...":""}"`)};d.length>0&&(console.log(` \u2500\u2500 Replies (they wrote last) \u2014 ${d.length}:`),d.forEach(y),console.log()),u.length>0&&(console.log(` \u2500\u2500 Re-engagement (we wrote last, following up) \u2014 ${u.length}:`),u.forEach(y),console.log()),g.length>0&&(console.log(` \u2500\u2500 Other \u2014 ${g.length}:`),g.forEach(y),console.log());let w=l.filter(([,$])=>j($)?.status===A.CONFIRMED).length,v=l.filter(([,$])=>{let b=j($)?.status;return b===A.DRAFT||b===A.NEEDS_REVIEW}).length;console.log(` ${w} confirmed, ${v} pending review`),v>0&&console.log(" Review: npm run messages -- --review-drafts"),w>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let c=new Date,a=t.filter(([,d])=>d.priority&&d.conversationStatus==="awaiting_reply").filter(([,d])=>d.followUpAfter?new Date(d.followUpAfter)<=c:!0).sort((d,u)=>{let g={high:0,medium:1,low:2}[d[1].priority]??3,y={high:0,medium:1,low:2}[u[1].priority]??3;return g-y});if(a.length>0){console.log(`
|
|
58
|
+
\u{1F514} FOLLOW-UP NEEDED \u2014 ${a.length} priority contacts waiting:
|
|
59
|
+
`);for(let[d,u]of a){let g=u.priority.toUpperCase(),y=u.lastSynced?Math.floor((c-new Date(u.lastSynced))/864e5):"?",w=u.lastMessagePreview?.slice(0,50)||"";console.log(` [${g}] ${d} \u2014 ${y}d ago`),u.notes&&console.log(` \u{1F4CC} ${u.notes}`),console.log(` ${w}`),console.log()}}if(s.length>0){console.log(`\u26A1 ACTION NEEDED \u2014 ${s.length} unanswered messages:
|
|
60
|
+
`);for(let[d,u]of s){let g=Ke(u)?" [DRAFT READY]":"",y=u.priority?` [${u.priority.toUpperCase()}]`:u.suggestedPriority?` [${u.suggestedPriority}]`:"",w=u.category?` (${u.category})`:"",v=u.actionNeeded&&u.actionNeeded!=="none"?` \u2192 ${u.actionNeeded}`:"",$=u.lastMessageTime||"",b=(u.autoTags||[]).slice(0,4).join(", ");if(console.log(` ${d}${w}${y}${g}${v}`),u.summary)console.log(` ${u.summary}`);else{let _=u.lastMessagePreview?u.lastMessagePreview.slice(0,60)+(u.lastMessagePreview.length>60?"...":""):"";console.log(` ${$} | ${_}`)}b&&console.log(` #${b.replace(/, /g," #")}`),u.notes&&console.log(` \u{1F4CC} ${u.notes}`),u.profileUrl&&console.log(` ${u.profileUrl}`),console.log()}}else console.log(`
|
|
61
|
+
All caught up \u2014 no unanswered messages.`);let f=V(),p=new Set(Object.keys(e)),m=new Set(Object.values(e).map(d=>d.profileUrl).filter(Boolean)),h=Object.entries(f).filter(([d,u])=>u.connectionStatus==="connected"&&u.personActionNeeded==="initiate_contact"&&!m.has(d)&&!(u.name&&p.has(u.name))).sort((d,u)=>{let g={high:0,medium:1,low:2}[d[1].personPriority]??3,y={high:0,medium:1,low:2}[u[1].personPriority]??3;return g!==y?g-y:(u[1].connectionDate||"").localeCompare(d[1].connectionDate||"")});if(h.length>0){console.log(`
|
|
62
62
|
\u2709\uFE0F NEW CONNECTIONS TO MESSAGE \u2014 ${h.length} total:
|
|
63
|
-
`);let
|
|
64
|
-
`)}console.log()}function
|
|
63
|
+
`);let d=15;for(let[u,g]of h.slice(0,d)){let y=g.personPriority?`[${g.personPriority.toUpperCase()}]`:"",w=g.title?`${g.title}${g.company?` at ${g.company}`:""}`:g.company||"";console.log(` ${y} ${g.name||"Unknown"} \u2014 ${w}`),g.personSummary&&console.log(` ${g.personSummary}`),u&&console.log(` ${u}`),console.log()}h.length>d&&console.log(` ... and ${h.length-d} more. Run: npm run today
|
|
64
|
+
`)}console.log()}function Gt(e,t){return new Promise(o=>e.question(t,o))}async function Un(){let e=O(),t=V(),o={};for(let f of Object.values(t))f.name&&f.title&&(o[f.name]=f.title);let n={draft:0,needs_review:0,confirmed:1,rejected:2},s=Object.entries(e).filter(([,f])=>Mn(f)).sort((f,p)=>{let m=n[j(f[1])?.status]??0,h=n[j(p[1])?.status]??0;if(m!==h)return m-h;let d={high:0,medium:1,low:2}[f[1].priority]??3,u={high:0,medium:1,low:2}[p[1].priority]??3;return d-u});if(s.length===0){console.log(`
|
|
65
65
|
No drafts to review.
|
|
66
|
-
`);return}let r=s.filter(([,
|
|
66
|
+
`);return}let r=s.filter(([,f])=>{let p=j(f)?.status;return p===A.DRAFT||p===A.NEEDS_REVIEW}),i=s.filter(([,f])=>j(f)?.status===A.CONFIRMED),l=s.filter(([,f])=>j(f)?.status===A.REJECTED);console.log(`
|
|
67
67
|
\u2550\u2550 Draft Review \u2550\u2550`),console.log(` Total: ${s.length} drafts (${r.length} pending, ${i.length} confirmed, ${l.length} rejected)
|
|
68
68
|
`),console.log(` Commands: [c]onfirm [r]eject [e]dit [s]kip [q]uit
|
|
69
|
-
`);let c=
|
|
70
|
-
${"\u2550".repeat(60)}`),console.log(` ${
|
|
71
|
-
`)),h.status
|
|
72
|
-
Saved. ${
|
|
73
|
-
Reached --max=${n}, stopping.`);break}if(
|
|
74
|
-
${
|
|
75
|
-
${
|
|
76
|
-
`);let
|
|
77
|
-
Extracted ${
|
|
69
|
+
`);let c=Kt.createInterface({input:process.stdin,output:process.stdout}),a=0;for(let f=0;f<s.length;f++){let[p,m]=s[f],h=j(m),d=h?.status||A.DRAFT,u={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[d]||"?",g={high:"\u{1F534}",medium:"\u{1F7E1}",low:"\u26AA"}[m.priority]||"",y=o[p]||"",w=m.messages||[],v=m.conversationStatus||"?";if(console.log(`
|
|
70
|
+
${"\u2550".repeat(60)}`),console.log(` ${f+1}/${s.length} ${u} ${p} ${g} ${(m.priority||"").toUpperCase()}`),y&&console.log(` ${y}`),console.log(` Status: ${v} | ${w.length} msgs synced`),m.notes&&console.log(` Notes: ${m.notes}`),console.log(`${"\u2500".repeat(60)}`),w.length>0){console.log(" Conversation:");let x=w.slice(-4);w.length>4&&console.log(` ... (${w.length-4} earlier messages)`);for(let k of x){let I=k.sender||"Unknown",ne=(k.text||"").replace(/\n/g," ").substring(0,120),eo=$e(I)?" \u2192":" \u2190";console.log(` ${eo} [${I}] ${ne}`)}}else m.lastMessagePreview&&console.log(` Preview: "${m.lastMessagePreview}"`);console.log(`${"\u2500".repeat(60)}`),console.log(" Draft:");let $=ze(m)||"",b=$.match(/.{1,80}/g)||[$];for(let x of b)console.log(` ${x}`);console.log(`${"\u2500".repeat(60)}`);let C=(await Gt(c," [c]onfirm [r]eject [e]dit [s]kip [q]uit > ")).trim().toLowerCase();if(C==="c"||C==="confirm"||C==="y"||C==="yes")h.status=A.CONFIRMED,a++,console.log(" \u2705 Confirmed");else if(C==="r"||C==="reject"||C==="n"||C==="no")h.status=A.REJECTED,a++,console.log(" \u274C Rejected");else if(C==="e"||C==="edit"){console.log(" Enter new draft text (end with empty line):");let x=[];for(;;){let k=await Gt(c," ");if(k.trim()==="")break;x.push(k)}x.length>0?(Fn(m,x.join(`
|
|
71
|
+
`)),h.status=A.CONFIRMED,a++,console.log(" \u2705 Edited & Confirmed")):console.log(" (no changes)")}else if(C==="q"||C==="quit"){console.log(" Quitting review...");break}else console.log(" \u23ED Skipped")}if(c.close(),a>0){F(e);let f=Object.values(e).filter(h=>j(h)?.status===A.CONFIRMED).length,p=Object.values(e).filter(h=>j(h)?.status===A.REJECTED).length,m=Object.values(e).filter(h=>{let d=j(h)?.status;return d===A.DRAFT||d===A.NEEDS_REVIEW}).length;console.log(`
|
|
72
|
+
Saved. ${f} confirmed, ${m} pending, ${p} rejected.`),f>0&&console.log(" Ready to send: npm run messages -- --push-drafts")}console.log()}async function Qt(e){try{await Nt(e)}catch{}}async function Bn(e,t){let{full:o,max:n,verbose:s,dryRun:r}=t,i=o?"full":"incremental",l=O(),c=new Set(Object.keys(l)),a=new Map,f=0,p=0,m=3,h=0,d=3;for(;;){f++;let y=await Tt(e),w=0,v=0;for(let $ of y)$.name&&(a.has($.name)||(a.set($.name,$),c.has($.name)?v++:w++));if(s?console.log(` Round #${f}: ${w} new, ${v} known | Total: ${a.size}`):process.stdout.write(`\r Conversations found: ${a.size} (page #${f})`),a.size>=n){console.log(`
|
|
73
|
+
Reached --max=${n}, stopping.`);break}if(w===0&&v===0){if(h++,h>=d){console.log(`
|
|
74
|
+
${d} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!o&&w===0&&v>0){if(p++,p>=m){console.log(`
|
|
75
|
+
${m} pages of already-synced conversations \u2014 caught up.`);break}}else w>0&&(p=0);await Ot(e),await E(2e3)}s||process.stdout.write(`
|
|
76
|
+
`);let u=Array.from(a.values());console.log(`
|
|
77
|
+
Extracted ${u.length} conversations.`);let g=Gn(u,r);Yn(u,g,r,i)}async function qn(e,t,o){let n=V(),s=O(),r;if(t.startsWith("http")){let a=n[t],f=Object.entries(s).find(([,p])=>p.profileUrl===t);r=a?.name||f?.[0]}else r=t;if(!r){console.error(` Cannot find name for "${t}". Run inbox scan first.`);return}console.log(`
|
|
78
78
|
Reading conversation with: ${r}
|
|
79
|
-
`),await
|
|
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 et(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 y=i.length-c,k=i[i.length-1];return console.error(` \u2717 ABORT: ${y} 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 y=i[i.length-1],k=null;for(let R=i.length-1;R>=0;R--)if(i[R].sender!=="Unknown"&&i[R].sender!==""){k=i[R].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(` "${y.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let d=n.slice(0,50).toLowerCase();if(i.some(y=>y.text.toLowerCase().startsWith(d)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!s.allowDoubleMessage){let y=new Date().toISOString().slice(0,10);if(i.some(R=>{if(!Xe(R.sender))return!1;let x=R.time||"";return x.startsWith(y)||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=y=>y.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 y=0;y<Math.max(a.length,g.length);y++)if(a[y]!==g[y]){console.error(` First diff at position ${y}: expected '${a[y]||"EOF"}' got '${g[y]||"EOF"}'`),console.error(` Context: ...${a.slice(Math.max(0,y-10),y+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 w=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!w)return console.error(" Send button not found."),!1;await w.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 I=V(),O=o?I[o]:null;return O&&(O.conversationStatus="awaiting_reply",O.lastMessageSent=A,O.lastUpdated=A,be(I)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function Qt(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 eo(e,t,o,n){try{console.log(` \u2192 Profile fallback: navigating to ${o}`);try{await we(e,o,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"})}catch(y){if(y.code==="SESSION_EXPIRED")return console.error(" \u2717 Session expired \u2014 run: ilml linkedin login"),!1;throw y}await E(3e3);let s=await e.evaluate(()=>{let y=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(),y++)}let R=document.querySelector(".msg-overlay-list-bubble");if(R&&!R.classList.contains("msg-overlay-list-bubble--is-minimized")){let T=R.querySelector(".msg-overlay-bubble-header__button");T&&T.offsetHeight>0&&(T.click(),y++)}return y});s>0&&(console.log(` Closed ${s} existing overlay(s)`),await E(1500));let r=await e.evaluate(()=>{let y=document.querySelectorAll(".msg-overlay-conversation-bubble"),k=Array.from(y).filter(x=>x.offsetHeight>0),R=document.querySelector(".msg-overlay-list-bubble"),T=R?R.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 y=0;y<8&&!i;y++)i=await e.evaluate(()=>{let k=document.querySelectorAll('a[href*="recipient="]');for(let R of k)try{let T=new URL(R.getAttribute("href"),location.origin).searchParams.get("recipient");if(T)return T}catch{}return null}),i||(y===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 Re(e,'div.msg-form__contenteditable, div[contenteditable="true"][role="textbox"]',{timeout:45e3,label:"compose box"})){let y=e.url(),k=/\/premium\/|\/checkpoint\/|\/login|\/authwall/.test(y)?" \u2014 looks like a gate (premium/checkpoint/login)":"";return console.error(` \u2717 Message composer never appeared after 45s. URL: ${y.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(y=>y.length>1),p=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(p){let y=p.toLowerCase();if(!(y.includes(u)||m.some(R=>y.includes(R))))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 y=n.slice(0,50).toLowerCase();if(h.some(x=>x.text.toLowerCase().startsWith(y)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let R=new Date().toISOString().slice(0,10);if(h.some(x=>{if(!Xe(x.sender))return!1;let tt=x.time||"";return tt.startsWith(R)||tt.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()||""),w=y=>y.replace(/\s+/g," ").trim();if(w(g)!==w(n))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${w(n).slice(0,100)}..."`),console.error(` Actual: "${w(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&&w(C.inputText)===w(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 I=V(),O=I[o];return O&&(O.conversationStatus="awaiting_reply",O.lastMessageSent=D,O.lastUpdated=D,be(I)),!0}catch(s){return console.error(" \u2717 Profile send error:",s.message),!1}}async function Wn(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(`
|
|
79
|
+
`),await Pe(e);let{verified:i}=await Se(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await le(e);if(l.length===0){if(console.log(" No messages extracted (DOM may have changed)."),o){let a=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:",a)}}else{console.log(` ${l.length} messages:
|
|
80
|
+
`);for(let a of l){let f=a.time?` (${a.time})`:"";console.log(` [${a.sender}]${f}`),console.log(` ${a.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=we(s[c].messages,l),s[c].lastSynced=new Date().toISOString(),F(s),console.log(` Saved ${s[c].messages.length} messages to conversations.json ["${c}"]`)}function Qe(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=O();!n&&r[e]?.profileUrl&&(n=r[e].profileUrl)}return{personName:o,profileUrl:n}}async function Xt(e,t,o,n,s={}){console.log(" Syncing conversation thread..."),await E(1e3);let r=await le(e);console.log(` Synced ${r.length} messages from thread.`);let i=!s.conversations,l=s.conversations||O(),c=new Date().toISOString(),a=t;l[a]?(l[a].lastMessageBy="me",l[a].lastMessagePreview=n.slice(0,100),l[a].lastMessageTime=c,l[a].conversationStatus="awaiting_reply",l[a].lastSynced=c,l[a].messages=we(l[a].messages,r)):l[a]={profileUrl:o,lastSynced:c,lastMessageBy:"me",lastMessagePreview:n.slice(0,100),lastMessageTime:c,unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:r},o&&(l[a].profileUrl=o),i&&F(l);let f=V(),p=o?f[o]:null;p&&(p.conversationStatus="awaiting_reply",p.lastMessageSent=c,p.lastUpdated=c,Ie(f))}async function Xe(e,t,o,n,s={}){try{let{verified:r}=await Se(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await le(e,{scrollUp:!1}),c=O()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages visible (saved: ${c})`),i.length>c&&c>0){let v=i.length-c,$=i[i.length-1];return console.error(` \u2717 ABORT: ${v} new message(s) since last sync!`),console.error(` Latest: [${$.sender}] ${$.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let v=i[i.length-1],$=null;for(let b=i.length-1;b>=0;b--)if(i[b].sender!=="Unknown"&&i[b].sender!==""){$=i[b].sender;break}if($===se)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(` "${v.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let a=n.slice(0,50).toLowerCase();if(i.some(v=>v.text.toLowerCase().startsWith(a)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!s.allowDoubleMessage){let v=new Date().toISOString().slice(0,10);if(i.some(b=>{if(!$e(b.sender))return!1;let C=b.time||"";return C.startsWith(v)||C.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=v=>v.replace(/\s+/g," ").trim(),u=d(n),g=d(h);if(g!==u){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${u.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let v=0;v<Math.max(u.length,g.length);v++)if(u[v]!==g[v]){console.error(` First diff at position ${v}: expected '${u[v]||"EOF"}' got '${g[v]||"EOF"}'`),console.error(` Context: ...${u.slice(Math.max(0,v-10),v+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 w=await e.evaluate(()=>{let $=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),_=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(C=>(C.innerText||"").trim()).filter(Boolean).find(C=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(C))||null;return{inputText:$,error:_}});return w.error?(console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${w.error.slice(0,140)}"`),!1):w.inputText&&d(w.inputText)===d(n)?(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)."),await Xt(e,t,o,n,{conversations:s.conversations}),!0)}catch(r){return console.error(" Error sending message:",r.message),!1}}function Yt(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 Zt(e,t,o,n,s={}){try{console.log(` \u2192 Profile fallback: navigating to ${o}`);try{await me(e,o,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"})}catch(b){if(b.code==="SESSION_EXPIRED")return console.error(" \u2717 Session expired \u2014 run: ilml linkedin login"),!1;throw b}await E(3e3);let r=await e.evaluate(()=>{let b=0,_=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let x of _){if(x.offsetHeight===0)continue;let k=x.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(k||(k=x.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!k){let I=x.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");I.length>0&&(k=I[I.length-1])}k&&k.offsetHeight>0&&(k.click(),b++)}let C=document.querySelector(".msg-overlay-list-bubble");if(C&&!C.classList.contains("msg-overlay-list-bubble--is-minimized")){let x=C.querySelector(".msg-overlay-bubble-header__button");x&&x.offsetHeight>0&&(x.click(),b++)}return b});r>0&&(console.log(` Closed ${r} existing overlay(s)`),await E(1500));let i=await e.evaluate(()=>{let b=document.querySelectorAll(".msg-overlay-conversation-bubble"),_=Array.from(b).filter(k=>k.offsetHeight>0),C=document.querySelector(".msg-overlay-list-bubble"),x=C?C.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:_.length,trayMinimized:x,bubbleNames:_.map(k=>k.querySelector('a[href*="/in/"]')?.textContent?.trim()?.slice(0,30)||"?")}});i.visibleBubbles>0&&console.log(` \u26A0 Still ${i.visibleBubbles} overlay(s) open: [${i.bubbleNames.join(", ")}], tray minimized: ${i.trayMinimized}`);let l=null;for(let b=0;b<8&&!l;b++)l=await e.evaluate(()=>{let _=document.querySelectorAll('a[href*="recipient="]');for(let C of _)try{let x=new URL(C.getAttribute("href"),location.origin).searchParams.get("recipient");if(x)return x}catch{}return null}),l||(b===0&&console.log(" \u2026waiting for the profile Message link to render"),await E(1300));if(!l)return console.error(" \u2717 Could not extract recipient URN from profile after retries (Message link never rendered)"),!1;console.log(` \u2713 Extracted recipient URN: ${l.slice(0,24)}\u2026`);let c=`https://www.linkedin.com/messaging/thread/new/?recipient=${encodeURIComponent(l)}&screenContext=NON_SELF_PROFILE_VIEW`;await e.goto(c,{waitUntil:"domcontentloaded",timeout:6e4}),await E(3e3);let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;if(!await De(e,'div.msg-form__contenteditable, div[contenteditable="true"][role="textbox"]',{timeout:45e3,label:"compose box"})){let b=e.url(),_=/\/premium\/|\/checkpoint\/|\/login|\/authwall/.test(b)?" \u2014 looks like a gate (premium/checkpoint/login)":"";return console.error(` \u2717 Message composer never appeared after 45s. URL: ${b.slice(0,120)}${_}`),!1}console.log(" \u2713 Compose page loaded, message form ready");let p=t.split(" ")[0].toLowerCase(),m=t.toLowerCase().split(/[\s,]+/).filter(b=>b.length>1),h=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(h){let b=h.toLowerCase();if(!(b.includes(p)||m.some(C=>b.includes(C))))return console.error(` \u2717 Recipient mismatch: compose shows "${h}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${h}"`)}else return console.error(" \u2717 Could not confirm the recipient (compose pill unreadable) \u2014 not sending on the direct path."),!1;let d=await le(e,{scrollUp:!1});if(d.length>0){let b=n.slice(0,50).toLowerCase();if(d.some(k=>k.text.toLowerCase().startsWith(b)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let C=new Date().toISOString().slice(0,10);if(d.some(k=>{if(!$e(k.sender))return!1;let ne=k.time||"";return ne.startsWith(C)||ne.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let u=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!u)return console.error(" Message input not found in overlay."),!1;await u.click(),await E(300);let g=n.replace(/\\([!?#$])/g,"$1");g!==n&&(console.log(" Cleaned bash escape artifacts from message text"),n=g),await e.keyboard.type(n,{delay:20}),await E(500);let y=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),w=b=>b.replace(/\s+/g," ").trim();if(w(y)!==w(n))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${w(n).slice(0,100)}..."`),console.error(` Actual: "${w(y).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 $=await e.evaluate(()=>{let _=((document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText||"").trim(),x=Array.from(document.querySelectorAll('.artdeco-toast-item, .artdeco-toast-item__message, [role="alert"], .artdeco-inline-feedback--error, .msg-s-event-listitem--error')).map(k=>(k.innerText||"").trim()).filter(Boolean).find(k=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(k))||null;return{inputText:_,error:x}});return $.error?(console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${$.error.slice(0,140)}"`),!1):$.inputText&&w($.inputText)===w(n)?(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)."),await Xt(e,t,o,n,{conversations:s.conversations}),!0)}catch(r){return console.error(" \u2717 Profile send error:",r.message),!1}}async function Wn(e,t,o,n){if(!t||!o)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let s=Qe(t);if(!s)return console.error(` Person not found: ${t}`),!1;let r=ke(s.personName,o);if(!r.ok)return Ae(s.personName,r),!1;if(console.log(`
|
|
81
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
|
|
82
|
+
[DRY RUN \u2014 message not sent]`),!1;if(s.profileUrl){if(await Zt(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 Jn(e,t,o){if(console.log(`
|
|
83
83
|
\u2550\u2550 Batch send: ${t.length} messages \u2550\u2550
|
|
84
|
-
`),o){for(let
|
|
85
|
-
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`);let
|
|
84
|
+
`),o){for(let i of t){let l=i.message??i.text??"";console.log(` [DRY RUN] ${i.name}: "${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}=t[i],c=t[i].message??t[i].text;if(console.log(`
|
|
85
|
+
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`),!c){console.error(` \u2717 No message body for "${l}" \u2014 each entry needs a "text" (or "message") field`),n.push({name:l,status:"no_text"});continue}let a=Qe(l);if(!a){console.error(` \u2717 Cannot resolve: ${l}`),n.push({name:l,status:"not_found"});continue}if(!t[i].skipSalutationCheck){let p=ke(a.personName,c);if(!p.ok){Ae(a.personName,p),n.push({name:l,status:"aborted_salutation"});continue}}console.log(` Text: "${c.slice(0,100)}${c.length>100?"...":""}"`);let f=await Xe(e,a.personName,a.profileUrl,c);n.push({name:l,status:f?"sent":"failed"}),await Qt(e)}console.log(`
|
|
86
86
|
\u2550\u2550 Batch results \u2550\u2550
|
|
87
|
-
`);let s=n.filter(i=>i.status
|
|
88
|
-
Total: ${s.length} sent, ${r.length} failed/skipped`)}async function Hn(e,t){let o=
|
|
87
|
+
`);let s=n.filter(i=>i.status===A.SENT),r=n.filter(i=>i.status!==A.SENT);for(let i of n){let l=i.status===A.SENT?"\u2713":"\u2717";console.log(` ${l} ${i.name} \u2014 ${i.status}`)}console.log(`
|
|
88
|
+
Total: ${s.length} sent, ${r.length} failed/skipped`)}function zt(e,t){let o=r=>String(r||"").replace(/\s+/g,"").toLowerCase(),n=o(t);if((e.messages||[]).some(r=>!Y.has(r.status)&&$e(r.sender)&&o(r.text)===n))e.messages=(e.messages||[]).filter(r=>!(r.status===A.CONFIRMED&&r.text===t));else for(let r of e.messages||[])r.status===A.CONFIRMED&&r.text===t&&(r.status=A.SENT,r.sentAt=new Date().toISOString())}async function Hn(e,t){let o=O(),n=V(),s=Object.entries(o).filter(([,d])=>Ke(d)),r=s.filter(([,d])=>Ye(d)?.status===A.CONFIRMED),i=s.filter(([,d])=>{let u=Ye(d)?.status;return u===A.DRAFT||u===A.NEEDS_REVIEW}).length;if(s.length===0){console.log(`
|
|
89
89
|
No drafts to push. Prepare drafts in conversations.json first.
|
|
90
90
|
`);return}if(r.length===0){console.log(`
|
|
91
91
|
No confirmed drafts to push (${i} pending, need review).`),console.log(` Run: npm run messages -- --review-drafts
|
|
92
92
|
`);return}if(console.log(`
|
|
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[
|
|
94
|
-
`),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await E(4e3);let l=[],c=[];for(let
|
|
95
|
-
\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[d,u]of r){let g=Yt(d,u,n),y=u.messages?.some(v=>!ae.has(v.status)&&v.status!==A.REJECTED)?"inbox":g?"profile":"no profileUrl";console.log(` [DRY RUN] ${d} (${y}):`);let w=ze(u)||"";console.log(` "${w.slice(0,100)}${w.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 d=0;d<r.length;d++){let[u,g]=r[d],y=ze(g);console.log(`
|
|
95
|
+
\u2500\u2500 [${d+1}/${r.length}] ${u} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let w=Qe(u),v=w?.personName||u,$=w?.profileUrl||g.profileUrl||null;if(!g.skipSalutationCheck){let k=ke(u,y);if(!k.ok){Ae(u,k),l.push({name:u,status:"aborted_salutation"});continue}}let _=(g.messages||[]).filter(k=>!Y.has(k.status)).length,C=!1,x=!1;try{await Ze(e);let{verified:k}=await Se(e,v);if(k){x=!0;let I=await le(e);if(I.length>_&&_>0){let ne=I.length-_;C=!0,g.messages=we(g.messages,I),console.log(` \u26A0 ${ne} new message(s) since draft was created!`);let Ce=I[I.length-1];console.log(` Latest: [${Ce.sender}] ${Ce.text.slice(0,80)}`)}}else console.log(" Not found or wrong thread in inbox search")}catch(k){console.log(` Pre-send sync error: ${k.message}`)}if(C){for(let k of g.messages||[])k.status===A.CONFIRMED&&(k.status=A.NEEDS_REVIEW);l.push({name:u,status:A.NEEDS_REVIEW}),console.log(" \u2192 Skipped \u2014 draft needs review (new messages from them)")}else x?await Xe(e,v,$,y,{allowDoubleMessage:!0,conversations:o})?(zt(g,y),g.reviewedAtPreview=g.lastMessagePreview||"",F(o),l.push({name:u,status:"sent",method:"inbox"})):l.push({name:u,status:"failed",method:"inbox"}):(c.push({name:u,conv:g,message:y,personName:v}),console.log(" \u2192 Queued for profile fallback"));C&&F(o),await Qt(e)}if(c.length>0){console.log(`
|
|
96
96
|
\u2500\u2500 Pass 2: Profile fallback (${c.length} remaining) \u2500\u2500
|
|
97
|
-
`);for(let
|
|
98
|
-
\u2500\u2500 [profile ${
|
|
97
|
+
`);for(let d=0;d<c.length;d++){let{name:u,conv:g,message:y,personName:w}=c[d];console.log(`
|
|
98
|
+
\u2500\u2500 [profile ${d+1}/${c.length}] ${u} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let v=Yt(u,g,n);if(!v){console.error(" \u2717 No profileUrl found \u2014 cannot send via profile"),l.push({name:u,status:"failed",method:"no_url"});continue}await Zt(e,w,v,y,{conversations:o})?(zt(g,y),g.reviewedAtPreview=g.lastMessagePreview||"",F(o),l.push({name:u,status:"sent",method:"profile"})):l.push({name:u,status:"failed",method:"profile"})}}console.log(`
|
|
99
99
|
\u2550\u2550 Push results \u2550\u2550
|
|
100
|
-
`);let
|
|
101
|
-
Total: ${
|
|
100
|
+
`);let a=l.filter(d=>d.status===A.SENT),f=l.filter(d=>d.status===A.NEEDS_REVIEW),p=l.filter(d=>d.status==="failed");for(let d of l){let u={sent:"\u2713",needs_review:"\u26A0",failed:"\u2717"}[d.status]||"?",g=d.method?` (${d.method})`:"";console.log(` ${u} ${d.name} \u2014 ${d.status}${g}`)}let m=a.filter(d=>d.method==="inbox").length,h=a.filter(d=>d.method==="profile").length;console.log(`
|
|
101
|
+
Total: ${a.length} sent (${m} inbox, ${h} profile), ${f.length} need review, ${p.length} failed`)}function Vn(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 Gn(e,t){let o=O(),n=V(),s=Vn(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 f=s[l.name]?.url||null,p=o[l.name];if(p?(p.lastSynced=r,p.lastMessageBy=l.lastMessageBy,p.lastMessagePreview=l.lastMessagePreview||p.lastMessagePreview,p.lastMessageTime=l.lastMessageTime||p.lastMessageTime,p.unread=l.unread,p.conversationStatus||(p.conversationStatus=c),f&&!p.profileUrl&&(p.profileUrl=f),i.updatedConversations++):(o[l.name]={profileUrl:f,lastSynced:r,lastMessageBy:l.lastMessageBy,lastMessagePreview:l.lastMessagePreview||"",lastMessageTime:l.lastMessageTime||"",unread:l.unread||!1,conversationStatus:c,messages:[]},i.newConversations++),f){let m=n[f];m.conversationStatus=c,l.lastMessageBy==="them"&&(m.lastMessageReceived=m.lastMessageReceived||r),l.lastMessageBy==="me"&&(m.lastMessageSent=m.lastMessageSent||r),m.lastUpdated=r,i.peopleLinked++}}return t||(F(o),Ie(n)),i}function Yn(e,t,o,n){let s=O(),r=Object.entries(s),i=r.filter(([,l])=>l.conversationStatus==="unanswered_by_us").sort((l,c)=>{let a=l[1].lastSynced||"";return(c[1].lastSynced||"").localeCompare(a)});if(console.log(`
|
|
102
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(`
|
|
103
103
|
\u26A1 ACTION NEEDED \u2014 ${i.length} unanswered messages:
|
|
104
|
-
`);for(let[
|
|
104
|
+
`);for(let[a,f]of c){let p=a.padEnd(30),m=(f.lastMessageTime||"").padEnd(10),h=f.lastMessagePreview?f.lastMessagePreview.slice(0,55)+(f.lastMessagePreview.length>55?"...":""):"";console.log(` ${p} ${m} ${h}`)}i.length>15&&console.log(`
|
|
105
105
|
... and ${i.length-15} more. Use --list for full list.`)}else console.log(`
|
|
106
106
|
All caught up \u2014 no unanswered messages.`);o&&console.log(`
|
|
107
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
|
|
108
|
-
`)}async function zn(){let e=
|
|
108
|
+
`)}async function zn(){let e=Pn();if(e.list){Ln();return}if(e.reviewDrafts){await Un();return}if(e.followUp||e.followUpBatch||e.clearFollowUp){let r=O(),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 a=c.target||c.name,f=c.note||c.text||"",p=c.date||null,m=r[a];m?(m.followUpNote=f,p&&(m.followUpDate=p),i++,console.log(` + ${a} \u2014 follow-up set${p?` for ${p}`:""}: ${f.slice(0,60)}`)):(r[a]={profileUrl:null,lastSynced:new Date().toISOString(),followUpNote:f,followUpDate:p||null,messages:[]},i++,console.log(` + ${a} \u2014 new entry with follow-up${p?` for ${p}`:""}`))}}i>0&&(F(r),console.log(`
|
|
109
109
|
${i} follow-up(s) updated.
|
|
110
|
-
`));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=O(),l=0;for(let c of r){let a=i[c];a?(a.reviewedAtPreview=a.lastMessagePreview||"",l++,console.log(` + ${c} \u2014 marked as reviewed`)):console.log(` ? ${c} \u2014 not found in conversations`)}l>0?(F(i),console.log(`
|
|
111
111
|
${l} conversation(s) marked as reviewed.
|
|
112
112
|
`)):console.log(`
|
|
113
113
|
No conversations updated.
|
|
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=
|
|
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=O(),l=V(),c=0;for(let{name:a,text:f,profileUrl:p,skipSalutationCheck:m}of r){if(!a||!f){console.error(` Skipping invalid draft: name=${a}`);continue}let h=e.draft?f.replace(/\\([!?#$])/g,"$1"):f;if(!m){let g=ke(a,h);if(!g.ok){Ae(a,g);continue}}if(!i[a]){let g=p||null;if(!g){let y=Object.entries(l).filter(([,w])=>w.name===a);y.length===1?g=y[0][0]:y.length>1&&console.warn(` \u26A0 Multiple people named "${a}" \u2014 pass profileUrl in draft JSON to disambiguate`)}i[a]={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 d=i[a];d.messages||(d.messages=[]),d.messages.push({sender:se,text:h,time:new Date().toISOString(),status:A.CONFIRMED,draftedAt:new Date().toISOString()}),d.reviewedAtPreview=d.lastMessagePreview||"";let u=d.messages.filter(g=>!ae.has(g.status)&&g.status!==A.REJECTED);console.log(` Draft added for ${a}`),console.log(` Thread: ${u.length} messages + 1 draft`),console.log(` "${h.slice(0,100)}${h.length>100?"...":""}"`),console.log(),c++}F(i),console.log(` ${c} draft(s) saved. Send all: npm run messages -- --push-drafts
|
|
115
115
|
`);return}console.log(`
|
|
116
116
|
\u{1F4E8} LinkedIn Message Bot
|
|
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=
|
|
118
|
-
`),await
|
|
119
|
-
\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=ut("messages",t),{browser:n,page:s}=await It();try{if(e.read)await qn(s,e.read,e.verbose);else if(e.pushDrafts)await Hn(s,e.dryRun);else if(e.sendBatch)await Jn(s,e.sendBatch,e.dryRun);else if(e.send)await Wn(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 Bn(s,{full:e.full,max:e.max,verbose:e.verbose,dryRun:e.dryRun})}Ne(o,"success")}catch(r){console.error(`
|
|
119
|
+
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),Ne(o,"error",null,r.message)}finally{await n.close()}}zn();
|
package/dist/syncAll.mjs
CHANGED
|
@@ -242,7 +242,7 @@ function findEntryContainer(root) {
|
|
|
242
242
|
\u26A0 Browser disconnected \u2014 aborting funnel`);break}if(!w.profileUrl){console.log(`[${m+1}/${t.length}] Skipping - no URL`);continue}let g=ao(w.profileUrl);if(g==="pending"||g==="connected"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"){console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl} \u2014 skipped (db: ${g})`),g==="pending"||g==="sent_with_note"||g==="sent_without_note"||g==="sent_without_note_upsell"?d.skipped.pending++:d.skipped.connected++,a&&await a(w,d,{success:!1,reason:g,connectionSent:!1,withCustomMessage:!1,messageSent:null,method:null,error:null,profileInfo:null});continue}console.log(`[${m+1}/${t.length}] ${w.name||w.profileUrl}`);let b=null;if(r){let y=await Dn(e,w.profileUrl);y?(Te(w.profileUrl,{...y,source:u}),d.viewed++,b={success:!0,reason:"viewed",connectionSent:!1,profileInfo:y,resolvedUrl:y.resolvedUrl}):(d.errors++,b={success:!1,reason:"view_failed",connectionSent:!1,profileInfo:null})}else{if(d.connectionsSent>=i){console.log(` Max connections per session (${i}) reached`);break}let y=Xt();if(!y.allowed){console.log(` \u26A0 Global quota exhausted: ${y.reason}`);break}if(b=await Nn(e,w.profileUrl,{message:o,useCustomMessage:s,excludeLocations:l,source:u,skipQuotaGate:!0}),b.success)d.connectionsSent++;else switch(b.reason){case"pending":d.skipped.pending++;break;case"connected":d.skipped.connected++;break;case"email_required":d.skipped.email++;break;case"button_not_found":d.skipped.notFound++;break;case"excluded_location":d.skipped.excludedLocation++;break;default:d.errors++}}if(b?.fatal){console.log(`
|
|
243
243
|
\u26A0 Fatal error \u2014 page is dead, aborting funnel`),d.errors++;break}if(b?.reason==="error"){if(f++,f>=3){console.log(`
|
|
244
244
|
\u26A0 ${f} consecutive errors \u2014 aborting funnel`);break}}else f=0;if(b&&b.reason&&(lo(w.profileUrl,b.reason,{method:b.method,messageSent:b.messageSent,profileInfo:b.profileInfo}),b.resolvedUrl&&_t(w.profileUrl,b.resolvedUrl),io(w.profileUrl,{source:u||"funnel",jobId:w.jobId||w.fromJob?.jobId||null,jobTitle:w.fromJob?.title||null,jobCompany:w.fromJob?.company||null,action:b.reason})),a&&await a(w,d,b),m<t.length-1){let y=c+Math.random()*2e3;await k(y)}}if(console.log(`
|
|
245
|
-
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!r){let m=ct();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return d}var pa,Rs=fe(async()=>{Le();await Je();pa={viewProfile:Dn,detectConnectionStatus:Ce,findConnectButton:Ct,clickConnectButton:On,sendConnectionRequest:Nn,runFunnel:_s,shouldExcludeLocation:Ht}});Le();await Je();wt();await Je();wt();var Er=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),_r=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Ao=["vancouver","british columbia"],Tr=["canada","montreal","quebec","alberta","calgary","ottawa"],Rr=["toronto","ontario"],Ir=["india","pakistan","nigeria","philippines"];function Dr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Er.has(u)&&s++,_r.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Or(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),c=/remote/i.test(r)||e.workplaceType==="remote";Ir.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&Ao.some(u=>r.includes(u))?n+=22:c?n+=20:Ao.some(u=>r.includes(u))?n+=18:Tr.some(u=>r.includes(u))?n+=10:Rr.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let a=(e.seniority||"").toLowerCase();a.includes("senior")||a.includes("lead")||a.includes("staff")?n+=10:a.includes("mid")?n+=5:(a.includes("entry")||a.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let l=new Set(e.jobTags||[]);return l.has("managerial")?n+=8:l.has("senior-ic")&&(n+=5),l.has("junior")&&(n-=15),l.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function xo(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=gt(),s=J(),i=new Set,r=new Set;for(let[d,f]of Object.entries(s))f.connectionStatus==="connected"&&i.add(d);let c={connectedRecruiters:i,conversationRecruiters:r},a=ht(),l=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([d,f])=>{if(typeof f!="object"||n&&!f.isEasyApply||f.applied)return!1;let m=a[d];return!(m&&l.has(m.status))}).map(([d,f])=>({jobId:d,score:Dr(f,c),job:f})).sort((d,f)=>{if(f.score!==d.score)return f.score-d.score;let m=d.job.scoutedAt||d.job.postedTime||"";return(f.job.scoutedAt||f.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Or(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await ot();import Hr from"puppeteer";import{addExtra as Jr}from"puppeteer-extra";import Vr from"puppeteer-extra-plugin-stealth";Le();await ot();import ce from"fs";import Se from"path";var Nr="cookies.json";function Eo(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin","cookies.json"):Nr}function Ot(){let e=Eo();if(!ce.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=ce.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function _o(){return ce.existsSync(Eo())}function Mr(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin"):"."}function To(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Pr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?To(t[1]):"default"}function Ro(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0}),Se.resolve(t);let n=To(e||Pr()),o=Se.join(Mr(),"chrome-profile",n);return ce.existsSync(o)||ce.mkdirSync(o,{recursive:!0}),Se.resolve(o)}var Io=".ilml-seeded";function Do(e){return!ce.existsSync(Se.join(e,Io))}function Oo(e){try{ce.writeFileSync(Se.join(e,Io),new Date().toISOString())}catch{}}function No(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{ce.rmSync(Se.join(e,n),{force:!0}),t++}catch{}return t}import ln from"fs";import jr from"path";var Lr={headless:!1,defaultViewport:null,protocolTimeout:3e5},St=new Set,Mo=!1;async function Nt(){let e=[...St].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});St.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Fr(){if(Mo)return;Mo=!0;let e=t=>async()=>{await Nt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Nt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Nt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Nt(),process.exit(0))}),process.on("exit",()=>{for(let t of St)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function cn(e){return jr.join(e,".ilml-browser-session.json")}function Fo(e,t={}){try{ln.writeFileSync(cn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ur(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Fo(e,n?{wsEndpoint:n}:{})}catch{}}function qr(e){let t=Uo(e);t&&t.ownerPid===process.pid&&bt(e)}function bt(e){try{ln.rmSync(cn(e),{force:!0})}catch{}}function Uo(e){try{return JSON.parse(ln.readFileSync(cn(e),"utf-8"))}catch{return null}}function Po(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function jo(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Lo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Uo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Po(o.ownerPid)?"live":(bt(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await jo(i,n,s);if(r===s)return i.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!r)return bt(t),"free";if(Po(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await jo(r.close().then(()=>!0).catch(()=>!1),n,!1))return bt(t),"free";try{r.disconnect()}catch{}return"live"}function Br(e,t){e&&(Fr(),St.add(e),e.on("disconnected",()=>{St.delete(e),t&&bt(t)}))}async function qo(e,t={}){let n=Ro(),o={...Lr,...t,userDataDir:n},s=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Lo(e,n)==="live")throw new Error(s);Fo(n);let i;try{i=await e.launch(o)}catch{if(await Lo(e,n)==="live")throw new Error(s);No(n);try{i=await e.launch(o)}catch(c){throw qr(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return Br(i,n),Ur(n,i),{browser:i,profileDir:n,needsSeed:Do(n)}}async function Bo(e,t){if(!t||!t.needsSeed)return!1;if(!_o())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(...Ot()),Oo(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Vo=Jr(Hr);Vo.use(Vr());async function Wo(){let{browser:e,profileDir:t,needsSeed:n}=await qo(Vo),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Bo(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function un(e){await tt(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await k(3e3)),console.log(" Inbox loaded.")}async function Yo(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",d=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,f,m;if(a.startsWith("You:"))f="me",m=a.slice(4).trim();else{let g=r.split(" ")[0];if(a.startsWith(r+":")||a.startsWith(g+":")){f="them";let b=a.indexOf(":");m=a.slice(b+1).trim()}else f="them",m=a}let w=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:d,lastMessageBy:f,x:w.x+w.width/2,y:w.y+w.height/2})}return o});for(let n of t)n.lastMessageTime=Yt(n.lastMessageTime)||n.lastMessageTime;return t}async function fn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Wr(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function dn(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Ho(e,t){let n=await Wr(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(c=>i.includes(c)),headerName:n}}async function Mt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:a,headerName:l}=await Ho(e,t);if(a)return await k(500),{verified:!0,headerName:l};let u=await e.evaluate(()=>{let d=document.querySelectorAll(".msg-s-message-group__name"),f=Array.from(d).map(w=>w.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:f,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(f=>f.toLowerCase().includes(n.toLowerCase())))return await k(300),{verified:!0,headerName:n};await k(s),i+=s}let{match:r,headerName:c}=await Ho(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function Yr(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let l=document.querySelector(".msg-overlay-conversation-bubble");l&&(r=l.querySelector(".msg-s-message-list-container")||l.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let c=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:c}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:c})});if(!i.found||i.atTop)break;if(await k(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function mn(e,{scrollUp:t=!0}={}){t&&await Yr(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function c(u){let d=u.getAttribute("data-event-urn");if(!d)return null;let f=d.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!f)return null;try{let w=atob(f[1]).match(/^(\d{13})/);if(!w)return null;let g=Number(w[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let a="";function l(u,d,f){let m=c(u),g=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let y=b.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=m?new Date(m).toISOString():f?`${f} ${g}`.trim():g;return{sender:d,text:y,time:S}}for(let u of r){let d=u.querySelector("time.msg-s-message-list__time-heading");d&&(a=d.textContent?.trim()||a);let f=u.querySelectorAll(".msg-s-message-group");if(f.length>0)for(let m of f){let w=m.querySelector(".msg-s-message-group__name");w&&(s=w.textContent?.trim()||s);let g=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let y of b){let S=l(y,g,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let w of m){let g=w.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let y=l(w,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let d of u){let f=d.textContent?.trim();f&&o.push({sender:"",text:f,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Yt(o.time)||o.time);return n}function pn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=[...new Set(e.map(l=>l.sender).filter(l=>l&&l!=="Unknown"))],r=i.some(l=>{let u=l.toLowerCase();return u.includes(o)||s.some(d=>u.includes(d))}),c=z.toLowerCase().split(/\s+/),a=i.every(l=>{let u=l.toLowerCase();return c.some(d=>u.includes(d))});if(r)return!0;if(a){for(let l of e){let d=(l.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(d){let f=d[1].toLowerCase();if(f!=="there"&&f!=="all"&&!(s.some(w=>w===f)||f===o))return console.log(` STALE DATA: message says "Hi ${d[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let l=n.map(d=>d.toLowerCase());if(i.some(d=>{let f=d.toLowerCase();return l.some(m=>f.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ye(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function gn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=f=>Ye(f.sender)+"||"+Ye(f.text),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(f=>Fe.has(f.status)?!1:!o.has(n(f))),r=t.filter(f=>!s.has(n(f))),c=t.filter(f=>s.has(n(f))),a=e.filter(f=>Fe.has(f.status)),l=[...i,...c,...r],u=[];for(let f of l){let m=Ye(f.text),w=Ye(f.sender),g=!1;for(let b=0;b<u.length;b++){let y=u[b];if(Ye(y.sender)!==w)continue;let S=Ye(y.text);if(m.length>S.length&&m.endsWith(S)){g=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=f,g=!0;break}}g||u.push(f)}return[...u,...a]}async function Go(e,t){await un(e),await k(2500),await e.evaluate(()=>{let c=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let a of c){let l=document.querySelector(a);if(l){l.scrollTop=0;return}}}),await k(500);async function n(){return e.evaluate(c=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===c){let f=l.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let c=0;c<s&&!o;c++){let a=await fn(e);if(!a)break;if(a.scrollTop===i){if(r++,r>=2)break}else r=0,i=a.scrollTop;await k(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await k(3e3),Mt(e,t)):{verified:!1,headerName:null}}async function hn(e,t){let n=await e.evaluate(r=>{let c=document.querySelectorAll(".msg-conversation-listitem");for(let a of c)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let d=a.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await k(3e3);let r=await Mt(e,t);if(r.verified)return r}let o=zn(t),s=o!==t?[t,o]:[t];for(let r of s)if(await Jo(e,r,t)){let a=await Mt(e,t);if(a.verified)return a}let i=Kn(o);if(i!==o&&i.length>0&&await Jo(e,i,t,{requireUnique:!0})){let c=await Mt(e,t);if(c.verified)return c}return{verified:!1,headerName:null}}async function Jo(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await k(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await k(300),await i.type(t,{delay:30}),await k(500),await e.keyboard.press("Enter"),await k(3500);let r=await e.evaluate((c,a)=>{let l=c.split(" ")[0].toLowerCase(),u=c.toLowerCase(),d=document.querySelectorAll(".msg-conversation-listitem"),f=[],m=[];for(let g of d){let y=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(l)){let h=g.getBoundingClientRect();if(h.height>0){let p=y.includes(",")||/\d+ other/.test(y),v=S===u?3:S.includes(u)?2:1,C={text:y,isGroup:p,score:v,x:h.x+h.width/2,y:h.y+h.height/2};p?m.push(C):f.push(C)}}}f.sort((g,b)=>b.score-g.score);let w=[...f,...m];return a&&w.length!==1?null:f[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ve(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await k(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 k(1e3))}await Sn();import"dotenv/config";import*as ee from"fs";import*as ke from"path";import{fileURLToPath as ui}from"url";import"dotenv/config";import{createGraphClient as ri,resolveToken as ii}from"@ilivemylife/graph-sdk";import{config as ai}from"dotenv";ai();var rs=ii()||process.env.TOKEN;rs||(console.error(`
|
|
245
|
+
=== Funnel Complete ===`),console.log(` Viewed: ${d.viewed}`),console.log(` Connections sent: ${d.connectionsSent}`),console.log(` Skipped (pending): ${d.skipped.pending}`),console.log(` Skipped (connected): ${d.skipped.connected}`),console.log(` Skipped (email req): ${d.skipped.email}`),console.log(` Skipped (not found): ${d.skipped.notFound}`),d.skipped.excludedLocation>0&&console.log(` Skipped (excluded location): ${d.skipped.excludedLocation}`),console.log(` Errors: ${d.errors}`),!r){let m=ct();console.log(` Connection quota left: today ${m.daily.remaining} of ${m.daily.max} | week ${m.weekly.remaining} of ${m.weekly.max}`)}return d}var pa,Rs=fe(async()=>{Le();await Je();pa={viewProfile:Dn,detectConnectionStatus:Ce,findConnectButton:Ct,clickConnectButton:On,sendConnectionRequest:Nn,runFunnel:_s,shouldExcludeLocation:Ht}});Le();await Je();wt();await Je();wt();var Er=new Set(["java","c#",".net","scala","python","typescript","javascript","react","node.js","aws","azure","docker","kubernetes","microservices","graphql","rest","sql","postgresql","mongodb","kafka","redis","ci/cd","terraform","spring"]),_r=new Set(["iot","machine learning","ai","data engineering","spark","go","rust","kotlin","next.js","devops","sre"]),Ao=["vancouver","british columbia"],Tr=["canada","montreal","quebec","alberta","calgary","ottawa"],Rr=["toronto","ontario"],Ir=["india","pakistan","nigeria","philippines"];function Dr(e,t={}){let n=0,o=(e.techStack||[]).map(u=>u.toLowerCase()),s=0,i=0;for(let u of o)Er.has(u)&&s++,_r.has(u)&&i++;if(n+=Math.min(s*6,24),n+=Math.min(i*3,6),e.salary){let u=Or(e.salary);u&&(u>=15e4?n+=20:u>=12e4?n+=15:u>=1e5?n+=10:u>=8e4?n+=5:u>=100&&u<1e3?n+=15:u>=70&&u<1e3&&(n+=10))}let r=(e.location||"").toLowerCase(),c=/remote/i.test(r)||e.workplaceType==="remote";Ir.some(u=>r.includes(u))?n-=30:c&&/united states|usa|\bus\b/i.test(r)?n+=25:c&&Ao.some(u=>r.includes(u))?n+=22:c?n+=20:Ao.some(u=>r.includes(u))?n+=18:Tr.some(u=>r.includes(u))?n+=10:Rr.some(u=>r.includes(u))&&(n+=5),e.isEasyApply&&(n+=5);let a=(e.seniority||"").toLowerCase();a.includes("senior")||a.includes("lead")||a.includes("staff")?n+=10:a.includes("mid")?n+=5:(a.includes("entry")||a.includes("intern"))&&(n-=10),e.recruiterUrl&&(t.conversationRecruiters?.has(e.recruiterUrl)?n+=20:t.connectedRecruiters?.has(e.recruiterUrl)?n+=15:n+=3);let l=new Set(e.jobTags||[]);return l.has("managerial")?n+=8:l.has("senior-ic")&&(n+=5),l.has("junior")&&(n-=15),l.has("consultant")&&(n-=3),Math.max(0,Math.min(100,n))}function xo(e=10,t={}){let{easyApplyOnly:n=!0}=t,o=gt(),s=J(),i=new Set,r=new Set;for(let[d,f]of Object.entries(s))f.connectionStatus==="connected"&&i.add(d);let c={connectedRecruiters:i,conversationRecruiters:r},a=ht(),l=new Set(["applied","skipped","expired","archived"]);return Object.entries(o).filter(([d,f])=>{if(typeof f!="object"||n&&!f.isEasyApply||f.applied)return!1;let m=a[d];return!(m&&l.has(m.status))}).map(([d,f])=>({jobId:d,score:Dr(f,c),job:f})).sort((d,f)=>{if(f.score!==d.score)return f.score-d.score;let m=d.job.scoutedAt||d.job.postedTime||"";return(f.job.scoutedAt||f.job.postedTime||"").localeCompare(m)}).slice(0,e)}function Or(e){if(!e)return null;let t=e.match(/[\$£€CAD\s]*([\d,]+(?:\.\d+)?)\s*[kK]?/g);if(!t||t.length===0)return null;let n=t.map(o=>{let s=parseFloat(o.replace(/[^\d.]/g,""));return o.toLowerCase().includes("k")&&(s*=1e3),s}).filter(o=>o>0);return n.length>=2?(n[0]+n[1])/2:n.length===1?n[0]:null}await ot();import Hr from"puppeteer";import{addExtra as Jr}from"puppeteer-extra";import Vr from"puppeteer-extra-plugin-stealth";Le();await ot();import ce from"fs";import Se from"path";var Nr="cookies.json";function Eo(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin","cookies.json"):Nr}function Ot(){let e=Eo();if(!ce.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=ce.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function _o(){return ce.existsSync(Eo())}function Mr(){let e=process.env.ILML_SCOPE_DIR;return e?Se.join(e,"plugins-state","linkedin"):"."}function To(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function Pr(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?To(t[1]):"default"}function Ro(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0}),Se.resolve(t);let n=To(e||Pr()),o=Se.join(Mr(),"chrome-profile",n);return ce.existsSync(o)||ce.mkdirSync(o,{recursive:!0}),Se.resolve(o)}var Io=".ilml-seeded";function Do(e){return!ce.existsSync(Se.join(e,Io))}function Oo(e){try{ce.writeFileSync(Se.join(e,Io),new Date().toISOString())}catch{}}function No(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{ce.rmSync(Se.join(e,n),{force:!0}),t++}catch{}return t}import ln from"fs";import jr from"path";var Lr={headless:!1,defaultViewport:null,protocolTimeout:3e5},St=new Set,Mo=!1;async function Nt(){let e=[...St].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});St.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function Fr(){if(Mo)return;Mo=!0;let e=t=>async()=>{await Nt(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Nt(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Nt(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Nt(),process.exit(0))}),process.on("exit",()=>{for(let t of St)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function cn(e){return jr.join(e,".ilml-browser-session.json")}function Fo(e,t={}){try{ln.writeFileSync(cn(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ur(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Fo(e,n?{wsEndpoint:n}:{})}catch{}}function qr(e){let t=Uo(e);t&&t.ownerPid===process.pid&&bt(e)}function bt(e){try{ln.rmSync(cn(e),{force:!0})}catch{}}function Uo(e){try{return JSON.parse(ln.readFileSync(cn(e),"utf-8"))}catch{return null}}function Po(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function jo(e,t,n){let o,s=new Promise(r=>{o=setTimeout(()=>r(n),t)}),i=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([i,s])}async function Lo(e,t,{probeTimeoutMs:n=4e3}={}){let o=Uo(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Po(o.ownerPid)?"live":(bt(t),"free");let s=Symbol("timeout"),i=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await jo(i,n,s);if(r===s)return i.then(a=>{if(a)try{a.disconnect()}catch{}}),"live";if(!r)return bt(t),"free";if(Po(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await jo(r.close().then(()=>!0).catch(()=>!1),n,!1))return bt(t),"free";try{r.disconnect()}catch{}return"live"}function Br(e,t){e&&(Fr(),St.add(e),e.on("disconnected",()=>{St.delete(e),t&&bt(t)}))}async function qo(e,t={}){let n=Ro(),o={...Lr,...t,userDataDir:n},s=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Lo(e,n)==="live")throw new Error(s);Fo(n);let i;try{i=await e.launch(o)}catch{if(await Lo(e,n)==="live")throw new Error(s);No(n);try{i=await e.launch(o)}catch(c){throw qr(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return Br(i,n),Ur(n,i),{browser:i,profileDir:n,needsSeed:Do(n)}}async function Bo(e,t){if(!t||!t.needsSeed)return!1;if(!_o())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(...Ot()),Oo(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Vo=Jr(Hr);Vo.use(Vr());async function Wo(){let{browser:e,profileDir:t,needsSeed:n}=await qo(Vo),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Bo(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}async function un(e){await tt(e,"https://www.linkedin.com/messaging/",{readySelector:".msg-conversations-container__conversations-list, .msg-conversation-listitem",label:"inbox"})||(console.warn(" Inbox container not found via known selectors, proceeding..."),await k(3e3)),console.log(" Inbox loaded.")}async function Yo(e){let t=await e.evaluate(()=>{let n=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let s of n){let r=s.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!r)continue;let a=s.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=s.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",d=s.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||s.querySelector(".msg-conversation-card__unread-count")!==null,f,m;if(a.startsWith("You:"))f="me",m=a.slice(4).trim();else{let g=r.split(" ")[0];if(a.startsWith(r+":")||a.startsWith(g+":")){f="them";let b=a.indexOf(":");m=a.slice(b+1).trim()}else f="them",m=a}let w=s.getBoundingClientRect();o.push({name:r,lastMessagePreview:m,lastMessageTime:u,unread:d,lastMessageBy:f,x:w.x+w.width/2,y:w.y+w.height/2})}return o});for(let n of t)n.lastMessageTime=Yt(n.lastMessageTime)||n.lastMessageTime;return t}async function fn(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let s=document.querySelector(o);if(s&&s.scrollHeight>s.clientHeight)return s.scrollBy(0,600),{scrollTop:s.scrollTop,scrollHeight:s.scrollHeight}}let n=document.querySelector(".msg-conversation-listitem");if(n){let o=n.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function Wr(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,n=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let s of n){let i=document.querySelector(s);if(i){let r=i.textContent?.trim()?.replace(/\s+/g," ");if(r&&r.length>1&&r.length<100&&!t.test(r))return r}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let s of o){let i=s.textContent?.trim();if(i&&i.length>1&&i.length<100&&!/conversation/i.test(i)&&!t.test(i))return i}return null})}async function dn(e){return e.evaluate(()=>{let t=[".msg-thread__link-to-profile",'.msg-entity-lockup__entity-title a[href*="/in/"]','.msg-s-message-list-container a[href*="/in/"]','.msg-thread a[href*="/in/"]','.msg-conversations-container__title-row a[href*="/in/"]','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header a[href*="/in/"]','.msg-overlay-conversation-bubble a[href*="/in/"]'];for(let n of t){let o=document.querySelector(n);if(o){let s=o.getAttribute("href")||"";if(s&&s.includes("/in/"))return s.startsWith("/")&&(s="https://www.linkedin.com"+s),s=s.replace(/\/$/,"").split("?")[0],s}}return null})}async function Ho(e,t){let n=await Wr(e);if(!n)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(c=>c.length>1),i=n.toLowerCase();return{match:i.includes(o)||s.some(c=>i.includes(c)),headerName:n}}async function Mt(e,t){let n=t.split(" ")[0],o=8e3,s=500,i=0;for(;i<o;){let{match:a,headerName:l}=await Ho(e,t);if(a)return await k(500),{verified:!0,headerName:l};let u=await e.evaluate(()=>{let d=document.querySelectorAll(".msg-s-message-group__name"),f=Array.from(d).map(w=>w.textContent?.trim()).filter(Boolean),m=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:f,msgCount:m}});if(u.msgCount>0&&u.allSenders.some(f=>f.toLowerCase().includes(n.toLowerCase())))return await k(300),{verified:!0,headerName:n};await k(s),i+=s}let{match:r,headerName:c}=await Ho(e,t);return r?{verified:!0,headerName:c}:{verified:!1,headerName:c}}async function Yr(e){let n=0,o=0;for(let s=0;s<50;s++){let i=await e.evaluate(()=>{let r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let l=document.querySelector(".msg-overlay-conversation-bubble");l&&(r=l.querySelector(".msg-s-message-list-container")||l.querySelector(".msg-s-message-list"))}if(!r)return{found:!1};let c=r.querySelectorAll("li.msg-s-message-list__event").length;return r.scrollTop<=1?{found:!0,atTop:!0,msgCount:c}:(r.scrollTop=0,{found:!0,atTop:!1,msgCount:c})});if(!i.found||i.atTop)break;if(await k(800),i.msgCount===n){if(o++,o>=3)break}else o=0;n=i.msgCount}}async function mn(e,{scrollUp:t=!0}={}){t&&await Yr(e);let n=await e.evaluate(()=>{let o=[],s="",i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(i=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!i)return o;let r=i.querySelectorAll("li.msg-s-message-list__event");if(r.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(r=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function c(u){let d=u.getAttribute("data-event-urn");if(!d)return null;let f=d.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!f)return null;try{let w=atob(f[1]).match(/^(\d{13})/);if(!w)return null;let g=Number(w[1]);if(g>14200704e5&&g<20512224e5)return g}catch{}return null}let a="";function l(u,d,f){let m=c(u),g=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",b=u.querySelector(".msg-s-event-listitem__message-bubble");if(!b)return null;let y=b.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=m?new Date(m).toISOString():f?`${f} ${g}`.trim():g;return{sender:d,text:y,time:S}}for(let u of r){let d=u.querySelector("time.msg-s-message-list__time-heading");d&&(a=d.textContent?.trim()||a);let f=u.querySelectorAll(".msg-s-message-group");if(f.length>0)for(let m of f){let w=m.querySelector(".msg-s-message-group__name");w&&(s=w.textContent?.trim()||s);let g=s||"Unknown",b=m.querySelectorAll(".msg-s-event-listitem");for(let y of b){let S=l(y,g,a);S&&o.push(S)}}else{let m=u.querySelectorAll(".msg-s-event-listitem");for(let w of m){let g=w.querySelector(".msg-s-message-group__name");g&&(s=g.textContent?.trim()||s);let y=l(w,s||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let d of u){let f=d.textContent?.trim();f&&o.push({sender:"",text:f,time:""})}}return o});for(let o of n)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=Yt(o.time)||o.time);return n}function pn(e,t,n){if(e.length===0)return!0;let o=t.split(" ")[0].toLowerCase(),s=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),i=[...new Set(e.map(l=>l.sender).filter(l=>l&&l!=="Unknown"))],r=i.some(l=>{let u=l.toLowerCase();return u.includes(o)||s.some(d=>u.includes(d))}),c=z.toLowerCase().split(/\s+/),a=i.every(l=>{let u=l.toLowerCase();return c.some(d=>u.includes(d))});if(r)return!0;if(a){for(let l of e){let d=(l.text||"").trim().match(/^(?:Hi|Hey|Hello|Dear)\s+([A-Z][a-z]+)/);if(d){let f=d[1].toLowerCase();if(f!=="there"&&f!=="all"&&!(s.some(w=>w===f)||f===o))return console.log(` STALE DATA: message says "Hi ${d[1]}" but expected "${t}"`),!1}}return!0}if(n?.length>0){let l=n.map(d=>d.toLowerCase());if(i.some(d=>{let f=d.toLowerCase();return l.some(m=>f.includes(m.split(" ")[0]))}))return console.log(` STALE DATA: messages belong to previous conversation (senders: ${i.join(", ")})`),!1}return console.log(` Sender warning: no match for "${t}" (found: ${i.join(", ")})`),!1}function Ye(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function gn(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let n=f=>Ye(f.sender)+"||"+Ye(f.text).replace(/\s+/g,""),o=new Set(t.map(n)),s=new Set(e.map(n)),i=e.filter(f=>Fe.has(f.status)?!1:!o.has(n(f))),r=t.filter(f=>!s.has(n(f))),c=t.filter(f=>s.has(n(f))),a=e.filter(f=>Fe.has(f.status)),l=[...i,...c,...r],u=[];for(let f of l){let m=Ye(f.text),w=Ye(f.sender),g=!1;for(let b=0;b<u.length;b++){let y=u[b];if(Ye(y.sender)!==w)continue;let S=Ye(y.text);if(m.length>S.length&&m.endsWith(S)){g=!0;break}if(S.length>m.length&&S.endsWith(m)){u[b]=f,g=!0;break}}g||u.push(f)}return[...u,...a]}async function Go(e,t){await un(e),await k(2500),await e.evaluate(()=>{let c=[".msg-conversations-container__conversations-list",".msg-conversations-container"];for(let a of c){let l=document.querySelector(a);if(l){l.scrollTop=0;return}}}),await k(500);async function n(){return e.evaluate(c=>{let a=document.querySelectorAll(".msg-conversation-listitem");for(let l of a)if(l.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===c){let f=l.getBoundingClientRect();if(f.height>0)return{x:f.x+f.width/2,y:f.y+f.height/2}}return null},t)}let o=await n(),s=50,i=-1,r=0;for(let c=0;c<s&&!o;c++){let a=await fn(e);if(!a)break;if(a.scrollTop===i){if(r++,r>=2)break}else r=0,i=a.scrollTop;await k(600),o=await n()}return o?(await e.mouse.click(o.x,o.y),await k(3e3),Mt(e,t)):{verified:!1,headerName:null}}async function hn(e,t){let n=await e.evaluate(r=>{let c=document.querySelectorAll(".msg-conversation-listitem");for(let a of c)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===r){let d=a.getBoundingClientRect();if(d.height>0)return{x:d.x+d.width/2,y:d.y+d.height/2}}return null},t);if(n){await e.mouse.click(n.x,n.y),await k(3e3);let r=await Mt(e,t);if(r.verified)return r}let o=zn(t),s=o!==t?[t,o]:[t];for(let r of s)if(await Jo(e,r,t)){let a=await Mt(e,t);if(a.verified)return a}let i=Kn(o);if(i!==o&&i.length>0&&await Jo(e,i,t,{requireUnique:!0})){let c=await Mt(e,t);if(c.verified)return c}return{verified:!1,headerName:null}}async function Jo(e,t,n,o={}){let{requireUnique:s=!1}=o,i=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!i)return!1;await i.click(),await k(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await k(300),await i.type(t,{delay:30}),await k(500),await e.keyboard.press("Enter"),await k(3500);let r=await e.evaluate((c,a)=>{let l=c.split(" ")[0].toLowerCase(),u=c.toLowerCase(),d=document.querySelectorAll(".msg-conversation-listitem"),f=[],m=[];for(let g of d){let y=g.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(l)){let h=g.getBoundingClientRect();if(h.height>0){let p=y.includes(",")||/\d+ other/.test(y),v=S===u?3:S.includes(u)?2:1,C={text:y,isGroup:p,score:v,x:h.x+h.width/2,y:h.y+h.height/2};p?m.push(C):f.push(C)}}}f.sort((g,b)=>b.score-g.score);let w=[...f,...m];return a&&w.length!==1?null:f[0]||m[0]||null},n,s);return r?(s&&console.log(" (found via stripped designations)"),await e.mouse.click(r.x,r.y),!0):!1}async function ve(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await k(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 k(1e3))}await Sn();import"dotenv/config";import*as ee from"fs";import*as ke from"path";import{fileURLToPath as ui}from"url";import"dotenv/config";import{createGraphClient as ri,resolveToken as ii}from"@ilivemylife/graph-sdk";import{config as ai}from"dotenv";ai();var rs=ii()||process.env.TOKEN;rs||(console.error(`
|
|
246
246
|
[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.
|
|
247
247
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
248
248
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.8";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
|
package/ilml-plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "linkedin",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.8",
|
|
4
4
|
"description": "Reference ilml plugin: keep a local mirror of your LinkedIn data with AI-assisted workflows",
|
|
5
5
|
"commands": {
|
|
6
6
|
"help": { "run": "node dist/help.mjs", "description": "List all commands with descriptions; or `help <cmd>` for detailed info on one command (usage, flags, ban-risk, when-to-use). Reads ilml-plugin.json directly.", "usage": "ilml linkedin help [<cmd>]", "useWhen": "You forgot what a command does, or you're an AI agent picking the right tool." },
|
package/package.json
CHANGED