ilml-plugin-linkedin 1.17.0 → 1.17.2
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 +65 -65
- package/dist/syncConnections.mjs +29 -28
- 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.17.2
|
|
4
|
+
- **Sending a message is now reliable, and never falsely reports "sent".** Two fixes to `messages --send` (and the draft push): (1) it opens the conversation **directly from the person's profile URL** instead of searching for them by name — the name search was failing on accented names (e.g. "Marc-André"), refusing to send to a valid contact; (2) it now **verifies the message actually went through** before reporting success — it only says "sent" (and marks the contact messaged) once the composer has cleared and no LinkedIn error appeared. Previously it declared "sent" the instant it clicked Send, so a send that LinkedIn rejected with a "try again" error still got recorded as sent. No schema change.
|
|
5
|
+
|
|
6
|
+
## 1.17.1
|
|
7
|
+
- **Fixed: `sync-connections` was saving a contact's name with their headline glued onto it** (e.g. "Bijan SaniiSoftware Industry Executive" instead of "Bijan Sanii"). On the connections page LinkedIn puts the name and headline inside one link, and the scan read them concatenated with no separator. It now reads the name from the rendered first line only, so new scans store clean names. (Contacts already saved with a glued name still work — the name is display-only — and are tidied separately.) No schema change.
|
|
8
|
+
|
|
3
9
|
## 1.17.0
|
|
4
10
|
- **Duplicate contacts are now prevented at the source, automatically — no command to run.** A person can appear on LinkedIn under two different URLs (a permanent id-based one and their custom-name one), and different parts of the plugin used to save them as two separate contacts. Two things fix this at the root: (1) whenever any command visits a profile, the plugin records the other URL LinkedIn redirects it to; (2) every write now checks whether you already have that person under any of their known URLs before creating a record — so a second copy isn't created in the first place. Works across all flows (apply, enrich, visit, sync), adds no profile visits, and needs nothing from you. Collapsing contacts that were *already* duplicated before this version is a separate follow-up. No schema change.
|
|
5
11
|
|
package/dist/messageBot.mjs
CHANGED
|
@@ -1,122 +1,122 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Rt=Object.defineProperty;var de=(e,t)=>{for(var s in t)Rt(e,s,{get:t[s],enumerable:!0})};import*as se from"fs";import*as Dt from"readline";var be={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},_t={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function ae(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let s=parseInt(t[1],10),o=parseInt(t[2],10),n=t[3].toUpperCase()==="PM";return n&&s!==12&&(s+=12),!n&&s===12&&(s=0),{hours:s,minutes:o}}function $e(e,t){if(!e)return null;let s=e.trim();if(!s)return null;if(t=t||new Date,/^just\s*now$/i.test(s))return t.toISOString();if(/^today\b/i.test(s)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(s)){let l=ae(s),a=new Date(t);return l?a.setHours(l.hours,l.minutes,0,0):a.setHours(0,0,0,0),a.toISOString()}let o=s.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=_t[o[1].toLowerCase()],a=ae(o[2]||""),f=new Date(t),p=f.getDay()-l;return p<=0&&(p+=7),f.setDate(f.getDate()-p),a?f.setHours(a.hours,a.minutes,0,0):f.setHours(0,0,0,0),f.toISOString()}let n=s.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(n){let l=be[n[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(n[2],10),f=parseInt(n[3],10),u=ae(n[4]||"");return new Date(f,l,a,u?.hours||0,u?.minutes||0,0,0).toISOString()}let r=s.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(r){let l=be[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(r[2],10),f=ae(r[3]||""),u=t.getFullYear(),p=new Date(u,l,a,f?.hours||0,f?.minutes||0,0,0);return p>t&&p.setFullYear(u-1),p.toISOString()}let i=s.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=be[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let a=parseInt(i[2],10),f=ae(i[3]||""),u=t.getFullYear(),p=new Date(u,l,a,f?.hours||0,f?.minutes||0,0,0);return p>t&&p.setFullYear(u-1),p.toISOString()}return null}async function A(e){let t=Math.floor(Math.random()*2001),s=e+t;return new Promise(o=>setTimeout(o,s))}async function Ve(e){let t=e.url();if(t.includes("/messaging"))return!1;if(t.includes("/login")||t.includes("/authwall"))throw new Error("Session expired \u2014 redirected to login");console.log(` \u26A0 Off-track: ${t.slice(0,80)}`),console.log(" \u21BB Navigating back to /messaging/..."),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Session expired during recovery");return console.log(" \u2713 Back on messaging"),!0}function Ye(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 Ge(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 Ot}from"@ilivemylife/graph-sdk";var It=await Ot();for(let[e,t]of Object.entries(It))process.env[e]===void 0&&(process.env[e]=t);var re=process.env.LINKEDIN_NAME,$=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ce=Object.freeze(new Set([$.DRAFT,$.CONFIRMED,$.NEEDS_REVIEW])),X=Object.freeze(new Set([$.DRAFT,$.CONFIRMED,$.REJECTED,$.NEEDS_REVIEW]));import"dotenv/config";import*as I from"fs";import*as N from"path";import{fileURLToPath as Nt}from"url";var jt=Nt(import.meta.url),Mt=N.dirname(N.dirname(jt)),G=process.env.DATA_DIR?N.resolve(process.env.DATA_DIR,"collected-profiles"):N.join(Mt,"collected-profiles"),ke=N.join(G,"people.json"),kn=N.join(G,"jobs.json"),En=N.join(G,"quota.json"),pe=N.join(G,"conversations.json"),Cn=N.join(G,"sync-state.json"),An=N.join(G,"application-questions.json"),Dn=N.join(G,"profile-history"),ze=(e,t)=>{let s=parseInt(e,10);return Number.isInteger(s)&&s>=0?s:t},xn=ze(process.env.CONNECT_MAX_DAILY,20),Tn=ze(process.env.CONNECT_MAX_WEEKLY,100),ie=null,Ft=null,Pt=null,Z=null,Lt=null,Ut=null;function Ke(){ie=null,Ft=null,Pt=null,Z=null,Lt=null,Ut=null}function me(){I.existsSync(G)||I.mkdirSync(G,{recursive:!0})}function Ee(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";I.writeFileSync(o,s);for(let n=0;n<3;n++)try{I.renameSync(o,e);return}catch(r){if(n<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function Qe(e,t){if(!I.existsSync(e))return null;try{let s=JSON.parse(I.readFileSync(e,"utf-8"));try{I.copyFileSync(e,e+".backup")}catch{}return s}catch(s){console.error(`[!] ${t} is corrupted: ${s.message}`),console.error(` File: ${N.resolve(e)}`);let o=e+".backup";if(I.existsSync(o))try{let n=JSON.parse(I.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{I.copyFileSync(o,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{I.copyFileSync(e,e+".corrupted")}catch{}return null}}function V(){return ie||(me(),ie=Qe(ke,"people.json")||{},ie)}function ge(e){me(),ie=e;try{Ee(ke,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${N.resolve(ke)}`)}}function j(){return Z||(me(),Z=Qe(pe,"conversations.json")||{},Bt(Z),Z)}function Bt(e){let t=0;for(let s of Object.values(e)){if(!(s.draftStatus!==void 0||s.draftPreparedAt!==void 0))continue;let n=(s.messages||[]).find(r=>r.status==="draft");n&&s.draftStatus&&s.draftStatus!=="pending"&&(n.status=s.draftStatus),delete s.draftStatus,delete s.draftPreparedAt,t++}if(t>0){console.log(` [migration] Moved draft state from conv to msg.status for ${t} conversations`);try{Ee(pe,e)}catch{}}}function L(e){me(),Z=e;try{Ee(pe,e)}catch(t){console.error(`[!] Failed to save conversations.json: ${t.message}`),console.error(` Path: ${N.resolve(pe)}`)}}import"dotenv/config";import*as B from"fs";import*as K from"path";import{fileURLToPath as Yt}from"url";import"dotenv/config";import{createGraphClient as qt,resolveToken as Jt}from"@ilivemylife/graph-sdk";import{config as Wt}from"dotenv";Wt();var Xe=Jt()||process.env.TOKEN;Xe||(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 Ze=qt({token:Xe});function Ht(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60),o=t%60;return o?`${s}m ${o}s`:`${s}m`}function Vt({scriptName:e,mode:t,status:s,error:o,duration:n}){let r=s==="error"?"\u2717":s==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=n?` ${Ht(n)}`:"",a=s==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:s==="quota-reached"?"daily quota reached":"done",f=t&&t!=="default"?` (${t})`:"";return`${r} ${e}${f} \u2014 ${a} \u2014 ${i}${l}`}async function et({scriptName:e,mode:t,status:s,summaryLines:o,error:n,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let a=`**${Vt({scriptName:e,mode:t,status:s,error:n,duration:r})}**
|
|
6
6
|
|
|
7
7
|
${o.join(`
|
|
8
|
-
`)}`;try{await
|
|
9
|
-
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let s=await e.newPage();await s.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=
|
|
8
|
+
`)}`;try{await Ze.addMessage(i,a)}catch(f){console.error(`[runReport] Failed to post end-of-session message: ${f.message}`)}}var Gt=Yt(import.meta.url),zt=K.dirname(K.dirname(Gt)),Ce=process.env.DATA_DIR?K.resolve(process.env.DATA_DIR,"collected-profiles"):K.join(zt,"collected-profiles"),Ae=K.join(Ce,"run-log.json");function Kt(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";B.writeFileSync(o,s);for(let n=0;n<3;n++)try{B.renameSync(o,e);return}catch(r){if(n<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function tt(){try{if(!B.existsSync(Ae))return{runs:[]};let e=JSON.parse(B.readFileSync(Ae,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ot(e){B.existsSync(Ce)||B.mkdirSync(Ce,{recursive:!0});try{Kt(Ae,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function nt(e,t="default"){let s=tt();for(let i of s.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,n={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};s.runs.push(n);let r=Date.now()-30*24*60*60*1e3;return s.runs=s.runs.filter(i=>new Date(i.timestamp).getTime()>r),ot(s),{script:e,mode:t,startTime:o.getTime(),runIndex:s.runs.length-1}}function De(e,t,s=null,o=null){if(!e)return;let n=null;try{let i=tt(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=s,l.error=o,n=l.duration;else{let a=i.runs.find(f=>f.script===e.script&&f.status==="running"&&f.timestamp===new Date(e.startTime).toISOString());a&&(a.status=t,a.result=t,a.duration=Date.now()-e.startTime,a.stats=s,a.error=o,n=a.duration)}ot(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=s&&Array.isArray(s.summaryLines)?s.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":s&&s.dailyLimitHit?"quota-reached":"done";et({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:o,duration:n??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import eo from"puppeteer";import{addExtra as to}from"puppeteer-extra";import oo from"puppeteer-extra-plugin-stealth";import st from"fs";import Qt from"path";var Xt="cookies.json";function Zt(){let e=process.env.ILML_SCOPE_DIR;return e?Qt.join(e,"plugins-state","linkedin","cookies.json"):Xt}function rt(){let e=Zt();if(!st.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=st.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let s;try{s=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(s)||s.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return s}var at=to(eo);at.use(oo());async function ct(){let e=await at.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
|
|
9
|
+
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let s=await e.newPage();await s.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let o=rt();await s.setCookie(...o),console.log(" Browser launched, cookies loaded.")}catch(o){console.error(`
|
|
10
10
|
[!] ${o.message}
|
|
11
|
-
`),await e.close(),process.exit(1)}return{browser:e,page:s}}async function Te(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await x(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await x(3e3)}console.log(" Inbox loaded.")}async function ct(e){let t=await e.evaluate(()=>{let s=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let n of s){let i=n.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let a=n.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=n.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",p=n.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||n.querySelector(".msg-conversation-card__unread-count")!==null,m,h;if(a.startsWith("You:"))m="me",h=a.slice(4).trim();else{let c=i.split(" ")[0];if(a.startsWith(i+":")||a.startsWith(c+":")){m="them";let g=a.indexOf(":");h=a.slice(g+1).trim()}else m="them",h=a}let d=n.getBoundingClientRect();o.push({name:i,lastMessagePreview:h,lastMessageTime:u,unread:p,lastMessageBy:m,x:d.x+d.width/2,y:d.y+d.height/2})}return o});for(let s of t)s.lastMessageTime=$e(s.lastMessageTime)||s.lastMessageTime;return t}async function ut(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let n=document.querySelector(o);if(n&&n.scrollHeight>n.clientHeight)return n.scrollBy(0,600),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight}}let s=document.querySelector(".msg-conversation-listitem");if(s){let o=s.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function to(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,s=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let n of s){let r=document.querySelector(n);if(r){let i=r.textContent?.trim()?.replace(/\s+/g," ");if(i&&i.length>1&&i.length<100&&!t.test(i))return i}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let n of o){let r=n.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function rt(e,t){let s=await to(e);if(!s)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),n=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=s.toLowerCase();return{match:r.includes(o)||n.some(l=>r.includes(l)),headerName:s}}async function xe(e,t){let s=t.split(" ")[0],o=8e3,n=500,r=0;for(;r<o;){let{match:a,headerName:f}=await rt(e,t);if(a)return await x(500),{verified:!0,headerName:f};let u=await e.evaluate(()=>{let p=document.querySelectorAll(".msg-s-message-group__name"),m=Array.from(p).map(d=>d.textContent?.trim()).filter(Boolean),h=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:m,msgCount:h}});if(u.msgCount>0&&u.allSenders.some(m=>m.toLowerCase().includes(s.toLowerCase())))return await x(300),{verified:!0,headerName:s};await x(n),r+=n}let{match:i,headerName:l}=await rt(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function oo(e){let s=0,o=0;for(let n=0;n<50;n++){let r=await e.evaluate(()=>{let i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let f=document.querySelector(".msg-overlay-conversation-bubble");f&&(i=f.querySelector(".msg-s-message-list-container")||f.querySelector(".msg-s-message-list"))}if(!i)return{found:!1};let l=i.querySelectorAll("li.msg-s-message-list__event").length;return i.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(i.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!r.found||r.atTop)break;if(await x(800),r.msgCount===s){if(o++,o>=3)break}else o=0;s=r.msgCount}}async function Z(e,{scrollUp:t=!0}={}){t&&await oo(e);let s=await e.evaluate(()=>{let o=[],n="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(r=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!r)return o;let i=r.querySelectorAll("li.msg-s-message-list__event");if(i.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(i=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(u){let p=u.getAttribute("data-event-urn");if(!p)return null;let m=p.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!m)return null;try{let d=atob(m[1]).match(/^(\d{13})/);if(!d)return null;let c=Number(d[1]);if(c>14200704e5&&c<20512224e5)return c}catch{}return null}let a="";function f(u,p,m){let h=l(u),c=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",g=u.querySelector(".msg-s-event-listitem__message-bubble");if(!g)return null;let y=g.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let S=h?new Date(h).toISOString():m?`${m} ${c}`.trim():c;return{sender:p,text:y,time:S}}for(let u of i){let p=u.querySelector("time.msg-s-message-list__time-heading");p&&(a=p.textContent?.trim()||a);let m=u.querySelectorAll(".msg-s-message-group");if(m.length>0)for(let h of m){let d=h.querySelector(".msg-s-message-group__name");d&&(n=d.textContent?.trim()||n);let c=n||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let S=f(y,c,a);S&&o.push(S)}}else{let h=u.querySelectorAll(".msg-s-event-listitem");for(let d of h){let c=d.querySelector(".msg-s-message-group__name");c&&(n=c.textContent?.trim()||n);let y=f(d,n||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let p of u){let m=p.textContent?.trim();m&&o.push({sender:"",text:m,time:""})}}return o});for(let o of s)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=$e(o.time)||o.time);return s}function ie(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function ce(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let s=m=>ie(m.sender)+"||"+ie(m.text),o=new Set(t.map(s)),n=new Set(e.map(s)),r=e.filter(m=>Q.has(m.status)?!1:!o.has(s(m))),i=t.filter(m=>!n.has(s(m))),l=t.filter(m=>n.has(s(m))),a=e.filter(m=>Q.has(m.status)),f=[...r,...l,...i],u=[];for(let m of f){let h=ie(m.text),d=ie(m.sender),c=!1;for(let g=0;g<u.length;g++){let y=u[g];if(ie(y.sender)!==d)continue;let S=ie(y.text);if(h.length>S.length&&h.endsWith(S)){c=!0;break}if(S.length>h.length&&S.endsWith(h)){u[g]=m,c=!0;break}}c||u.push(m)}return[...u,...a]}async function he(e,t){let s=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let a of l)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let p=a.getBoundingClientRect();if(p.height>0)return{x:p.x+p.width/2,y:p.y+p.height/2}}return null},t);if(s){await e.mouse.click(s.x,s.y),await x(3e3);let i=await xe(e,t);if(i.verified)return i}let o=Ve(t),n=o!==t?[t,o]:[t];for(let i of n)if(await it(e,i,t)){let a=await xe(e,t);if(a.verified)return a}let r=Ye(o);if(r!==o&&r.length>0&&await it(e,r,t,{requireUnique:!0})){let l=await xe(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function it(e,t,s,o={}){let{requireUnique:n=!1}=o,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await x(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await x(300),await r.type(t,{delay:30}),await x(500),await e.keyboard.press("Enter"),await x(3500);let i=await e.evaluate((l,a)=>{let f=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),p=document.querySelectorAll(".msg-conversation-listitem"),m=[],h=[];for(let c of p){let y=c.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(f)){let v=c.getBoundingClientRect();if(v.height>0){let E=y.includes(",")||/\d+ other/.test(y),D=S===u?3:S.includes(u)?2:1,_={text:y,isGroup:E,score:D,x:v.x+v.width/2,y:v.y+v.height/2};E?h.push(_):m.push(_)}}}m.sort((c,g)=>g.score-c.score);let d=[...m,...h];return a&&d.length!==1?null:m[0]||h[0]||null},s,n);return i?(n&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function ft(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await x(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 x(1e3))}import"dotenv/config";import*as w from"fs";import*as Fe from"os";import*as T from"path";import{fileURLToPath as No}from"url";var Oe={};de(Oe,{NAME:()=>so,VERSION:()=>no,up:()=>lo});import*as B from"fs";import*as ye from"path";var no=1,so="normalize-jobs-and-questions",ro=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],io=50;function Re(e){return B.existsSync(e)?JSON.parse(B.readFileSync(e,"utf-8")):null}function _e(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{B.writeFileSync(o,s)}catch(n){try{B.unlinkSync(o)}catch{}throw n}try{B.renameSync(o,e)}catch(n){try{B.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function lo(e,t){let s=ye.join(e,"jobs.json"),o=ye.join(t,"scouted-jobs.json"),n=ye.join(e,"application-questions.json"),r=Re(s)||{},i=Re(o)||{},l=0,a=[];for(let u of Object.keys(r)){if(!i[u])continue;let p=i[u],m=r[u];for(let h of ro)p[h]!=null&&m[h]==null&&(m[h]=p[h]);a.push(u),l++}l>0?(_e(s,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Re(n);if(f&&Array.isArray(f.applications)){let u={},p=0;for(let m of f.applications){let h=m.jobId||"unknown";u[h]||(u[h]={applications:[]});let d=(m.questions||[]).map(c=>{let g={type:c.type||"input",question:c.question||"",answer:c.answer||""};return c.options&&(c.options.length<=io?g.options=c.options:(g.optionsOmitted=!0,p++)),c.page&&(g.page=c.page),c.wasPreFilled&&(g.wasPreFilled=!0),c.wasRetry&&(g.wasRetry=!0),g});u[h].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||d.length,questions:d})}_e(n,u),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete i[u];_e(o,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ie={};de(Ie,{NAME:()=>co,VERSION:()=>ao,up:()=>po});import*as q from"fs";import*as dt from"path";var ao=2,co="reset-unread-flags";function uo(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function fo(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{q.writeFileSync(o,s)}catch(n){try{q.unlinkSync(o)}catch{}throw n}try{q.renameSync(o,e)}catch(n){try{q.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function po(e){let t=dt.join(e,"conversations.json"),s=uo(t);if(!s){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let n of Object.keys(s))s[n].unread===!0&&(s[n].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}fo(t,s),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var je={};de(je,{NAME:()=>go,VERSION:()=>mo,up:()=>vo});import*as J from"fs";import*as pt from"path";var mo=3,go="recompute-last-message-by",ho=new Set(["draft","confirmed","rejected","needs_review"]);function yo(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function wo(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{J.writeFileSync(o,s)}catch(n){try{J.unlinkSync(o)}catch{}throw n}try{J.renameSync(o,e)}catch(n){try{J.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}function So(e,t){if(!e||e.length===0)return"them";let s=e.filter(r=>!ho.has(r.status));if(s.length===0)return"them";let o=s.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),n=o.length>0?o:[...s].reverse();for(let r of n){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function vo(e){let t=pt.join(e,"conversations.json"),s=yo(t);if(!s){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,r=0,i=0;for(let l of Object.keys(s)){let a=s[l];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let f=Array.isArray(a.messages)?a.messages:[],u=So(f,o),p=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&i++,a.lastMessageBy=u,a.conversationStatus=p,n++}if(n===0){console.log(" No conversations to recompute.");return}wo(t,s),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ne={};de(Ne,{NAME:()=>$o,VERSION:()=>bo,up:()=>Ao});import*as W from"fs";import*as mt from"path";var bo=4,$o="split-connection-timestamps",ko=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Eo(e){if(!W.existsSync(e))return null;let t=W.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Co(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,s)}catch(n){try{W.unlinkSync(o)}catch{}throw n}try{W.renameSync(o,e)}catch(n){try{W.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function Ao(e){let t=mt.join(e,"people.json"),s=Eo(t);if(!s||typeof s!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,n=0;for(let r of Object.keys(s)){let i=s[r];!i||typeof i!="object"||(n++,ko.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Co(t,s),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as L from"path";import{fileURLToPath as Do}from"url";var xo=Do(import.meta.url),To=L.dirname(L.dirname(xo)),ue=process.env.DATA_DIR?L.resolve(process.env.DATA_DIR,"market-research"):L.join(To,"market-research"),Xn=L.join(ue,"scouted-jobs.json"),Zn=L.join(ue,"discovered-people.json"),es=L.join(ue,"visit-log.json"),ts=L.join(ue,"companies.json"),os=L.join(ue,"job-decisions.json");function gt(){Ro=null,_o=null,Oo=null,Io=null,jo=null}var Ro=null;var _o=null;var Oo=null;var Io=null;var jo=null;var Mo=No(import.meta.url),Fo=T.dirname(Mo),Po=T.dirname(T.dirname(Fo));function Lo(e){return e&&(e==="~"?Fe.homedir():e.startsWith("~/")||e.startsWith("~\\")?T.join(Fe.homedir(),e.slice(2)):e)}var V=process.env.DATA_DIR?T.resolve(Lo(process.env.DATA_DIR)):Po,te=T.join(V,"collected-profiles"),oe=T.join(V,"market-research"),N=T.join(V,".schema-version"),ht=[T.join(te,".schema-version"),T.join(oe,".schema-version")],K=4,G=[{version:1,module:Oe},{version:2,module:Ie},{version:3,module:je},{version:4,module:Ne}];(function(){G.sort((o,n)=>o.version-n.version);let t=new Set;for(let o of G){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let n=o.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let s=G.length?G[G.length-1].version:0;if(s!==K)throw new Error(`MIGRATION_REGISTRY: highest version v${s} but CURRENT_SCHEMA_VERSION=${K}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<G.length;o++){let n=o+1;if(G[o].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${o} but found v${G[o].version}`)}})();function vt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
11
|
+
`),await e.close(),process.exit(1)}return{browser:e,page:s}}async function Te(e){await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let t=e.url();if(t.includes("/login")||t.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector(".msg-conversations-container__conversations-list, .msg-conversation-listitem",{timeout:15e3})}catch{console.warn(" Inbox container not found via known selectors, proceeding..."),await A(3e3)}console.log(" Inbox loaded.")}async function ut(e){let t=await e.evaluate(()=>{let s=document.querySelectorAll(".msg-conversation-listitem"),o=[];for(let n of s){let i=n.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||null;if(!i)continue;let a=n.querySelector(".msg-conversation-card__message-snippet")?.textContent?.trim()?.replace(/\s+/g," ")||"";if(/^\s*Sponsored\b/i.test(a)||/^\s*Promoted\b/i.test(a))continue;let u=n.querySelector(".msg-conversation-listitem__time-stamp, .msg-conversation-card__time-stamp")?.textContent?.trim()||"",p=n.querySelector(".msg-conversation-card__convo-item-container--unread")!==null||n.querySelector(".msg-conversation-card__unread-count")!==null,m,h;if(a.startsWith("You:"))m="me",h=a.slice(4).trim();else{let c=i.split(" ")[0];if(a.startsWith(i+":")||a.startsWith(c+":")){m="them";let g=a.indexOf(":");h=a.slice(g+1).trim()}else m="them",h=a}let d=n.getBoundingClientRect();o.push({name:i,lastMessagePreview:h,lastMessageTime:u,unread:p,lastMessageBy:m,x:d.x+d.width/2,y:d.y+d.height/2})}return o});for(let s of t)s.lastMessageTime=$e(s.lastMessageTime)||s.lastMessageTime;return t}async function ft(e){return e.evaluate(()=>{let t=[".msg-conversations-container__conversations-list",".msg-conversations-container",'[class*="msg-conversations-container"] ul'];for(let o of t){let n=document.querySelector(o);if(n&&n.scrollHeight>n.clientHeight)return n.scrollBy(0,600),{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight}}let s=document.querySelector(".msg-conversation-listitem");if(s){let o=s.parentElement;for(;o;){if(o.scrollHeight>o.clientHeight+10)return o.scrollBy(0,600),{scrollTop:o.scrollTop,scrollHeight:o.scrollHeight};o=o.parentElement}}return null})}async function no(e){return e.evaluate(()=>{let t=/^status\s+is\s+|^online$|^offline$|^away$|^busy$|^active\s/i,s=['.msg-overlay-conversation-bubble__header a[href*="/in/"] .truncate','.msg-overlay-conversation-bubble__header a[href*="/in/"]','.msg-overlay-bubble-header__title a[href*="/in/"]',".msg-overlay-bubble-header__title",".msg-overlay-conversation-bubble__header .truncate",".msg-thread__link-to-profile","h2.msg-entity-lockup__entity-title",".msg-s-message-list-container h2",".msg-thread h2",".msg-conversations-container__title-row h2",'.msg-thread a[href*="/in/"]'];for(let n of s){let r=document.querySelector(n);if(r){let i=r.textContent?.trim()?.replace(/\s+/g," ");if(i&&i.length>1&&i.length<100&&!t.test(i))return i}}let o=document.querySelectorAll(".msg-s-message-list-container h2, .msg-thread h2");for(let n of o){let r=n.textContent?.trim();if(r&&r.length>1&&r.length<100&&!/conversation/i.test(r)&&!t.test(r))return r}return null})}async function it(e,t){let s=await no(e);if(!s)return{match:!1,headerName:null};let o=t.split(" ")[0].toLowerCase(),n=t.toLowerCase().split(/[\s,]+/).filter(l=>l.length>1),r=s.toLowerCase();return{match:r.includes(o)||n.some(l=>r.includes(l)),headerName:s}}async function xe(e,t){let s=t.split(" ")[0],o=8e3,n=500,r=0;for(;r<o;){let{match:a,headerName:f}=await it(e,t);if(a)return await A(500),{verified:!0,headerName:f};let u=await e.evaluate(()=>{let p=document.querySelectorAll(".msg-s-message-group__name"),m=Array.from(p).map(d=>d.textContent?.trim()).filter(Boolean),h=document.querySelectorAll(".msg-s-event-listitem").length;return{allSenders:m,msgCount:h}});if(u.msgCount>0&&u.allSenders.some(m=>m.toLowerCase().includes(s.toLowerCase())))return await A(300),{verified:!0,headerName:s};await A(n),r+=n}let{match:i,headerName:l}=await it(e,t);return i?{verified:!0,headerName:l}:{verified:!1,headerName:l}}async function so(e){let s=0,o=0;for(let n=0;n<50;n++){let r=await e.evaluate(()=>{let i=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!i){let f=document.querySelector(".msg-overlay-conversation-bubble");f&&(i=f.querySelector(".msg-s-message-list-container")||f.querySelector(".msg-s-message-list"))}if(!i)return{found:!1};let l=i.querySelectorAll("li.msg-s-message-list__event").length;return i.scrollTop<=1?{found:!0,atTop:!0,msgCount:l}:(i.scrollTop=0,{found:!0,atTop:!1,msgCount:l})});if(!r.found||r.atTop)break;if(await A(800),r.msgCount===s){if(o++,o>=3)break}else o=0;s=r.msgCount}}async function ee(e,{scrollUp:t=!0}={}){t&&await so(e);let s=await e.evaluate(()=>{let o=[],n="",r=document.querySelector(".msg-thread .msg-s-message-list-container")||document.querySelector(".msg-s-message-list-container");if(!r){let u=document.querySelector(".msg-overlay-conversation-bubble");u&&(r=u.querySelector(".msg-s-message-list-container")||u.querySelector(".msg-s-message-list"))}if(!r)return o;let i=r.querySelectorAll("li.msg-s-message-list__event");if(i.length===0){let u=document.querySelector(".msg-overlay-conversation-bubble, .msg-overlay-list-bubble");u&&(i=u.querySelectorAll("li.msg-s-message-list__event, .msg-s-event-listitem"))}function l(u){let p=u.getAttribute("data-event-urn");if(!p)return null;let m=p.match(/,2-([A-Za-z0-9+/=]+)\)/);if(!m)return null;try{let d=atob(m[1]).match(/^(\d{13})/);if(!d)return null;let c=Number(d[1]);if(c>14200704e5&&c<20512224e5)return c}catch{}return null}let a="";function f(u,p,m){let h=l(u),c=u.querySelector(".msg-s-message-group__timestamp, time")?.textContent?.trim()||"",g=u.querySelector(".msg-s-event-listitem__message-bubble");if(!g)return null;let y=g.textContent?.trim()?.replace(/Open Emoji Keyboard|Reply to this message|React with[^.]+/g,"")?.replace(/^(?:👏\s*👍\s*😊\s*)+/,"")?.replace(/\s+/g," ")?.trim()||"";if(!y)return null;let S=h?new Date(h).toISOString():m?`${m} ${c}`.trim():c;return{sender:p,text:y,time:S}}for(let u of i){let p=u.querySelector("time.msg-s-message-list__time-heading");p&&(a=p.textContent?.trim()||a);let m=u.querySelectorAll(".msg-s-message-group");if(m.length>0)for(let h of m){let d=h.querySelector(".msg-s-message-group__name");d&&(n=d.textContent?.trim()||n);let c=n||"Unknown",g=h.querySelectorAll(".msg-s-event-listitem");for(let y of g){let S=f(y,c,a);S&&o.push(S)}}else{let h=u.querySelectorAll(".msg-s-event-listitem");for(let d of h){let c=d.querySelector(".msg-s-message-group__name");c&&(n=c.textContent?.trim()||n);let y=f(d,n||"Unknown",a);y&&o.push(y)}}}if(o.length===0){let u=document.querySelectorAll(".msg-s-event-listitem--group-a11y-heading");for(let p of u){let m=p.textContent?.trim();m&&o.push({sender:"",text:m,time:""})}}return o});for(let o of s)(!o.time||!/^\d{4}-\d{2}-\d{2}T/.test(o.time))&&(o.time=$e(o.time)||o.time);return s}function le(e){return(e||"").replace(/\s+/g," ").trim().toLowerCase()}function ue(e,t){if(!e||e.length===0)return t||[];if(!t||t.length===0)return e;let s=m=>le(m.sender)+"||"+le(m.text),o=new Set(t.map(s)),n=new Set(e.map(s)),r=e.filter(m=>X.has(m.status)?!1:!o.has(s(m))),i=t.filter(m=>!n.has(s(m))),l=t.filter(m=>n.has(s(m))),a=e.filter(m=>X.has(m.status)),f=[...r,...l,...i],u=[];for(let m of f){let h=le(m.text),d=le(m.sender),c=!1;for(let g=0;g<u.length;g++){let y=u[g];if(le(y.sender)!==d)continue;let S=le(y.text);if(h.length>S.length&&h.endsWith(S)){c=!0;break}if(S.length>h.length&&S.endsWith(h)){u[g]=m,c=!0;break}}c||u.push(m)}return[...u,...a]}async function he(e,t){let s=await e.evaluate(i=>{let l=document.querySelectorAll(".msg-conversation-listitem");for(let a of l)if(a.querySelector(".msg-conversation-listitem__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")===i){let p=a.getBoundingClientRect();if(p.height>0)return{x:p.x+p.width/2,y:p.y+p.height/2}}return null},t);if(s){await e.mouse.click(s.x,s.y),await A(3e3);let i=await xe(e,t);if(i.verified)return i}let o=Ye(t),n=o!==t?[t,o]:[t];for(let i of n)if(await lt(e,i,t)){let a=await xe(e,t);if(a.verified)return a}let r=Ge(o);if(r!==o&&r.length>0&&await lt(e,r,t,{requireUnique:!0})){let l=await xe(e,t);if(l.verified)return l}return{verified:!1,headerName:null}}async function lt(e,t,s,o={}){let{requireUnique:n=!1}=o,r=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");if(!r)return!1;await r.click(),await A(300),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await A(300),await r.type(t,{delay:30}),await A(500),await e.keyboard.press("Enter"),await A(3500);let i=await e.evaluate((l,a)=>{let f=l.split(" ")[0].toLowerCase(),u=l.toLowerCase(),p=document.querySelectorAll(".msg-conversation-listitem"),m=[],h=[];for(let c of p){let y=c.querySelector(".msg-conversation-listitem__participant-names, .msg-conversation-card__participant-names")?.textContent?.trim()?.replace(/\s+/g," ")||"",S=y.toLowerCase();if(S.includes(f)){let C=c.getBoundingClientRect();if(C.height>0){let v=y.includes(",")||/\d+ other/.test(y),D=S===u?3:S.includes(u)?2:1,O={text:y,isGroup:v,score:D,x:C.x+C.width/2,y:C.y+C.height/2};v?h.push(O):m.push(O)}}}m.sort((c,g)=>g.score-c.score);let d=[...m,...h];return a&&d.length!==1?null:m[0]||h[0]||null},s,n);return i?(n&&console.log(" (found via stripped designations)"),await e.mouse.click(i.x,i.y),!0):!1}async function dt(e){let t=await e.$("input#search-conversations, .msg-cross-pillar-search-form__search-field");t&&(await t.click(),await A(200),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),await e.keyboard.press("Escape"),await A(1e3))}import"dotenv/config";import*as w from"fs";import*as Fe from"os";import*as T from"path";import{fileURLToPath as Fo}from"url";var Oe={};de(Oe,{NAME:()=>io,VERSION:()=>ro,up:()=>co});import*as q from"fs";import*as ye from"path";var ro=1,io="normalize-jobs-and-questions",lo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],ao=50;function Re(e){return q.existsSync(e)?JSON.parse(q.readFileSync(e,"utf-8")):null}function _e(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{q.writeFileSync(o,s)}catch(n){try{q.unlinkSync(o)}catch{}throw n}try{q.renameSync(o,e)}catch(n){try{q.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function co(e,t){let s=ye.join(e,"jobs.json"),o=ye.join(t,"scouted-jobs.json"),n=ye.join(e,"application-questions.json"),r=Re(s)||{},i=Re(o)||{},l=0,a=[];for(let u of Object.keys(r)){if(!i[u])continue;let p=i[u],m=r[u];for(let h of lo)p[h]!=null&&m[h]==null&&(m[h]=p[h]);a.push(u),l++}l>0?(_e(s,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let f=Re(n);if(f&&Array.isArray(f.applications)){let u={},p=0;for(let m of f.applications){let h=m.jobId||"unknown";u[h]||(u[h]={applications:[]});let d=(m.questions||[]).map(c=>{let g={type:c.type||"input",question:c.question||"",answer:c.answer||""};return c.options&&(c.options.length<=ao?g.options=c.options:(g.optionsOmitted=!0,p++)),c.page&&(g.page=c.page),c.wasPreFilled&&(g.wasPreFilled=!0),c.wasRetry&&(g.wasRetry=!0),g});u[h].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||d.length,questions:d})}_e(n,u),console.log(` Phase 2: Rekeyed ${f.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),p>0&&console.log(` Phase 2: Stripped bloated options from ${p} questions`)}else f&&!f.applications?console.log(" Phase 2: application-questions.json already in keyed format"):console.log(" Phase 2: No application-questions.json found");if(a.length>0){for(let u of a)delete i[u];_e(o,i),console.log(` Phase 3: Removed ${a.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Ie={};de(Ie,{NAME:()=>fo,VERSION:()=>uo,up:()=>go});import*as J from"fs";import*as pt from"path";var uo=2,fo="reset-unread-flags";function po(e){return J.existsSync(e)?JSON.parse(J.readFileSync(e,"utf-8")):null}function mo(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{J.writeFileSync(o,s)}catch(n){try{J.unlinkSync(o)}catch{}throw n}try{J.renameSync(o,e)}catch(n){try{J.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function go(e){let t=pt.join(e,"conversations.json"),s=po(t);if(!s){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let n of Object.keys(s))s[n].unread===!0&&(s[n].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}mo(t,s),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Ne={};de(Ne,{NAME:()=>yo,VERSION:()=>ho,up:()=>$o});import*as W from"fs";import*as mt from"path";var ho=3,yo="recompute-last-message-by",wo=new Set(["draft","confirmed","rejected","needs_review"]);function So(e){return W.existsSync(e)?JSON.parse(W.readFileSync(e,"utf-8")):null}function vo(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{W.writeFileSync(o,s)}catch(n){try{W.unlinkSync(o)}catch{}throw n}try{W.renameSync(o,e)}catch(n){try{W.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}function bo(e,t){if(!e||e.length===0)return"them";let s=e.filter(r=>!wo.has(r.status));if(s.length===0)return"them";let o=s.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),n=o.length>0?o:[...s].reverse();for(let r of n){let i=r.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function $o(e){let t=mt.join(e,"conversations.json"),s=So(t);if(!s){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,r=0,i=0;for(let l of Object.keys(s)){let a=s[l];if(!a||typeof a!="object")continue;Object.prototype.hasOwnProperty.call(a,"_cardSynced")&&(delete a._cardSynced,r++);let f=Array.isArray(a.messages)?a.messages:[],u=bo(f,o),p=u==="me"?"awaiting_reply":"unanswered_by_us";a.lastMessageBy!==u&&i++,a.lastMessageBy=u,a.conversationStatus=p,n++}if(n===0){console.log(" No conversations to recompute.");return}vo(t,s),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var je={};de(je,{NAME:()=>Eo,VERSION:()=>ko,up:()=>xo});import*as H from"fs";import*as gt from"path";var ko=4,Eo="split-connection-timestamps",Co=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ao(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 Do(e,t){let s=JSON.stringify(t,null,2),o=e+".tmp";try{H.writeFileSync(o,s)}catch(n){try{H.unlinkSync(o)}catch{}throw n}try{H.renameSync(o,e)}catch(n){try{H.unlinkSync(o)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=n.code,r}throw n}}async function xo(e){let t=gt.join(e,"people.json"),s=Ao(t);if(!s||typeof s!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,n=0;for(let r of Object.keys(s)){let i=s[r];!i||typeof i!="object"||(n++,Co.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Do(t,s),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as U from"path";import{fileURLToPath as To}from"url";var Ro=To(import.meta.url),_o=U.dirname(U.dirname(Ro)),fe=process.env.DATA_DIR?U.resolve(process.env.DATA_DIR,"market-research"):U.join(_o,"market-research"),Zn=U.join(fe,"scouted-jobs.json"),es=U.join(fe,"discovered-people.json"),ts=U.join(fe,"visit-log.json"),os=U.join(fe,"companies.json"),ns=U.join(fe,"job-decisions.json");function ht(){Oo=null,Io=null,No=null,jo=null,Mo=null}var Oo=null;var Io=null;var No=null;var jo=null;var Mo=null;var Po=Fo(import.meta.url),Lo=T.dirname(Po),Uo=T.dirname(T.dirname(Lo));function Bo(e){return e&&(e==="~"?Fe.homedir():e.startsWith("~/")||e.startsWith("~\\")?T.join(Fe.homedir(),e.slice(2)):e)}var Y=process.env.DATA_DIR?T.resolve(Bo(process.env.DATA_DIR)):Uo,oe=T.join(Y,"collected-profiles"),ne=T.join(Y,"market-research"),F=T.join(Y,".schema-version"),yt=[T.join(oe,".schema-version"),T.join(ne,".schema-version")],Q=4,z=[{version:1,module:Oe},{version:2,module:Ie},{version:3,module:Ne},{version:4,module:je}];(function(){z.sort((o,n)=>o.version-n.version);let t=new Set;for(let o of z){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(t.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);t.add(o.version);let n=o.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let s=z.length?z[z.length-1].version:0;if(s!==Q)throw new Error(`MIGRATION_REGISTRY: highest version v${s} but CURRENT_SCHEMA_VERSION=${Q}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<z.length;o++){let n=o+1;if(z[o].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${o} but found v${z[o].version}`)}})();function bt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
12
12
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
13
|
-
`),process.exit(1));try{w.mkdirSync(
|
|
14
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
15
|
-
`),process.exit(1))}let e;try{e=w.statSync(
|
|
16
|
-
[FATAL] DATA_DIR (${
|
|
13
|
+
`),process.exit(1));try{w.mkdirSync(Y,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
14
|
+
[FATAL] Cannot create DATA_DIR (${Y}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
15
|
+
`),process.exit(1))}let e;try{e=w.statSync(Y)}catch(t){console.error(`
|
|
16
|
+
[FATAL] DATA_DIR (${Y}) is not accessible: ${t.message}
|
|
17
17
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
18
|
-
[FATAL] DATA_DIR (${
|
|
19
|
-
`),process.exit(1));for(let t of[
|
|
18
|
+
[FATAL] DATA_DIR (${Y}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
19
|
+
`),process.exit(1));for(let t of[oe,ne]){let s;try{s=w.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}s.isSymbolicLink()&&(console.error(`
|
|
20
20
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
21
|
-
`),process.exit(1))}}var
|
|
22
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
21
|
+
`),process.exit(1))}}var te=T.join(Y,".migration-lock");function qo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return w.writeFileSync(te,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(w.readFileSync(te,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let o=!1;try{process.kill(t.pid,0),o=!0}catch(i){i.code==="EPERM"&&(o=!0)}let n=24*60*60*1e3,r=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(r=Date.now()-i)}o&&r<n&&(console.error(`
|
|
22
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${te}
|
|
23
23
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
24
|
-
`),process.exit(1)),o&&r>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let s=
|
|
24
|
+
`),process.exit(1)),o&&r>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let s=te+".tmp";try{return w.writeFileSync(s,e),w.renameSync(s,te),!0}catch(o){try{w.unlinkSync(s)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function Pe(){try{if(JSON.parse(w.readFileSync(te,"utf-8")).pid!==process.pid)return;w.unlinkSync(te)}catch{}}var wt=!1;function Jo(){if(wt)return;wt=!0;let e=()=>{try{Pe()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Wo(){if(w.existsSync(F))return;let e=[],t=[];for(let r of yt)if(w.existsSync(r))try{e.push({file:r,schema:we(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
|
|
25
25
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
|
|
26
26
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
27
27
|
`),process.exit(1)}if(e.length===0)return;let s=e.map(r=>r.schema.version);if(new Set(s).size>1){console.error(`
|
|
28
28
|
[FATAL] Legacy .schema-version files disagree:`);for(let r of e)console.error(` ${r.file}: v${r.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
29
|
-
`),process.exit(1)}let o=e[0].schema,n=
|
|
30
|
-
[FATAL] ${
|
|
31
|
-
`),process.exit(1)}let t=
|
|
32
|
-
[FATAL] ${
|
|
33
|
-
`),process.exit(1)),t}function
|
|
34
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
35
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
29
|
+
`),process.exit(1)}let o=e[0].schema,n=F+".tmp";try{w.writeFileSync(n,JSON.stringify(o,null,2)),w.renameSync(n,F)}catch(r){try{w.unlinkSync(n)}catch{}throw r}for(let r of yt)if(w.existsSync(r))try{w.unlinkSync(r)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${F}`)}function Ho(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 we(e){let t=w.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function St(){if(Wo(),!w.existsSync(F))return{version:0,migrations:[]};let e;try{e=we(F)}catch(s){if(s.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
30
|
+
[FATAL] ${F} is not valid JSON: ${s.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
31
|
+
`),process.exit(1)}let t=Ho(e);return t===null&&(console.error(`
|
|
32
|
+
[FATAL] ${F} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
33
|
+
`),process.exit(1)),t}function $t(e){try{w.chmodSync(e,384)}catch{}}function Vo(e){if(bt(),w.existsSync(F))try{if(w.lstatSync(F).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${F}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(s){if(s.message?.includes("symbolic link"))throw s}let t=F+".tmp";try{w.writeFileSync(t,JSON.stringify(e,null,2)),$t(t),w.renameSync(t,F)}catch(s){try{w.unlinkSync(t)}catch{}throw s}}function vt(e,t){if(!w.existsSync(e))return;let s=`.pre-v${String(t).padStart(3,"0")}.backup`,o=w.readdirSync(e).filter(l=>{let a=l.toLowerCase();if(a.includes(".backup")||a===".schema-version"||a.endsWith(".tmp"))return!1;try{return w.statSync(T.join(e,l)).isFile()}catch{return!1}}),n=0,r=0,i=[];for(let l of o){let a=T.join(e,l),f=T.join(e,l+s);if(w.existsSync(f)){r++;continue}try{Et(a,f),n++}catch(u){i.push({file:l,err:u.message})}}if(i.length>0){let l=new Error(`Failed to back up ${i.length} file(s) in ${T.basename(e)}/: `+i.map(a=>`${a.file} (${a.err})`).join(", "));throw l.code="BACKUP_INCOMPLETE",l}if(n>0||r>0){let l=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${T.basename(e)}/ (${s})${l}`)}}var Me=!1;async function kt(){if(Me)return;bt(),Qo();let t=St().version;if(t===Q){Me=!0;return}Jo(),qo(),process.on("exit",Pe),t>Q&&(console.error(`
|
|
34
|
+
[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.
|
|
35
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${Q}.
|
|
36
36
|
`),process.exit(1)),console.log(`
|
|
37
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
37
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${Q}`);let s=Xo();if(!s.ok){console.error(`
|
|
38
38
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of s.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
|
|
39
39
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
40
|
-
`),process.exit(1)}let o=
|
|
41
|
-
Running migration v${String(n.version).padStart(3,"0")}...`);let r=`v${String(n.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{
|
|
40
|
+
`),process.exit(1)}let o=z.filter(n=>n.version>t);for(let n of o){console.log(`
|
|
41
|
+
Running migration v${String(n.version).padStart(3,"0")}...`);let r=`v${String(n.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{vt(oe,n.version),vt(ne,n.version)}catch(a){console.error(`
|
|
42
42
|
[FATAL] Pre-migration backup failed for ${r}: ${a.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
43
|
-
`),process.exit(1)}let l=n.module;try{await l.up(
|
|
44
|
-
[FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let f=
|
|
43
|
+
`),process.exit(1)}let l=n.module;try{await l.up(oe,ne)}catch(a){console.error(`
|
|
44
|
+
[FATAL] Migration ${r} failed: ${a.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let f=Zo(i);f.ok?(console.error(` \u2713 Auto-rollback restored ${f.restored} files. Schema stays at v${t}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
45
45
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${f.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
46
46
|
`))}catch(f){console.error(` [!] Auto-rollback CRASHED while restoring: ${f.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
47
|
-
`)}process.exit(1)}try{let a=new Date().toISOString(),f={version:n.version,name:l.NAME||r,appliedAt:a},u=
|
|
47
|
+
`)}process.exit(1)}try{let a=new Date().toISOString(),f={version:n.version,name:l.NAME||r,appliedAt:a},u=St();u.version=n.version,u.migratedAt=a,u.migrations=u.migrations||[],u.migrations.push(f),Vo(u)}catch(a){console.error(`
|
|
48
48
|
[FATAL] Migration ${r} applied successfully but schema version file could NOT be updated: ${a.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
49
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{
|
|
50
|
-
\u2713 Schema is now at v${
|
|
51
|
-
`)}var
|
|
49
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{Ke()}catch{}try{ht()}catch{}Me=!0,Pe(),console.log(`
|
|
50
|
+
\u2713 Schema is now at v${Q}
|
|
51
|
+
`)}var Yo=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Go(e){let t=e.toLowerCase();return Yo.some(s=>s.test(t))}var zo=6e4;function Ko(){let e=Date.now(),t=[];for(let s of[Y,oe,ne]){if(!w.existsSync(s))continue;let o;try{o=w.readdirSync(s)}catch{continue}for(let n of o){if(!Go(n))continue;let r=T.join(s,n);try{let i=w.statSync(r);if(!i.isFile()||e-i.mtimeMs<zo)continue;t.push({dir:s,file:n,fullPath:r})}catch{}}}return t}function Qo({verbose:e=!1}={}){let t=Ko();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let s=0;for(let o of t)try{w.unlinkSync(o.fullPath),s++,e&&console.log(` Removed orphan: ${T.basename(o.dir)}/${o.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${n.message}`)}return!e&&s>0&&console.log(` Cleaned up ${s} orphan .tmp file(s) from previous run.`),s}function Xo(){let e=[];for(let t of[oe,ne]){if(!w.existsSync(t))continue;let s=w.readdirSync(t).filter(o=>{let n=o.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let o of s){let n=T.join(t,o);try{we(n)}catch(r){e.push({dir:T.basename(t),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Zo(e){let t=[],s=[];for(let r of[oe,ne]){if(!w.existsSync(r))continue;let i=w.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let a=T.join(r,l),f=l.slice(0,-e.length),u=T.join(r,f);try{f.toLowerCase().endsWith(".json")?we(a):w.accessSync(a,w.constants.R_OK),t.push({backupPath:a,originalPath:u,fileName:l,dir:r})}catch(p){s.push(`${T.basename(r)}/${l}: ${p.message}`)}}}if(s.length>0)return{ok:!1,error:s.join("; "),restored:0};let o=0,n=[];for(let{backupPath:r,originalPath:i,fileName:l,dir:a}of t)try{Et(r,i),o++}catch(f){n.push(`${T.basename(a)}/${l}: ${f.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:o}:{ok:!0,restored:o}}function Et(e,t){let s=t+".tmp";try{w.copyFileSync(e,s),$t(s)}catch(o){try{w.unlinkSync(s)}catch{}throw o}try{w.renameSync(s,t)}catch(o){try{w.unlinkSync(s)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let n=new Error(`File locked: ${t} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw n.code=o.code,n}throw o}}await kt();var en=re.toLowerCase().split(/\s+/).filter(e=>e.length>1);function qe(e){if(!e)return!1;if(e===re)return!0;let t=e.toLowerCase();return en.some(s=>t.includes(s))}function Le(e){return(e.messages||[]).find(t=>ce.has(t.status))}function P(e){return(e.messages||[]).find(t=>X.has(t.status))}function Ue(e){return Le(e)?.text||null}function Be(e){return(e.messages||[]).some(t=>ce.has(t.status))}function tn(e){return(e.messages||[]).some(t=>X.has(t.status))}function on(e,t){let s=P(e);s&&(s.text=t)}function Se(e,t){if(!e||typeof t!="string")return{ok:!0};let s=t.match(/^\s*(?:hi|hello|hey)[,\s\-—]+([A-Z][A-Za-z'\-]*)/i);if(!s)return{ok:!0};let o=s[1],n=e.split(/[\s,]+/)[0],r=o.toLowerCase(),i=n.toLowerCase();return i.startsWith(r)||r.startsWith(i)?{ok:!0}:{ok:!1,greeted:o,convFirstWord:n,reason:`message opens with "Hi ${o}" but conv key's first word is "${n}"`}}function ve(e,t){console.error(`
|
|
52
52
|
\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.
|
|
53
|
-
`)}function
|
|
53
|
+
`)}function nn(){let e={list:!1,full:!1,read:null,send:null,sendBatch:null,pushDrafts:!1,reviewDrafts:!1,max:1/0,dryRun:!1,verbose:!1},t=process.argv.slice(2);for(let s=0;s<t.length;s++){let o=t[s];if(o==="--list")e.list=!0;else if(o==="--full")e.full=!0;else if(o==="--dry-run")e.dryRun=!0;else if(o==="--verbose")e.verbose=!0;else if(o.startsWith("--max="))e.max=parseInt(o.split("=")[1],10);else if(o==="--read")e.read=t[++s]||null;else if(o==="--send"){let n=t[++s],r=t[++s]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=se.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.send={target:n,text:r}}else if(o==="--draft"){let n=t[++s],r=t[++s]||"";if(r.startsWith("@")){let i=r.slice(1);try{r=se.readFileSync(i,"utf-8").trim()}catch{console.error(`Cannot read message file: ${i}`),process.exit(1)}}e.draft={target:n,text:r}}else if(o==="--push-drafts")e.pushDrafts=!0;else if(o==="--review-drafts")e.reviewDrafts=!0;else if(o==="--follow-up"){let n=t[++s],r=t[++s]||"",i=t[++s]||null;e.followUp={target:n,note:r,date:i}}else if(o==="--follow-up-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.followUpBatch=JSON.parse(se.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read follow-up batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--clear-follow-up")e.clearFollowUp=t[++s]||null;else if(o==="--review")e.review=t[++s]||null;else if(o==="--review-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.reviewBatch=JSON.parse(se.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read review batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--draft-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.draftBatch=JSON.parse(se.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read draft batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}else if(o==="--send-batch"){let n=t[++s]||"";n.startsWith("@")&&(n=n.slice(1));try{e.sendBatch=JSON.parse(se.readFileSync(n,"utf-8"))}catch(r){console.error(`Cannot read batch file: ${n} \u2014 ${r.message}`),process.exit(1)}}}return e}function sn(){let e=j(),t=Object.entries(e),s=t.length;if(s===0){console.log(`
|
|
54
54
|
No conversations synced yet. Run: npm run messages
|
|
55
55
|
`);return}let o={};for(let[,d]of t){let c=d.conversationStatus||"(none)";o[c]=(o[c]||0)+1}let n=t.filter(([,d])=>d.conversationStatus==="unanswered_by_us").sort((d,c)=>{let g=d[1].lastSynced||"";return(c[1].lastSynced||"").localeCompare(g)});console.log(`
|
|
56
56
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` Conversations: ${s} total`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(`
|
|
57
57
|
By status:`);for(let[d,c]of Object.entries(o).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${c}`);let r={};for(let[,d]of t){let c=d.category||"(none)";r[c]=(r[c]||0)+1}let i=t.filter(([,d])=>d.category).length;if(i>0){console.log(`
|
|
58
|
-
By category (${i} categorized):`);for(let[d,c]of Object.entries(r).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${c}`)}let l=t.filter(([,d])=>Be(d));if(l.length>0){let d=l.filter(([,
|
|
58
|
+
By category (${i} categorized):`);for(let[d,c]of Object.entries(r).sort((g,y)=>y[1]-g[1]))console.log(` ${d.padEnd(25)} ${c}`)}let l=t.filter(([,d])=>Be(d));if(l.length>0){let d=l.filter(([,v])=>v.conversationStatus==="unanswered_by_us"),c=l.filter(([,v])=>v.conversationStatus==="awaiting_reply"),g=l.filter(([,v])=>v.conversationStatus!=="unanswered_by_us"&&v.conversationStatus!=="awaiting_reply");console.log(`
|
|
59
59
|
\u{1F4DD} DRAFTS READY TO PUSH \u2014 ${l.length} total:
|
|
60
|
-
`);let y=([
|
|
60
|
+
`);let y=([v,D])=>{let O=D.priority?` [${D.priority.toUpperCase()}]`:"",R=P(D),k=R?.status||$.DRAFT,b={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[k]||"",E=R?.text||"";console.log(` ${b} ${v}${O}`),console.log(` "${E.slice(0,80)}${E.length>80?"...":""}"`)};d.length>0&&(console.log(` \u2500\u2500 Replies (they wrote last) \u2014 ${d.length}:`),d.forEach(y),console.log()),c.length>0&&(console.log(` \u2500\u2500 Re-engagement (we wrote last, following up) \u2014 ${c.length}:`),c.forEach(y),console.log()),g.length>0&&(console.log(` \u2500\u2500 Other \u2014 ${g.length}:`),g.forEach(y),console.log());let S=l.filter(([,v])=>P(v)?.status===$.CONFIRMED).length,C=l.filter(([,v])=>{let D=P(v)?.status;return D===$.DRAFT||D===$.NEEDS_REVIEW}).length;console.log(` ${S} confirmed, ${C} pending review`),C>0&&console.log(" Review: npm run messages -- --review-drafts"),S>0&&console.log(" Send: npm run messages -- --push-drafts"),console.log()}let a=new Date,f=t.filter(([,d])=>d.priority&&d.conversationStatus==="awaiting_reply").filter(([,d])=>d.followUpAfter?new Date(d.followUpAfter)<=a:!0).sort((d,c)=>{let g={high:0,medium:1,low:2}[d[1].priority]??3,y={high:0,medium:1,low:2}[c[1].priority]??3;return g-y});if(f.length>0){console.log(`
|
|
61
61
|
\u{1F514} FOLLOW-UP NEEDED \u2014 ${f.length} priority contacts waiting:
|
|
62
62
|
`);for(let[d,c]of f){let g=c.priority.toUpperCase(),y=c.lastSynced?Math.floor((a-new Date(c.lastSynced))/864e5):"?",S=c.lastMessagePreview?.slice(0,50)||"";console.log(` [${g}] ${d} \u2014 ${y}d ago`),c.notes&&console.log(` \u{1F4CC} ${c.notes}`),console.log(` ${S}`),console.log()}}if(n.length>0){console.log(`\u26A1 ACTION NEEDED \u2014 ${n.length} unanswered messages:
|
|
63
|
-
`);for(let[d,c]of n){let g=Be(c)?" [DRAFT READY]":"",y=c.priority?` [${c.priority.toUpperCase()}]`:c.suggestedPriority?` [${c.suggestedPriority}]`:"",S=c.category?` (${c.category})`:"",
|
|
64
|
-
All caught up \u2014 no unanswered messages.`);let u=
|
|
63
|
+
`);for(let[d,c]of n){let g=Be(c)?" [DRAFT READY]":"",y=c.priority?` [${c.priority.toUpperCase()}]`:c.suggestedPriority?` [${c.suggestedPriority}]`:"",S=c.category?` (${c.category})`:"",C=c.actionNeeded&&c.actionNeeded!=="none"?` \u2192 ${c.actionNeeded}`:"",v=c.lastMessageTime||"",D=(c.autoTags||[]).slice(0,4).join(", ");if(console.log(` ${d}${S}${y}${g}${C}`),c.summary)console.log(` ${c.summary}`);else{let O=c.lastMessagePreview?c.lastMessagePreview.slice(0,60)+(c.lastMessagePreview.length>60?"...":""):"";console.log(` ${v} | ${O}`)}D&&console.log(` #${D.replace(/, /g," #")}`),c.notes&&console.log(` \u{1F4CC} ${c.notes}`),c.profileUrl&&console.log(` ${c.profileUrl}`),console.log()}}else console.log(`
|
|
64
|
+
All caught up \u2014 no unanswered messages.`);let u=V(),p=new Set(Object.keys(e)),m=new Set(Object.values(e).map(d=>d.profileUrl).filter(Boolean)),h=Object.entries(u).filter(([d,c])=>c.connectionStatus==="connected"&&c.personActionNeeded==="initiate_contact"&&!m.has(d)&&!(c.name&&p.has(c.name))).sort((d,c)=>{let g={high:0,medium:1,low:2}[d[1].personPriority]??3,y={high:0,medium:1,low:2}[c[1].personPriority]??3;return g!==y?g-y:(c[1].connectionDate||"").localeCompare(d[1].connectionDate||"")});if(h.length>0){console.log(`
|
|
65
65
|
\u2709\uFE0F NEW CONNECTIONS TO MESSAGE \u2014 ${h.length} total:
|
|
66
66
|
`);let d=15;for(let[c,g]of h.slice(0,d)){let y=g.personPriority?`[${g.personPriority.toUpperCase()}]`:"",S=g.title?`${g.title}${g.company?` at ${g.company}`:""}`:g.company||"";console.log(` ${y} ${g.name||"Unknown"} \u2014 ${S}`),g.personSummary&&console.log(` ${g.personSummary}`),c&&console.log(` ${c}`),console.log()}h.length>d&&console.log(` ... and ${h.length-d} more. Run: npm run today
|
|
67
|
-
`)}console.log()}function
|
|
67
|
+
`)}console.log()}function Ct(e,t){return new Promise(s=>e.question(t,s))}async function rn(){let e=j(),t=V(),s={};for(let u of Object.values(t))u.name&&u.title&&(s[u.name]=u.title);let o={draft:0,needs_review:0,confirmed:1,rejected:2},n=Object.entries(e).filter(([,u])=>tn(u)).sort((u,p)=>{let m=o[P(u[1])?.status]??0,h=o[P(p[1])?.status]??0;if(m!==h)return m-h;let d={high:0,medium:1,low:2}[u[1].priority]??3,c={high:0,medium:1,low:2}[p[1].priority]??3;return d-c});if(n.length===0){console.log(`
|
|
68
68
|
No drafts to review.
|
|
69
|
-
`);return}let r=n.filter(([,u])=>{let p=
|
|
69
|
+
`);return}let r=n.filter(([,u])=>{let p=P(u)?.status;return p===$.DRAFT||p===$.NEEDS_REVIEW}),i=n.filter(([,u])=>P(u)?.status===$.CONFIRMED),l=n.filter(([,u])=>P(u)?.status===$.REJECTED);console.log(`
|
|
70
70
|
\u2550\u2550 Draft Review \u2550\u2550`),console.log(` Total: ${n.length} drafts (${r.length} pending, ${i.length} confirmed, ${l.length} rejected)
|
|
71
71
|
`),console.log(` Commands: [c]onfirm [r]eject [e]dit [s]kip [q]uit
|
|
72
|
-
`);let a=
|
|
73
|
-
${"\u2550".repeat(60)}`),console.log(` ${u+1}/${n.length} ${c} ${p} ${g} ${(m.priority||"").toUpperCase()}`),y&&console.log(` ${y}`),console.log(` Status: ${
|
|
74
|
-
`)),h.status
|
|
75
|
-
Saved. ${u} confirmed, ${m} pending, ${p} rejected.`),u>0&&console.log(" Ready to send: npm run messages -- --push-drafts")}console.log()}async function
|
|
76
|
-
Reached --max=${o}, stopping.`);break}if(S===0&&
|
|
77
|
-
${d} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!s&&S===0&&
|
|
78
|
-
${m} pages of already-synced conversations \u2014 caught up.`);break}}else S>0&&(p=0);await
|
|
72
|
+
`);let a=Dt.createInterface({input:process.stdin,output:process.stdout}),f=0;for(let u=0;u<n.length;u++){let[p,m]=n[u],h=P(m),d=h?.status||$.DRAFT,c={draft:"\u23F3",confirmed:"\u2705",rejected:"\u274C",needs_review:"\u{1F504}"}[d]||"?",g={high:"\u{1F534}",medium:"\u{1F7E1}",low:"\u26AA"}[m.priority]||"",y=s[p]||"",S=m.messages||[],C=m.conversationStatus||"?";if(console.log(`
|
|
73
|
+
${"\u2550".repeat(60)}`),console.log(` ${u+1}/${n.length} ${c} ${p} ${g} ${(m.priority||"").toUpperCase()}`),y&&console.log(` ${y}`),console.log(` Status: ${C} | ${S.length} msgs synced`),m.notes&&console.log(` Notes: ${m.notes}`),console.log(`${"\u2500".repeat(60)}`),S.length>0){console.log(" Conversation:");let k=S.slice(-4);S.length>4&&console.log(` ... (${S.length-4} earlier messages)`);for(let b of k){let E=b.sender||"Unknown",x=(b.text||"").replace(/\n/g," ").substring(0,120),M=qe(E)?" \u2192":" \u2190";console.log(` ${M} [${E}] ${x}`)}}else m.lastMessagePreview&&console.log(` Preview: "${m.lastMessagePreview}"`);console.log(`${"\u2500".repeat(60)}`),console.log(" Draft:");let v=Ue(m)||"",D=v.match(/.{1,80}/g)||[v];for(let k of D)console.log(` ${k}`);console.log(`${"\u2500".repeat(60)}`);let R=(await Ct(a," [c]onfirm [r]eject [e]dit [s]kip [q]uit > ")).trim().toLowerCase();if(R==="c"||R==="confirm"||R==="y"||R==="yes")h.status=$.CONFIRMED,f++,console.log(" \u2705 Confirmed");else if(R==="r"||R==="reject"||R==="n"||R==="no")h.status=$.REJECTED,f++,console.log(" \u274C Rejected");else if(R==="e"||R==="edit"){console.log(" Enter new draft text (end with empty line):");let k=[];for(;;){let b=await Ct(a," ");if(b.trim()==="")break;k.push(b)}k.length>0?(on(m,k.join(`
|
|
74
|
+
`)),h.status=$.CONFIRMED,f++,console.log(" \u2705 Edited & Confirmed")):console.log(" (no changes)")}else if(R==="q"||R==="quit"){console.log(" Quitting review...");break}else console.log(" \u23ED Skipped")}if(a.close(),f>0){L(e);let u=Object.values(e).filter(h=>P(h)?.status===$.CONFIRMED).length,p=Object.values(e).filter(h=>P(h)?.status===$.REJECTED).length,m=Object.values(e).filter(h=>{let d=P(h)?.status;return d===$.DRAFT||d===$.NEEDS_REVIEW}).length;console.log(`
|
|
75
|
+
Saved. ${u} confirmed, ${m} pending, ${p} rejected.`),u>0&&console.log(" Ready to send: npm run messages -- --push-drafts")}console.log()}async function xt(e){try{await dt(e)}catch{}}async function ln(e,t){let{full:s,max:o,verbose:n,dryRun:r}=t,i=s?"full":"incremental",l=j(),a=new Set(Object.keys(l)),f=new Map,u=0,p=0,m=3,h=0,d=3;for(;;){u++;let y=await ut(e),S=0,C=0;for(let v of y)v.name&&(f.has(v.name)||(f.set(v.name,v),a.has(v.name)?C++:S++));if(n?console.log(` Round #${u}: ${S} new, ${C} known | Total: ${f.size}`):process.stdout.write(`\r Conversations found: ${f.size} (page #${u})`),f.size>=o){console.log(`
|
|
76
|
+
Reached --max=${o}, stopping.`);break}if(S===0&&C===0){if(h++,h>=d){console.log(`
|
|
77
|
+
${d} rounds with no new items \u2014 end of list.`);break}}else h=0;if(!s&&S===0&&C>0){if(p++,p>=m){console.log(`
|
|
78
|
+
${m} pages of already-synced conversations \u2014 caught up.`);break}}else S>0&&(p=0);await ft(e),await A(2e3)}n||process.stdout.write(`
|
|
79
79
|
`);let c=Array.from(f.values());console.log(`
|
|
80
|
-
Extracted ${c.length} conversations.`);let g=
|
|
80
|
+
Extracted ${c.length} conversations.`);let g=pn(c,r);mn(c,g,r,i)}async function an(e,t,s){let o=V(),n=j(),r;if(t.startsWith("http")){let f=o[t],u=Object.entries(n).find(([,p])=>p.profileUrl===t);r=f?.name||u?.[0]}else r=t;if(!r){console.error(` Cannot find name for "${t}". Run inbox scan first.`);return}console.log(`
|
|
81
81
|
Reading conversation with: ${r}
|
|
82
|
-
`),await Te(e);let{verified:i}=await he(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await
|
|
83
|
-
`);for(let f of l){let u=f.time?` (${f.time})`:"";console.log(` [${f.sender}]${u}`),console.log(` ${f.text}`),console.log()}}let a=r;n[a]||(n[a]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),n[a].messages=ce(n[a].messages,l),n[a].lastSynced=new Date().toISOString(),P(n),console.log(` Saved ${n[a].messages.length} messages to conversations.json ["${a}"]`)}function Je(e){let t=H(),s=e,o=null;if(e.startsWith("http")){let n=t[e];if(n?.name)s=n.name,o=e;else return null}else{let n=Object.entries(t).find(([,i])=>i.name===e);n&&(o=n[0]);let r=j();!o&&r[e]?.profileUrl&&(o=r[e].profileUrl)}return{personName:s,profileUrl:o}}async function We(e,t,s,o,n={}){try{let{verified:r}=await he(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await Z(e,{scrollUp:!1}),a=j()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages visible (saved: ${a})`),i.length>a&&a>0){let $=i.length-a,A=i[i.length-1];return console.error(` \u2717 ABORT: ${$} new message(s) since last sync!`),console.error(` Latest: [${A.sender}] ${A.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let $=i[i.length-1],A=null;for(let C=i.length-1;C>=0;C--)if(i[C].sender!=="Unknown"&&i[C].sender!==""){A=i[C].sender;break}if(A===se)if(n.allowDoubleMessage)console.log(" \u26A0 Last message is from us \u2014 but allowDoubleMessage is set (re-engagement).");else return console.error(" \u2717 ABORT: Last message is already from us!"),console.error(` "${$.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let f=o.slice(0,50).toLowerCase();if(i.some($=>$.text.toLowerCase().startsWith(f)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!n.allowDoubleMessage){let $=new Date().toISOString().slice(0,10);if(i.some(C=>{if(!qe(C.sender))return!1;let F=C.time||"";return F.startsWith($)||F.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}console.log(" \u2713 Safety checks passed");let 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 x(300);let m=o.replace(/\\([!?#$])/g,"$1");m!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=m),await e.keyboard.type(o,{delay:20}),await x(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),d=$=>$.replace(/\s+/g," ").trim(),c=d(o),g=d(h);if(g!==c){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${c.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let $=0;$<Math.max(c.length,g.length);$++)if(c[$]!==g[$]){console.error(` First diff at position ${$}: expected '${c[$]||"EOF"}' got '${g[$]||"EOF"}'`),console.error(` Context: ...${c.slice(Math.max(0,$-10),$+10)}...`);break}return await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1}console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found."),!1;await y.click(),await x(2e3),console.log(" \u2713 Message sent!"),console.log(" Syncing conversation thread..."),await x(1e3);let S=await Z(e);console.log(` Synced ${S.length} messages from thread.`);let v=j(),E=new Date().toISOString(),D=t;v[D]?(v[D].lastMessageBy="me",v[D].lastMessagePreview=o.slice(0,100),v[D].lastMessageTime=E,v[D].conversationStatus="awaiting_reply",v[D].lastSynced=E,v[D].messages=ce(v[D].messages,S)):v[D]={profileUrl:s,lastSynced:E,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:S},s&&(v[D].profileUrl=s),P(v);let _=H(),b=s?_[s]:null;return b&&(b.conversationStatus="awaiting_reply",b.lastMessageSent=E,b.lastUpdated=E,ge(_)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function Ct(e,t,s){if(t?.profileUrl)return t.profileUrl;let o=Object.entries(s).find(([,n])=>n.name===e);return o?o[0]:null}async function ln(e,t,s,o){try{console.log(` \u2192 Profile fallback: navigating to ${s}`),await e.goto(s,{waitUntil:"domcontentloaded",timeout:3e4}),await x(3e3);let n=await e.evaluate(()=>{let b=0,$=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let C of $){if(C.offsetHeight===0)continue;let R=C.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(R||(R=C.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!R){let F=C.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");F.length>0&&(R=F[F.length-1])}R&&R.offsetHeight>0&&(R.click(),b++)}let A=document.querySelector(".msg-overlay-list-bubble");if(A&&!A.classList.contains("msg-overlay-list-bubble--is-minimized")){let C=A.querySelector(".msg-overlay-bubble-header__button");C&&C.offsetHeight>0&&(C.click(),b++)}return b});n>0&&(console.log(` Closed ${n} existing overlay(s)`),await x(1500));let r=await e.evaluate(()=>{let b=document.querySelectorAll(".msg-overlay-conversation-bubble"),$=Array.from(b).filter(R=>R.offsetHeight>0),A=document.querySelector(".msg-overlay-list-bubble"),C=A?A.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:$.length,trayMinimized:C,bubbleNames:$.map(R=>R.querySelector('a[href*="/in/"]')?.textContent?.trim()?.slice(0,30)||"?")}});r.visibleBubbles>0&&console.log(` \u26A0 Still ${r.visibleBubbles} overlay(s) open: [${r.bubbleNames.join(", ")}], tray minimized: ${r.trayMinimized}`);let i=await e.evaluate(()=>{let b=document.querySelectorAll('a[href*="recipient="]');for(let $ of b)try{let C=new URL($.getAttribute("href"),location.origin).searchParams.get("recipient");if(C)return C}catch{}return null});if(!i)return console.error(" \u2717 Could not extract recipient URN from profile (no <a> with recipient=)"),!1;console.log(` \u2713 Extracted recipient URN: ${i.slice(0,24)}\u2026`);let l=`https://www.linkedin.com/messaging/thread/new/?recipient=${encodeURIComponent(i)}&screenContext=NON_SELF_PROFILE_VIEW`;await e.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await x(3e3);let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;try{await e.waitForSelector('div.msg-form__contenteditable, div[contenteditable="true"][role="textbox"]',{timeout:1e4})}catch{return console.error(' \u2717 Message composer never appeared on compose page (neither msg-form__contenteditable nor [contenteditable="true"][role="textbox"])'),!1}console.log(" \u2713 Compose page loaded, message form ready");let f=t.split(" ")[0].toLowerCase(),u=t.toLowerCase().split(/[\s,]+/).filter(b=>b.length>1),p=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(p){let b=p.toLowerCase();if(!(b.includes(f)||u.some(A=>b.includes(A))))return console.error(` \u2717 Recipient mismatch: compose shows "${p}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${p}"`)}else console.log(" \u26A0 Could not read recipient pill \u2014 proceeding with URN-trust");let m=await Z(e,{scrollUp:!1});if(m.length>0){let b=o.slice(0,50).toLowerCase();if(m.some(R=>R.text.toLowerCase().startsWith(b)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let A=new Date().toISOString().slice(0,10);if(m.some(R=>{if(!qe(R.sender))return!1;let fe=R.time||"";return fe.startsWith(A)||fe.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let h=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!h)return console.error(" Message input not found in overlay."),!1;await h.click(),await x(300);let d=o.replace(/\\([!?#$])/g,"$1");d!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=d),await e.keyboard.type(o,{delay:20}),await x(500);let c=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),g=b=>b.replace(/\s+/g," ").trim();if(g(c)!==g(o))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${g(o).slice(0,100)}..."`),console.error(` Actual: "${g(c).slice(0,100)}..."`),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1;console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found in overlay."),!1;await y.click(),await x(2e3),console.log(" \u2713 Message sent via profile!"),console.log(" Syncing conversation thread..."),await x(1e3);let S=await Z(e);console.log(` Synced ${S.length} messages from thread.`);let v=j(),E=new Date().toISOString();v[t]?(v[t].lastMessageBy="me",v[t].lastMessagePreview=o.slice(0,100),v[t].lastMessageTime=E,v[t].conversationStatus="awaiting_reply",v[t].lastSynced=E,v[t].messages=ce(v[t].messages,S)):v[t]={profileUrl:s,lastSynced:E,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:S},s&&(v[t].profileUrl=s),P(v);let D=H(),_=D[s];return _&&(_.conversationStatus="awaiting_reply",_.lastMessageSent=E,_.lastUpdated=E,ge(D)),!0}catch(n){return console.error(" \u2717 Profile send error:",n.message),!1}}async function an(e,t,s,o){if(!t||!s)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let n=Je(t);if(!n)return console.error(` Person not found: ${t}`),!1;let r=Se(n.personName,s);return r.ok?(console.log(`
|
|
84
|
-
Sending message to: ${n.personName}`),console.log(` Text: "${s.slice(0,150)}${s.length>150?"...":""}"`),o
|
|
85
|
-
[DRY RUN \u2014 message not sent]`),!1)
|
|
82
|
+
`),await Te(e);let{verified:i}=await he(e,r);if(!i){console.error(` \u2717 Could not open correct thread for "${r}". Aborting to avoid saving wrong data.`);return}let l=await ee(e);if(l.length===0){if(console.log(" No messages extracted (DOM may have changed)."),s){let f=await e.evaluate(()=>({events:document.querySelectorAll("li.msg-s-message-list__event").length,bubbles:document.querySelectorAll(".msg-s-event-listitem").length,any:document.querySelectorAll('[class*="msg-s-event"]').length}));console.log(" [DEBUG] Counts:",f)}}else{console.log(` ${l.length} messages:
|
|
83
|
+
`);for(let f of l){let u=f.time?` (${f.time})`:"";console.log(` [${f.sender}]${u}`),console.log(` ${f.text}`),console.log()}}let a=r;n[a]||(n[a]={profileUrl:t.startsWith("http")?t:null,lastSynced:new Date().toISOString(),lastMessageBy:null,lastMessagePreview:"",lastMessageTime:"",unread:!1,conversationStatus:null,messages:[]}),n[a].messages=ue(n[a].messages,l),n[a].lastSynced=new Date().toISOString(),L(n),console.log(` Saved ${n[a].messages.length} messages to conversations.json ["${a}"]`)}function Je(e){let t=V(),s=e,o=null;if(e.startsWith("http")){let n=t[e];if(n?.name)s=n.name,o=e;else return null}else{let n=Object.entries(t).find(([,i])=>i.name===e);n&&(o=n[0]);let r=j();!o&&r[e]?.profileUrl&&(o=r[e].profileUrl)}return{personName:s,profileUrl:o}}async function We(e,t,s,o,n={}){try{let{verified:r}=await he(e,t);if(!r)return console.error(` \u2717 Could not open correct thread for "${t}". Skipping.`),!1;let i=await ee(e,{scrollUp:!1}),a=j()[t]?.messages?.length||0;if(console.log(` Pre-send check: ${i.length} messages visible (saved: ${a})`),i.length>a&&a>0){let b=i.length-a,E=i[i.length-1];return console.error(` \u2717 ABORT: ${b} new message(s) since last sync!`),console.error(` Latest: [${E.sender}] ${E.text.slice(0,100)}`),console.error(" Re-run readHotThreads to sync first."),!1}if(i.length>0){let b=i[i.length-1],E=null;for(let x=i.length-1;x>=0;x--)if(i[x].sender!=="Unknown"&&i[x].sender!==""){E=i[x].sender;break}if(E===re)if(n.allowDoubleMessage)console.log(" \u26A0 Last message is from us \u2014 but allowDoubleMessage is set (re-engagement).");else return console.error(" \u2717 ABORT: Last message is already from us!"),console.error(` "${b.text.slice(0,100)}"`),console.error(" Not sending to avoid double-reply."),!1}let f=o.slice(0,50).toLowerCase();if(i.some(b=>b.text.toLowerCase().startsWith(f)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;if(!n.allowDoubleMessage){let b=new Date().toISOString().slice(0,10);if(i.some(x=>{if(!qe(x.sender))return!1;let M=x.time||"";return M.startsWith(b)||M.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}console.log(" \u2713 Safety checks passed");let p=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!p)return console.error(" Message input not found in conversation."),!1;await p.click(),await A(300);let m=o.replace(/\\([!?#$])/g,"$1");m!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=m),await e.keyboard.type(o,{delay:20}),await A(500);let h=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),d=b=>b.replace(/\s+/g," ").trim(),c=d(o),g=d(h);if(g!==c){console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${c.slice(0,100)}..."`),console.error(` Actual: "${g.slice(0,100)}..."`);for(let b=0;b<Math.max(c.length,g.length);b++)if(c[b]!==g[b]){console.error(` First diff at position ${b}: expected '${c[b]||"EOF"}' got '${g[b]||"EOF"}'`),console.error(` Context: ...${c.slice(Math.max(0,b-10),b+10)}...`);break}return await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1}console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found."),!1;await y.click(),await A(2500);let S=await e.evaluate(()=>{let E=((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(M=>(M.innerText||"").trim()).filter(Boolean).find(M=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(M))||null;return{inputText:E,error:_}});if(S.error)return console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${S.error.slice(0,140)}"`),!1;if(S.inputText&&d(S.inputText)===d(o))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 A(1e3);let C=await ee(e);console.log(` Synced ${C.length} messages from thread.`);let v=j(),D=new Date().toISOString(),O=t;v[O]?(v[O].lastMessageBy="me",v[O].lastMessagePreview=o.slice(0,100),v[O].lastMessageTime=D,v[O].conversationStatus="awaiting_reply",v[O].lastSynced=D,v[O].messages=ue(v[O].messages,C)):v[O]={profileUrl:s,lastSynced:D,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:C},s&&(v[O].profileUrl=s),L(v);let R=V(),k=s?R[s]:null;return k&&(k.conversationStatus="awaiting_reply",k.lastMessageSent=D,k.lastUpdated=D,ge(R)),!0}catch(r){return console.error(" Error sending message:",r.message),!1}}function At(e,t,s){if(t?.profileUrl)return t.profileUrl;let o=Object.entries(s).find(([,n])=>n.name===e);return o?o[0]:null}async function Tt(e,t,s,o){try{console.log(` \u2192 Profile fallback: navigating to ${s}`),await e.goto(s,{waitUntil:"domcontentloaded",timeout:3e4}),await A(3e3);let n=await e.evaluate(()=>{let k=0,b=document.querySelectorAll(".msg-overlay-conversation-bubble");for(let x of b){if(x.offsetHeight===0)continue;let _=x.querySelector('.msg-overlay-bubble-header__control--close-btn, button[data-control-name="overlay.close_conversation_window"]');if(_||(_=x.querySelector('button[aria-label*="Close"], button[aria-label*="close"]')),!_){let M=x.querySelectorAll(".msg-overlay-bubble-header__controls button, .msg-overlay-bubble-header button");M.length>0&&(_=M[M.length-1])}_&&_.offsetHeight>0&&(_.click(),k++)}let E=document.querySelector(".msg-overlay-list-bubble");if(E&&!E.classList.contains("msg-overlay-list-bubble--is-minimized")){let x=E.querySelector(".msg-overlay-bubble-header__button");x&&x.offsetHeight>0&&(x.click(),k++)}return k});n>0&&(console.log(` Closed ${n} existing overlay(s)`),await A(1500));let r=await e.evaluate(()=>{let k=document.querySelectorAll(".msg-overlay-conversation-bubble"),b=Array.from(k).filter(_=>_.offsetHeight>0),E=document.querySelector(".msg-overlay-list-bubble"),x=E?E.classList.contains("msg-overlay-list-bubble--is-minimized"):null;return{visibleBubbles:b.length,trayMinimized:x,bubbleNames:b.map(_=>_.querySelector('a[href*="/in/"]')?.textContent?.trim()?.slice(0,30)||"?")}});r.visibleBubbles>0&&console.log(` \u26A0 Still ${r.visibleBubbles} overlay(s) open: [${r.bubbleNames.join(", ")}], tray minimized: ${r.trayMinimized}`);let i=null;for(let k=0;k<8&&!i;k++)i=await e.evaluate(()=>{let b=document.querySelectorAll('a[href*="recipient="]');for(let E of b)try{let x=new URL(E.getAttribute("href"),location.origin).searchParams.get("recipient");if(x)return x}catch{}return null}),i||(k===0&&console.log(" \u2026waiting for the profile Message link to render"),await A(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 A(3e3);let a=e.url();if(a.includes("/premium/")||a.includes("/redeem"))return console.error(` \u2717 /messaging/thread/new/ redirected to Premium \u2014 likely ${t} is InMail-only`),!1;try{await e.waitForSelector('div.msg-form__contenteditable, div[contenteditable="true"][role="textbox"]',{timeout:1e4})}catch{return console.error(' \u2717 Message composer never appeared on compose page (neither msg-form__contenteditable nor [contenteditable="true"][role="textbox"])'),!1}console.log(" \u2713 Compose page loaded, message form ready");let f=t.split(" ")[0].toLowerCase(),u=t.toLowerCase().split(/[\s,]+/).filter(k=>k.length>1),p=await e.evaluate(()=>document.querySelector(".msg-connections-typeahead__added-recipients")?.textContent?.trim()?.replace(/\s+/g," ")||"");if(p){let k=p.toLowerCase();if(!(k.includes(f)||u.some(E=>k.includes(E))))return console.error(` \u2717 Recipient mismatch: compose shows "${p}", expected "${t}"`),!1;console.log(` \u2713 Recipient verified: "${p}"`)}else return console.error(" \u2717 Could not confirm the recipient (compose pill unreadable) \u2014 not sending on the direct path."),!1;let m=await ee(e,{scrollUp:!1});if(m.length>0){let k=o.slice(0,50).toLowerCase();if(m.some(_=>_.text.toLowerCase().startsWith(k)))return console.error(" \u2717 ABORT: This message appears to already be in the thread!"),!1;let E=new Date().toISOString().slice(0,10);if(m.some(_=>{if(!qe(_.sender))return!1;let He=_.time||"";return He.startsWith(E)||He.toLowerCase().includes("today")}))return console.error(" \u2717 ABORT: We already sent a message today in this thread!"),!1}let h=await e.$("div.msg-form__contenteditable")||await e.$('div[contenteditable="true"][role="textbox"]');if(!h)return console.error(" Message input not found in overlay."),!1;await h.click(),await A(300);let d=o.replace(/\\([!?#$])/g,"$1");d!==o&&(console.log(" Cleaned bash escape artifacts from message text"),o=d),await e.keyboard.type(o,{delay:20}),await A(500);let c=await e.evaluate(()=>(document.querySelector("div.msg-form__contenteditable")||document.querySelector('div[contenteditable="true"][role="textbox"]'))?.innerText?.trim()||""),g=k=>k.replace(/\s+/g," ").trim();if(g(c)!==g(o))return console.error(" \u2717 ABORT: Typed text does not match intended message!"),console.error(` Intended: "${g(o).slice(0,100)}..."`),console.error(` Actual: "${g(c).slice(0,100)}..."`),await e.keyboard.down("Control"),await e.keyboard.press("a"),await e.keyboard.up("Control"),await e.keyboard.press("Backspace"),!1;console.log(" \u2713 Text verified \u2014 matches intended message");let y=await e.$("button.msg-form__send-button")||await e.$('button[type="submit"]');if(!y)return console.error(" Send button not found in overlay."),!1;await y.click(),await A(2500);let S=await e.evaluate(()=>{let b=((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(_=>(_.innerText||"").trim()).filter(Boolean).find(_=>/try again|there was an error|went wrong|couldn|failed|not sent/i.test(_))||null;return{inputText:b,error:x}});if(S.error)return console.error(` \u2717 NOT sent \u2014 LinkedIn returned an error: "${S.error.slice(0,140)}"`),!1;if(S.inputText&&g(S.inputText)===g(o))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 A(1e3);let C=await ee(e);console.log(` Synced ${C.length} messages from thread.`);let v=j(),D=new Date().toISOString();v[t]?(v[t].lastMessageBy="me",v[t].lastMessagePreview=o.slice(0,100),v[t].lastMessageTime=D,v[t].conversationStatus="awaiting_reply",v[t].lastSynced=D,v[t].messages=ue(v[t].messages,C)):v[t]={profileUrl:s,lastSynced:D,lastMessageBy:"me",lastMessagePreview:o.slice(0,100),lastMessageTime:new Date().toISOString(),unread:!1,conversationStatus:"awaiting_reply",situation:"we_initiated_waiting",messages:C},s&&(v[t].profileUrl=s),L(v);let O=V(),R=O[s];return R&&(R.conversationStatus="awaiting_reply",R.lastMessageSent=D,R.lastUpdated=D,ge(O)),!0}catch(n){return console.error(" \u2717 Profile send error:",n.message),!1}}async function cn(e,t,s,o){if(!t||!s)return console.error(' Usage: npm run messages -- --send "Person Name" "message text"'),!1;let n=Je(t);if(!n)return console.error(` Person not found: ${t}`),!1;let r=Se(n.personName,s);if(!r.ok)return ve(n.personName,r),!1;if(console.log(`
|
|
84
|
+
Sending message to: ${n.personName}`),console.log(` Text: "${s.slice(0,150)}${s.length>150?"...":""}"`),o)return console.log(`
|
|
85
|
+
[DRY RUN \u2014 message not sent]`),!1;if(n.profileUrl){if(await Tt(e,n.personName,n.profileUrl,s))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 A(4e3),We(e,n.personName,n.profileUrl,s)}async function un(e,t,s){if(console.log(`
|
|
86
86
|
\u2550\u2550 Batch send: ${t.length} messages \u2550\u2550
|
|
87
|
-
`),s){for(let{name:i,message:l}of t)console.log(` [DRY RUN] ${i}: "${l.slice(0,80)}..."`);return}await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await
|
|
88
|
-
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`);let f=Je(l);if(!f){console.error(` \u2717 Cannot resolve: ${l}`),o.push({name:l,status:"not_found"});continue}if(!t[i].skipSalutationCheck){let p=Se(f.personName,a);if(!p.ok){ve(f.personName,p),o.push({name:l,status:"aborted_salutation"});continue}}console.log(` Text: "${a.slice(0,100)}${a.length>100?"...":""}"`);let u=await We(e,f.personName,f.profileUrl,a);o.push({name:l,status:u?"sent":"failed"}),await
|
|
87
|
+
`),s){for(let{name:i,message:l}of t)console.log(` [DRY RUN] ${i}: "${l.slice(0,80)}..."`);return}await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let o=[];for(let i=0;i<t.length;i++){let{name:l,message:a}=t[i];console.log(`
|
|
88
|
+
\u2500\u2500 [${i+1}/${t.length}] ${l} \u2500\u2500`);let f=Je(l);if(!f){console.error(` \u2717 Cannot resolve: ${l}`),o.push({name:l,status:"not_found"});continue}if(!t[i].skipSalutationCheck){let p=Se(f.personName,a);if(!p.ok){ve(f.personName,p),o.push({name:l,status:"aborted_salutation"});continue}}console.log(` Text: "${a.slice(0,100)}${a.length>100?"...":""}"`);let u=await We(e,f.personName,f.profileUrl,a);o.push({name:l,status:u?"sent":"failed"}),await xt(e)}console.log(`
|
|
89
89
|
\u2550\u2550 Batch results \u2550\u2550
|
|
90
|
-
`);let n=o.filter(i=>i.status
|
|
91
|
-
Total: ${n.length} sent, ${r.length} failed/skipped`)}async function
|
|
90
|
+
`);let n=o.filter(i=>i.status===$.SENT),r=o.filter(i=>i.status!==$.SENT);for(let i of o){let l=i.status===$.SENT?"\u2713":"\u2717";console.log(` ${l} ${i.name} \u2014 ${i.status}`)}console.log(`
|
|
91
|
+
Total: ${n.length} sent, ${r.length} failed/skipped`)}async function fn(e,t){let s=j(),o=V(),n=Object.entries(s).filter(([,d])=>Be(d)),r=n.filter(([,d])=>Le(d)?.status===$.CONFIRMED),i=n.filter(([,d])=>{let c=Le(d)?.status;return c===$.DRAFT||c===$.NEEDS_REVIEW}).length;if(n.length===0){console.log(`
|
|
92
92
|
No drafts to push. Prepare drafts in conversations.json first.
|
|
93
93
|
`);return}if(r.length===0){console.log(`
|
|
94
94
|
No confirmed drafts to push (${i} pending, need review).`),console.log(` Run: npm run messages -- --review-drafts
|
|
95
95
|
`);return}if(console.log(`
|
|
96
|
-
\u2550\u2550 Pushing ${r.length} confirmed draft(s) \u2550\u2550`),i>0&&console.log(` (${i} more pending \u2014 run --review-drafts to confirm)`),console.log(),t){for(let[d,c]of r){let g=
|
|
97
|
-
`),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await
|
|
98
|
-
\u2500\u2500 [${d+1}/${r.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let S=Je(c),
|
|
96
|
+
\u2550\u2550 Pushing ${r.length} confirmed draft(s) \u2550\u2550`),i>0&&console.log(` (${i} more pending \u2014 run --review-drafts to confirm)`),console.log(),t){for(let[d,c]of r){let g=At(d,c,o),y=c.messages?.some(C=>!ce.has(C.status)&&C.status!==$.REJECTED)?"inbox":g?"profile":"no profileUrl";console.log(` [DRY RUN] ${d} (${y}):`);let S=Ue(c)||"";console.log(` "${S.slice(0,100)}${S.length>100?"...":""}"`),console.log()}return}console.log(`\u2500\u2500 Pass 1: Inbox search \u2500\u2500
|
|
97
|
+
`),await e.goto("https://www.linkedin.com/messaging/",{waitUntil:"domcontentloaded",timeout:6e4}),await A(4e3);let l=[],a=[];for(let d=0;d<r.length;d++){let[c,g]=r[d],y=Ue(g);console.log(`
|
|
98
|
+
\u2500\u2500 [${d+1}/${r.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let S=Je(c),C=S?.personName||c,v=S?.profileUrl||g.profileUrl||null;if(!g.skipSalutationCheck){let b=Se(c,y);if(!b.ok){ve(c,b),l.push({name:c,status:"aborted_salutation"});continue}}let O=(g.messages||[]).filter(b=>!X.has(b.status)).length,R=!1,k=!1;try{await Ve(e);let{verified:b}=await he(e,C);if(b){k=!0;let E=await ee(e);if(E.length>O&&O>0){let x=E.length-O;R=!0,g.messages=ue(g.messages,E),console.log(` \u26A0 ${x} new message(s) since draft was created!`);let _=E[E.length-1];console.log(` Latest: [${_.sender}] ${_.text.slice(0,80)}`)}}else console.log(" Not found or wrong thread in inbox search")}catch(b){console.log(` Pre-send sync error: ${b.message}`)}if(R){for(let b of g.messages||[])b.status===$.CONFIRMED&&(b.status=$.NEEDS_REVIEW);l.push({name:c,status:$.NEEDS_REVIEW}),console.log(" \u2192 Skipped \u2014 draft needs review (new messages from them)")}else if(k)if(await We(e,C,v,y,{allowDoubleMessage:!0})){for(let E of g.messages||[])E.status===$.CONFIRMED&&E.text===y&&(E.status=$.SENT,E.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",L(s),l.push({name:c,status:"sent",method:"inbox"})}else l.push({name:c,status:"failed",method:"inbox"});else a.push({name:c,conv:g,message:y,personName:C}),console.log(" \u2192 Queued for profile fallback");R&&L(s),await xt(e)}if(a.length>0){console.log(`
|
|
99
99
|
\u2500\u2500 Pass 2: Profile fallback (${a.length} remaining) \u2500\u2500
|
|
100
100
|
`);for(let d=0;d<a.length;d++){let{name:c,conv:g,message:y,personName:S}=a[d];console.log(`
|
|
101
|
-
\u2500\u2500 [profile ${d+1}/${a.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let
|
|
101
|
+
\u2500\u2500 [profile ${d+1}/${a.length}] ${c} \u2500\u2500`),console.log(` Draft: "${y.slice(0,100)}${y.length>100?"...":""}"`);let C=At(c,g,o);if(!C){console.error(" \u2717 No profileUrl found \u2014 cannot send via profile"),l.push({name:c,status:"failed",method:"no_url"});continue}if(await Tt(e,S,C,y)){for(let D of g.messages||[])D.status===$.CONFIRMED&&D.text===y&&(D.status=$.SENT,D.sentAt=new Date().toISOString());g.reviewedAtPreview=g.lastMessagePreview||"",L(s),l.push({name:c,status:"sent",method:"profile"})}else l.push({name:c,status:"failed",method:"profile"})}}console.log(`
|
|
102
102
|
\u2550\u2550 Push results \u2550\u2550
|
|
103
|
-
`);let f=l.filter(d=>d.status
|
|
104
|
-
Total: ${f.length} sent (${m} inbox, ${h} profile), ${u.length} need review, ${p.length} failed`)}function
|
|
103
|
+
`);let f=l.filter(d=>d.status===$.SENT),u=l.filter(d=>d.status===$.NEEDS_REVIEW),p=l.filter(d=>d.status==="failed");for(let d of l){let c={sent:"\u2713",needs_review:"\u26A0",failed:"\u2717"}[d.status]||"?",g=d.method?` (${d.method})`:"";console.log(` ${c} ${d.name} \u2014 ${d.status}${g}`)}let m=f.filter(d=>d.method==="inbox").length,h=f.filter(d=>d.method==="profile").length;console.log(`
|
|
104
|
+
Total: ${f.length} sent (${m} inbox, ${h} profile), ${u.length} need review, ${p.length} failed`)}function dn(e){let t={};for(let[s,o]of Object.entries(e)){let n=o.name;n&&(t[n]?o.connectionStatus==="connected"&&t[n].connectionStatus!=="connected"&&(t[n]={url:s,...o}):t[n]={url:s,...o})}return t}function pn(e,t){let s=j(),o=V(),n=dn(o),r=new Date().toISOString(),i={newConversations:0,updatedConversations:0,unansweredByUs:0,awaitingReply:0,peopleLinked:0,newPeople:0};for(let l of e){if(!l.name)continue;let a;l.lastMessageBy==="them"?(a="unanswered_by_us",i.unansweredByUs++):l.lastMessageBy==="me"?(a="awaiting_reply",i.awaitingReply++):a="mutual_silence";let u=n[l.name]?.url||null,p=s[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=a),u&&!p.profileUrl&&(p.profileUrl=u),i.updatedConversations++):(s[l.name]={profileUrl:u,lastSynced:r,lastMessageBy:l.lastMessageBy,lastMessagePreview:l.lastMessagePreview||"",lastMessageTime:l.lastMessageTime||"",unread:l.unread||!1,conversationStatus:a,messages:[]},i.newConversations++),u){let m=o[u];m.conversationStatus=a,l.lastMessageBy==="them"&&(m.lastMessageReceived=m.lastMessageReceived||r),l.lastMessageBy==="me"&&(m.lastMessageSent=m.lastMessageSent||r),m.lastUpdated=r,i.peopleLinked++}}return t||(L(s),ge(o)),i}function mn(e,t,s,o){let n=j(),r=Object.entries(n),i=r.filter(([,l])=>l.conversationStatus==="unanswered_by_us").sort((l,a)=>{let f=l[1].lastSynced||"";return(a[1].lastSynced||"").localeCompare(f)});if(console.log(`
|
|
105
105
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(` Message Bot Summary (${o})`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` Conversations scanned: ${e.length}`),console.log(` New conversations: ${t.newConversations}`),console.log(` Updated conversations: ${t.updatedConversations}`),console.log(` Linked to people.json: ${t.peopleLinked}`),t.newPeople>0&&console.log(` New people (non-contact): ${t.newPeople}`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` This scan \u2014 unanswered: ${t.unansweredByUs}`),console.log(` This scan \u2014 awaiting: ${t.awaitingReply}`),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),console.log(` Total in DB: ${r.length} conversations`),console.log(` Total unanswered: ${i.length}`),i.length>0){let a=i.slice(0,15);console.log(`
|
|
106
106
|
\u26A1 ACTION NEEDED \u2014 ${i.length} unanswered messages:
|
|
107
107
|
`);for(let[f,u]of a){let p=f.padEnd(30),m=(u.lastMessageTime||"").padEnd(10),h=u.lastMessagePreview?u.lastMessagePreview.slice(0,55)+(u.lastMessagePreview.length>55?"...":""):"";console.log(` ${p} ${m} ${h}`)}i.length>15&&console.log(`
|
|
108
108
|
... and ${i.length-15} more. Use --list for full list.`)}else console.log(`
|
|
109
109
|
All caught up \u2014 no unanswered messages.`);s&&console.log(`
|
|
110
110
|
[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
|
|
111
|
-
`)}async function
|
|
111
|
+
`)}async function gn(){let e=nn();if(e.list){sn();return}if(e.reviewDrafts){await rn();return}if(e.followUp||e.followUpBatch||e.clearFollowUp){let r=j(),i=0;if(e.clearFollowUp){let l=r[e.clearFollowUp];l?(delete l.followUpNote,delete l.followUpDate,i++,console.log(` \u2713 ${e.clearFollowUp} \u2014 follow-up cleared`)):console.log(` ? ${e.clearFollowUp} \u2014 not found`)}else{let l=e.followUpBatch||[e.followUp];for(let a of l){let f=a.target||a.name,u=a.note||a.text||"",p=a.date||null,m=r[f];m?(m.followUpNote=u,p&&(m.followUpDate=p),i++,console.log(` + ${f} \u2014 follow-up set${p?` for ${p}`:""}: ${u.slice(0,60)}`)):(r[f]={profileUrl:null,lastSynced:new Date().toISOString(),followUpNote:u,followUpDate:p||null,messages:[]},i++,console.log(` + ${f} \u2014 new entry with follow-up${p?` for ${p}`:""}`))}}i>0&&(L(r),console.log(`
|
|
112
112
|
${i} follow-up(s) updated.
|
|
113
|
-
`));return}if(e.review||e.reviewBatch){let r=e.reviewBatch||[e.review],i=j(),l=0;for(let a of r){let f=i[a];f?(f.reviewedAtPreview=f.lastMessagePreview||"",l++,console.log(` + ${a} \u2014 marked as reviewed`)):console.log(` ? ${a} \u2014 not found in conversations`)}l>0?(
|
|
113
|
+
`));return}if(e.review||e.reviewBatch){let r=e.reviewBatch||[e.review],i=j(),l=0;for(let a of r){let f=i[a];f?(f.reviewedAtPreview=f.lastMessagePreview||"",l++,console.log(` + ${a} \u2014 marked as reviewed`)):console.log(` ? ${a} \u2014 not found in conversations`)}l>0?(L(i),console.log(`
|
|
114
114
|
${l} conversation(s) marked as reviewed.
|
|
115
115
|
`)):console.log(`
|
|
116
116
|
No conversations updated.
|
|
117
|
-
`);return}if(e.draft||e.draftBatch){let r=e.draftBatch?e.draftBatch:[{name:e.draft.target,text:e.draft.text}];r.length===0&&(console.error("No drafts to add."),process.exit(1));let i=j(),l=
|
|
117
|
+
`);return}if(e.draft||e.draftBatch){let r=e.draftBatch?e.draftBatch:[{name:e.draft.target,text:e.draft.text}];r.length===0&&(console.error("No drafts to add."),process.exit(1));let i=j(),l=V(),a=0;for(let{name:f,text:u,profileUrl:p,skipSalutationCheck:m}of r){if(!f||!u){console.error(` Skipping invalid draft: name=${f}`);continue}let h=e.draft?u.replace(/\\([!?#$])/g,"$1"):u;if(!m){let g=Se(f,h);if(!g.ok){ve(f,g);continue}}if(!i[f]){let g=p||null;if(!g){let y=Object.entries(l).filter(([,S])=>S.name===f);y.length===1?g=y[0][0]:y.length>1&&console.warn(` \u26A0 Multiple people named "${f}" \u2014 pass profileUrl in draft JSON to disambiguate`)}i[f]={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[f];d.messages||(d.messages=[]),d.messages.push({sender:re,text:h,time:new Date().toISOString(),status:$.CONFIRMED,draftedAt:new Date().toISOString()}),d.reviewedAtPreview=d.lastMessagePreview||"";let c=d.messages.filter(g=>!ce.has(g.status)&&g.status!==$.REJECTED);console.log(` Draft added for ${f}`),console.log(` Thread: ${c.length} messages + 1 draft`),console.log(` "${h.slice(0,100)}${h.length>100?"...":""}"`),console.log(),a++}L(i),console.log(` ${a} draft(s) saved. Send all: npm run messages -- --push-drafts
|
|
118
118
|
`);return}console.log(`
|
|
119
119
|
\u{1F4E8} LinkedIn Message Bot
|
|
120
|
-
`),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let t=e.read?"read":e.pushDrafts?"push-drafts":e.sendBatch?"send-batch":e.send?"send":e.full?"full":"incremental",s=
|
|
121
|
-
`),await Te(n),await
|
|
122
|
-
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),De(s,"error",null,r.message)}finally{await o.close()}}
|
|
120
|
+
`),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let t=e.read?"read":e.pushDrafts?"push-drafts":e.sendBatch?"send-batch":e.send?"send":e.full?"full":"incremental",s=nt("messages",t),{browser:o,page:n}=await ct();try{if(e.read)await an(n,e.read,e.verbose);else if(e.pushDrafts)await fn(n,e.dryRun);else if(e.sendBatch)await un(n,e.sendBatch,e.dryRun);else if(e.send)await cn(n,e.send.target,e.send.text,e.dryRun);else{let r=e.full?"full":"incremental";console.log(`Mode: ${r} inbox scan
|
|
121
|
+
`),await Te(n),await ln(n,{full:e.full,max:e.max,verbose:e.verbose,dryRun:e.dryRun})}De(s,"success")}catch(r){console.error(`
|
|
122
|
+
\u2717 Error:`,r.message),e.verbose&&console.error(r.stack),De(s,"error",null,r.message)}finally{await o.close()}}gn();
|
package/dist/syncConnections.mjs
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
var Pe=Object.defineProperty;var B=(e,t)=>{for(var o in t)Pe(e,o,{get:t[o],enumerable:!0})};import{pathToFileURL as uo}from"url";var Y={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Ue={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function M(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 J(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=M(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=Ue[n[1].toLowerCase()],c=M(n[2]||""),a=new Date(t),u=a.getDay()-l;return u<=0&&(u+=7),a.setDate(a.getDate()-u),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=Y[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(s[2],10),a=parseInt(s[3],10),f=M(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=Y[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(r[2],10),a=M(r[3]||""),f=t.getFullYear(),u=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return u>t&&u.setFullYear(f-1),u.toISOString()}let i=o.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=Y[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(i[2],10),a=M(i[3]||""),f=t.getFullYear(),u=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return u>t&&u.setFullYear(f-1),u.toISOString()}return null}async function P(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}import{getPluginConfig as qe}from"@ilivemylife/graph-sdk";var Be=await qe();for(let[e,t]of Object.entries(Be))process.env[e]===void 0&&(process.env[e]=t);var Je=process.env.LINKEDIN_NAME,
|
|
1
|
+
var Pe=Object.defineProperty;var B=(e,t)=>{for(var o in t)Pe(e,o,{get:t[o],enumerable:!0})};import{pathToFileURL as uo}from"url";var Y={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},Ue={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function M(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 J(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=M(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=Ue[n[1].toLowerCase()],c=M(n[2]||""),a=new Date(t),u=a.getDay()-l;return u<=0&&(u+=7),a.setDate(a.getDate()-u),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=Y[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(s[2],10),a=parseInt(s[3],10),f=M(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=Y[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(r[2],10),a=M(r[3]||""),f=t.getFullYear(),u=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return u>t&&u.setFullYear(f-1),u.toISOString()}let i=o.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=Y[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(i[2],10),a=M(i[3]||""),f=t.getFullYear(),u=new Date(f,l,c,a?.hours||0,a?.minutes||0,0,0);return u>t&&u.setFullYear(f-1),u.toISOString()}return null}async function P(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(n=>setTimeout(n,o))}import{getPluginConfig as qe}from"@ilivemylife/graph-sdk";var Be=await qe();for(let[e,t]of Object.entries(Be))process.env[e]===void 0&&(process.env[e]=t);var Je=process.env.LINKEDIN_NAME,_=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),$o=Object.freeze(new Set([_.DRAFT,_.CONFIRMED,_.NEEDS_REVIEW])),He=Object.freeze(new Set([_.DRAFT,_.CONFIRMED,_.REJECTED,_.NEEDS_REVIEW]));import"dotenv/config";import*as y from"fs";import*as S from"path";import{fileURLToPath as We}from"url";var Ve=We(import.meta.url),Ye=S.dirname(S.dirname(Ve)),I=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"collected-profiles"):S.join(Ye,"collected-profiles"),G=S.join(I,"people.json"),xo=S.join(I,"jobs.json"),Io=S.join(I,"quota.json"),Do=S.join(I,"conversations.json"),Ro=S.join(I,"sync-state.json"),Oo=S.join(I,"application-questions.json"),_o=S.join(I,"profile-history"),ce=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},jo=ce(process.env.CONNECT_MAX_DAILY,20),No=ce(process.env.CONNECT_MAX_WEEKLY,100),L=null,Ge=null,Ke=null,ze=null,Qe=null,Xe=null;function le(){L=null,Ge=null,Ke=null,ze=null,Qe=null,Xe=null}function ae(){y.existsSync(I)||y.mkdirSync(I,{recursive:!0})}function Ze(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";y.writeFileSync(n,o);for(let s=0;s<3;s++)try{y.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 et(e,t){if(!y.existsSync(e))return null;try{let o=JSON.parse(y.readFileSync(e,"utf-8"));try{y.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${S.resolve(e)}`);let n=e+".backup";if(y.existsSync(n))try{let s=JSON.parse(y.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{y.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{y.copyFileSync(e,e+".corrupted")}catch{}return null}}function H(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function U(){return L||(ae(),L=et(G,"people.json")||{},L)}function ue(e){ae(),L=e;try{Ze(G,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${S.resolve(G)}`)}}import st from"puppeteer";import{addExtra as rt}from"puppeteer-extra";import it from"puppeteer-extra-plugin-stealth";import fe from"fs";import tt from"path";var ot="cookies.json";function nt(){let e=process.env.ILML_SCOPE_DIR;return e?tt.join(e,"plugins-state","linkedin","cookies.json"):ot}function pe(){let e=nt();if(!fe.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=fe.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}var de=rt(st);de.use(it());async function me(){let e=await de.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),t=async()=>{console.log(`
|
|
2
2
|
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t);let o=await e.newPage();await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let n=pe();await o.setCookie(...n),console.log(" Browser launched, cookies loaded.")}catch(n){console.error(`
|
|
3
3
|
[!] ${n.message}
|
|
4
|
-
`),await e.close(),process.exit(1)}return{browser:e,page:o}}import"dotenv/config";import*as
|
|
4
|
+
`),await e.close(),process.exit(1)}return{browser:e,page:o}}import"dotenv/config";import*as $ from"fs";import*as R from"path";import{fileURLToPath as pt}from"url";import"dotenv/config";import{createGraphClient as ct,resolveToken as lt}from"@ilivemylife/graph-sdk";import{config as at}from"dotenv";at();var he=lt()||process.env.TOKEN;he||(console.error(`
|
|
5
5
|
[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.
|
|
6
6
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
7
7
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
8
8
|
`),process.exit(1));var ge=ct({token:he});function ut(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 ft({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?` ${ut(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 ye({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=`**${ft({scriptName:e,mode:t,status:o,error:s,duration:r})}**
|
|
9
9
|
|
|
10
10
|
${n.join(`
|
|
11
|
-
`)}`;try{await ge.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var dt=pt(import.meta.url),mt=D.dirname(D.dirname(dt)),K=process.env.DATA_DIR?D.resolve(process.env.DATA_DIR,"collected-profiles"):D.join(mt,"collected-profiles"),z=D.join(K,"run-log.json");function ht(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";k.writeFileSync(n,o);for(let s=0;s<3;s++)try{k.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 Se(){try{if(!k.existsSync(z))return{runs:[]};let e=JSON.parse(k.readFileSync(z,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function we(e){k.existsSync(K)||k.mkdirSync(K,{recursive:!0});try{ht(z,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function be(e,t="default"){let o=Se();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),we(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function Q(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=Se(),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)}we(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";ye({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"dotenv/config";import*as p from"fs";import*as re from"os";import*as m from"path";import{fileURLToPath as Yt}from"url";var ee={};B(ee,{NAME:()=>yt,VERSION:()=>gt,up:()=>bt});import*as $ from"fs";import*as W from"path";var gt=1,yt="normalize-jobs-and-questions",St=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],wt=50;function X(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Z(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{$.writeFileSync(n,o)}catch(s){try{$.unlinkSync(n)}catch{}throw s}try{$.renameSync(n,e)}catch(s){try{$.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 bt(e,t){let o=W.join(e,"jobs.json"),n=W.join(t,"scouted-jobs.json"),s=W.join(e,"application-questions.json"),r=X(o)||{},i=X(n)||{},l=0,c=[];for(let f of Object.keys(r)){if(!i[f])continue;let u=i[f],d=r[f];for(let g of St)u[g]!=null&&d[g]==null&&(d[g]=u[g]);c.push(f),l++}l>0?(Z(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=X(s);if(a&&Array.isArray(a.applications)){let f={},u=0;for(let d of a.applications){let g=d.jobId||"unknown";f[g]||(f[g]={applications:[]});let y=(d.questions||[]).map(h=>{let F={type:h.type||"input",question:h.question||"",answer:h.answer||""};return h.options&&(h.options.length<=wt?F.options=h.options:(F.optionsOmitted=!0,u++)),h.page&&(F.page=h.page),h.wasPreFilled&&(F.wasPreFilled=!0),h.wasRetry&&(F.wasRetry=!0),F});f[g].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||y.length,questions:y})}Z(s,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),u>0&&console.log(` Phase 2: Stripped bloated options from ${u} 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];Z(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 te={};B(te,{NAME:()=>kt,VERSION:()=>vt,up:()=>Ct});import*as A from"fs";import*as ve from"path";var vt=2,kt="reset-unread-flags";function $t(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function At(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{A.writeFileSync(n,o)}catch(s){try{A.unlinkSync(n)}catch{}throw s}try{A.renameSync(n,e)}catch(s){try{A.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 Ct(e){let t=ve.join(e,"conversations.json"),o=$t(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}At(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var oe={};B(oe,{NAME:()=>Tt,VERSION:()=>Et,up:()=>Ot});import*as C from"fs";import*as ke from"path";var Et=3,Tt="recompute-last-message-by",xt=new Set(["draft","confirmed","rejected","needs_review"]);function It(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function Dt(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{C.writeFileSync(n,o)}catch(s){try{C.unlinkSync(n)}catch{}throw s}try{C.renameSync(n,e)}catch(s){try{C.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 Rt(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!xt.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 Ot(e){let t=ke.join(e,"conversations.json"),o=It(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=Rt(a,n),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,s++}if(s===0){console.log(" No conversations to recompute.");return}Dt(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 ne={};B(ne,{NAME:()=>jt,VERSION:()=>_t,up:()=>Mt});import*as E from"fs";import*as $e from"path";var _t=4,jt="split-connection-timestamps",Nt=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ft(e){if(!E.existsSync(e))return null;let t=E.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Lt(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{E.writeFileSync(n,o)}catch(s){try{E.unlinkSync(n)}catch{}throw s}try{E.renameSync(n,e)}catch(s){try{E.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 Mt(e){let t=$e.join(e,"people.json"),o=Ft(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++,Nt.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}Lt(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 v from"path";import{fileURLToPath as Pt}from"url";var Ut=Pt(import.meta.url),qt=v.dirname(v.dirname(Ut)),q=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"market-research"):v.join(qt,"market-research"),ln=v.join(q,"scouted-jobs.json"),an=v.join(q,"discovered-people.json"),un=v.join(q,"visit-log.json"),fn=v.join(q,"companies.json"),pn=v.join(q,"job-decisions.json");function Ae(){Bt=null,Jt=null,Ht=null,Wt=null,Vt=null}var Bt=null;var Jt=null;var Ht=null;var Wt=null;var Vt=null;var Gt=Yt(import.meta.url),Kt=m.dirname(Gt),zt=m.dirname(m.dirname(Kt));function Qt(e){return e&&(e==="~"?re.homedir():e.startsWith("~/")||e.startsWith("~\\")?m.join(re.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?m.resolve(Qt(process.env.DATA_DIR)):zt,j=m.join(T,"collected-profiles"),N=m.join(T,"market-research"),b=m.join(T,".schema-version"),Ce=[m.join(j,".schema-version"),m.join(N,".schema-version")],R=4,I=[{version:1,module:ee},{version:2,module:te},{version:3,module:oe},{version:4,module:ne}];(function(){I.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of I){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=I.length?I[I.length-1].version:0;if(o!==R)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${R}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<I.length;n++){let s=n+1;if(I[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${I[n].version}`)}})();function Ie(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
11
|
+
`)}`;try{await ge.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var dt=pt(import.meta.url),mt=R.dirname(R.dirname(dt)),K=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(mt,"collected-profiles"),z=R.join(K,"run-log.json");function ht(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";$.writeFileSync(n,o);for(let s=0;s<3;s++)try{$.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 Se(){try{if(!$.existsSync(z))return{runs:[]};let e=JSON.parse($.readFileSync(z,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function we(e){$.existsSync(K)||$.mkdirSync(K,{recursive:!0});try{ht(z,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function be(e,t="default"){let o=Se();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),we(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function Q(e,t,o=null,n=null){if(!e)return;let s=null;try{let i=Se(),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)}we(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";ye({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"dotenv/config";import*as p from"fs";import*as re from"os";import*as h from"path";import{fileURLToPath as Yt}from"url";var ee={};B(ee,{NAME:()=>yt,VERSION:()=>gt,up:()=>bt});import*as A from"fs";import*as W from"path";var gt=1,yt="normalize-jobs-and-questions",St=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],wt=50;function X(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Z(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{A.writeFileSync(n,o)}catch(s){try{A.unlinkSync(n)}catch{}throw s}try{A.renameSync(n,e)}catch(s){try{A.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 bt(e,t){let o=W.join(e,"jobs.json"),n=W.join(t,"scouted-jobs.json"),s=W.join(e,"application-questions.json"),r=X(o)||{},i=X(n)||{},l=0,c=[];for(let f of Object.keys(r)){if(!i[f])continue;let u=i[f],m=r[f];for(let g of St)u[g]!=null&&m[g]==null&&(m[g]=u[g]);c.push(f),l++}l>0?(Z(o,r),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=X(s);if(a&&Array.isArray(a.applications)){let f={},u=0;for(let m of a.applications){let g=m.jobId||"unknown";f[g]||(f[g]={applications:[]});let v=(m.questions||[]).map(d=>{let w={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=wt?w.options=d.options:(w.optionsOmitted=!0,u++)),d.page&&(w.page=d.page),d.wasPreFilled&&(w.wasPreFilled=!0),d.wasRetry&&(w.wasRetry=!0),w});f[g].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||v.length,questions:v})}Z(s,f),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),u>0&&console.log(` Phase 2: Stripped bloated options from ${u} 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];Z(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 te={};B(te,{NAME:()=>kt,VERSION:()=>vt,up:()=>Ct});import*as C from"fs";import*as ve from"path";var vt=2,kt="reset-unread-flags";function $t(e){return C.existsSync(e)?JSON.parse(C.readFileSync(e,"utf-8")):null}function At(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{C.writeFileSync(n,o)}catch(s){try{C.unlinkSync(n)}catch{}throw s}try{C.renameSync(n,e)}catch(s){try{C.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 Ct(e){let t=ve.join(e,"conversations.json"),o=$t(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}At(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var oe={};B(oe,{NAME:()=>Tt,VERSION:()=>Et,up:()=>Ot});import*as E from"fs";import*as ke from"path";var Et=3,Tt="recompute-last-message-by",xt=new Set(["draft","confirmed","rejected","needs_review"]);function It(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function Dt(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{E.writeFileSync(n,o)}catch(s){try{E.unlinkSync(n)}catch{}throw s}try{E.renameSync(n,e)}catch(s){try{E.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 Rt(e,t){if(!e||e.length===0)return"them";let o=e.filter(r=>!xt.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 Ot(e){let t=ke.join(e,"conversations.json"),o=It(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=Rt(a,n),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,s++}if(s===0){console.log(" No conversations to recompute.");return}Dt(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 ne={};B(ne,{NAME:()=>jt,VERSION:()=>_t,up:()=>Mt});import*as T from"fs";import*as $e from"path";var _t=4,jt="split-connection-timestamps",Nt=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Ft(e){if(!T.existsSync(e))return null;let t=T.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Lt(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{T.writeFileSync(n,o)}catch(s){try{T.unlinkSync(n)}catch{}throw s}try{T.renameSync(n,e)}catch(s){try{T.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 Mt(e){let t=$e.join(e,"people.json"),o=Ft(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++,Nt.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}Lt(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 k from"path";import{fileURLToPath as Pt}from"url";var Ut=Pt(import.meta.url),qt=k.dirname(k.dirname(Ut)),q=process.env.DATA_DIR?k.resolve(process.env.DATA_DIR,"market-research"):k.join(qt,"market-research"),ln=k.join(q,"scouted-jobs.json"),an=k.join(q,"discovered-people.json"),un=k.join(q,"visit-log.json"),fn=k.join(q,"companies.json"),pn=k.join(q,"job-decisions.json");function Ae(){Bt=null,Jt=null,Ht=null,Wt=null,Vt=null}var Bt=null;var Jt=null;var Ht=null;var Wt=null;var Vt=null;var Gt=Yt(import.meta.url),Kt=h.dirname(Gt),zt=h.dirname(h.dirname(Kt));function Qt(e){return e&&(e==="~"?re.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(re.homedir(),e.slice(2)):e)}var x=process.env.DATA_DIR?h.resolve(Qt(process.env.DATA_DIR)):zt,N=h.join(x,"collected-profiles"),F=h.join(x,"market-research"),b=h.join(x,".schema-version"),Ce=[h.join(N,".schema-version"),h.join(F,".schema-version")],O=4,D=[{version:1,module:ee},{version:2,module:te},{version:3,module:oe},{version:4,module:ne}];(function(){D.sort((n,s)=>n.version-s.version);let t=new Set;for(let n of D){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=D.length?D[D.length-1].version:0;if(o!==O)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${O}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<D.length;n++){let s=n+1;if(D[n].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${n} but found v${D[n].version}`)}})();function Ie(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
12
12
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
13
|
-
`),process.exit(1));try{p.mkdirSync(
|
|
14
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
15
|
-
`),process.exit(1))}let e;try{e=p.statSync(
|
|
16
|
-
[FATAL] DATA_DIR (${
|
|
13
|
+
`),process.exit(1));try{p.mkdirSync(x,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
14
|
+
[FATAL] Cannot create DATA_DIR (${x}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
15
|
+
`),process.exit(1))}let e;try{e=p.statSync(x)}catch(t){console.error(`
|
|
16
|
+
[FATAL] DATA_DIR (${x}) is not accessible: ${t.message}
|
|
17
17
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
18
|
-
[FATAL] DATA_DIR (${
|
|
19
|
-
`),process.exit(1));for(let t of[
|
|
18
|
+
[FATAL] DATA_DIR (${x}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
19
|
+
`),process.exit(1));for(let t of[N,F]){let o;try{o=p.lstatSync(t)}catch(n){if(n.code==="ENOENT")continue;throw n}o.isSymbolicLink()&&(console.error(`
|
|
20
20
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
21
|
-
`),process.exit(1))}}var
|
|
22
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
21
|
+
`),process.exit(1))}}var j=h.join(x,".migration-lock");function Xt(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return p.writeFileSync(j,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let t;try{t=JSON.parse(p.readFileSync(j,"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(`
|
|
22
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${j}
|
|
23
23
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
24
|
-
`),process.exit(1)),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=
|
|
24
|
+
`),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=j+".tmp";try{return p.writeFileSync(o,e),p.renameSync(o,j),!0}catch(n){try{p.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function ie(){try{if(JSON.parse(p.readFileSync(j,"utf-8")).pid!==process.pid)return;p.unlinkSync(j)}catch{}}var Ee=!1;function Zt(){if(Ee)return;Ee=!0;let e=()=>{try{ie()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function eo(){if(p.existsSync(b))return;let e=[],t=[];for(let r of Ce)if(p.existsSync(r))try{e.push({file:r,schema:V(r)})}catch(i){t.push({file:r,err:i.message})}if(t.length>0){console.error(`
|
|
25
25
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let r of t)console.error(` ${r.file}: ${r.err}`);console.error(`
|
|
26
26
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
27
27
|
`),process.exit(1)}if(e.length===0)return;let o=e.map(r=>r.schema.version);if(new Set(o).size>1){console.error(`
|
|
@@ -30,36 +30,37 @@ ${n.join(`
|
|
|
30
30
|
[FATAL] ${b} 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.
|
|
31
31
|
`),process.exit(1)}let t=to(e);return t===null&&(console.error(`
|
|
32
32
|
[FATAL] ${b} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
33
|
-
`),process.exit(1)),t}function De(e){try{p.chmodSync(e,384)}catch{}}function oo(e){if(Ie(),p.existsSync(b))try{if(p.lstatSync(b).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${b}. 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=b+".tmp";try{p.writeFileSync(t,JSON.stringify(e,null,2)),De(t),p.renameSync(t,b)}catch(o){try{p.unlinkSync(t)}catch{}throw o}}function xe(e,t){if(!p.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=p.readdirSync(e).filter(l=>{let c=l.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return p.statSync(
|
|
34
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
35
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
33
|
+
`),process.exit(1)),t}function De(e){try{p.chmodSync(e,384)}catch{}}function oo(e){if(Ie(),p.existsSync(b))try{if(p.lstatSync(b).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${b}. 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=b+".tmp";try{p.writeFileSync(t,JSON.stringify(e,null,2)),De(t),p.renameSync(t,b)}catch(o){try{p.unlinkSync(t)}catch{}throw o}}function xe(e,t){if(!p.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,n=p.readdirSync(e).filter(l=>{let c=l.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return p.statSync(h.join(e,l)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let l of n){let c=h.join(e,l),a=h.join(e,l+o);if(p.existsSync(a)){r++;continue}try{Oe(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 ${h.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 ${h.basename(e)}/ (${o})${l}`)}}var se=!1;async function Re(){if(se)return;Ie(),co();let t=Te().version;if(t===O){se=!0;return}Zt(),Xt(),process.on("exit",ie),t>O&&(console.error(`
|
|
34
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${O}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
35
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${O}.
|
|
36
36
|
`),process.exit(1)),console.log(`
|
|
37
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
37
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${O}`);let o=lo();if(!o.ok){console.error(`
|
|
38
38
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of o.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
39
39
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
40
|
-
`),process.exit(1)}let n=
|
|
41
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{xe(
|
|
40
|
+
`),process.exit(1)}let n=D.filter(s=>s.version>t);for(let s of n){console.log(`
|
|
41
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{xe(N,s.version),xe(F,s.version)}catch(c){console.error(`
|
|
42
42
|
[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.
|
|
43
|
-
`),process.exit(1)}let l=s.module;try{await l.up(
|
|
43
|
+
`),process.exit(1)}let l=s.module;try{await l.up(N,F)}catch(c){console.error(`
|
|
44
44
|
[FATAL] Migration ${r} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=ao(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.
|
|
45
45
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
46
46
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
47
47
|
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:s.version,name:l.NAME||r,appliedAt:c},f=Te();f.version=s.version,f.migratedAt=c,f.migrations=f.migrations||[],f.migrations.push(a),oo(f)}catch(c){console.error(`
|
|
48
48
|
[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.
|
|
49
49
|
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{le()}catch{}try{Ae()}catch{}se=!0,ie(),console.log(`
|
|
50
|
-
\u2713 Schema is now at v${
|
|
51
|
-
`)}var no=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function so(e){let t=e.toLowerCase();return no.some(o=>o.test(t))}var ro=6e4;function io(){let e=Date.now(),t=[];for(let o of[
|
|
50
|
+
\u2713 Schema is now at v${O}
|
|
51
|
+
`)}var no=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function so(e){let t=e.toLowerCase();return no.some(o=>o.test(t))}var ro=6e4;function io(){let e=Date.now(),t=[];for(let o of[x,N,F]){if(!p.existsSync(o))continue;let n;try{n=p.readdirSync(o)}catch{continue}for(let s of n){if(!so(s))continue;let r=h.join(o,s);try{let i=p.statSync(r);if(!i.isFile()||e-i.mtimeMs<ro)continue;t.push({dir:o,file:s,fullPath:r})}catch{}}}return t}function co({verbose:e=!1}={}){let t=io();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let n of t)try{p.unlinkSync(n.fullPath),o++,e&&console.log(` Removed orphan: ${h.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 lo(){let e=[];for(let t of[N,F]){if(!p.existsSync(t))continue;let o=p.readdirSync(t).filter(n=>{let s=n.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let n of o){let s=h.join(t,n);try{V(s)}catch(r){e.push({dir:h.basename(t),file:n,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function ao(e){let t=[],o=[];for(let r of[N,F]){if(!p.existsSync(r))continue;let i=p.readdirSync(r).filter(l=>l.endsWith(e));for(let l of i){let c=h.join(r,l),a=l.slice(0,-e.length),f=h.join(r,a);try{a.toLowerCase().endsWith(".json")?V(c):p.accessSync(c,p.constants.R_OK),t.push({backupPath:c,originalPath:f,fileName:l,dir:r})}catch(u){o.push(`${h.basename(r)}/${l}: ${u.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{Oe(r,i),n++}catch(a){s.push(`${h.basename(c)}/${l}: ${a.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:n}:{ok:!0,restored:n}}function Oe(e,t){let o=t+".tmp";try{p.copyFileSync(e,o),De(o)}catch(n){try{p.unlinkSync(o)}catch{}throw n}try{p.renameSync(o,t)}catch(n){try{p.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}}function fo(){let e={list:!1,full:!1,max:1/0,dryRun:!1,verbose:!1};for(let t of process.argv.slice(2))t==="--list"?e.list=!0:t==="--full"?e.full=!0:t==="--dry-run"?e.dryRun=!0:t==="--verbose"?e.verbose=!0:t.startsWith("--max=")&&(e.max=parseInt(t.split("=")[1],10));return e}function po(){let e=U(),t=Object.values(e),o=t.length,n={};for(let r of t){let i=r.connectionStatus||"(none)";n[i]=(n[i]||0)+1}let s={};for(let r of t){for(let i of r.sources||[])s[i]=(s[i]||0)+1;(!r.sources||r.sources.length===0)&&(s["(no source)"]=(s["(no source)"]||0)+1)}console.log(`
|
|
52
52
|
=== People Database: ${o} entries ===
|
|
53
53
|
`),console.log("By connection status:");for(let[r,i]of Object.entries(n).sort((l,c)=>c[1]-l[1]))console.log(` ${r.padEnd(30)} ${i}`);console.log(`
|
|
54
|
-
By source:`);for(let[r,i]of Object.entries(s).sort((l,c)=>c[1]-l[1]))console.log(` ${r.padEnd(30)} ${i}`);console.log()}async function mo(e){let t="https://www.linkedin.com/mynetwork/invite-connect/connections/";console.log(`Navigating to ${t}`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await P(3e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector('main a[href*="/in/"]',{timeout:15e3})}catch{console.warn("\u26A0 No connection cards found after 15s. Page may have changed layout.")}let n=await e.evaluate(()=>{let i=((document.querySelector("main")||document.body).innerText||"").match(/([\d,]+)\s+connections?/i);return i?parseInt(i[1].replace(/,/g,""),10):null});return n&&console.log(` LinkedIn reports: ${n.toLocaleString()} connections`),n}async function je(e){return e.evaluate(()=>{let o=(document.querySelector("main")||document.body).querySelectorAll('a[href*="/in/"]'),n={};for(let
|
|
55
|
-
`)
|
|
54
|
+
By source:`);for(let[r,i]of Object.entries(s).sort((l,c)=>c[1]-l[1]))console.log(` ${r.padEnd(30)} ${i}`);console.log()}async function mo(e){let t="https://www.linkedin.com/mynetwork/invite-connect/connections/";console.log(`Navigating to ${t}`),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await P(3e3);let o=e.url();if(o.includes("/login")||o.includes("/authwall"))throw new Error("Redirected to login \u2014 cookies expired. Run: npm run login");try{await e.waitForSelector('main a[href*="/in/"]',{timeout:15e3})}catch{console.warn("\u26A0 No connection cards found after 15s. Page may have changed layout.")}let n=await e.evaluate(()=>{let i=((document.querySelector("main")||document.body).innerText||"").match(/([\d,]+)\s+connections?/i);return i?parseInt(i[1].replace(/,/g,""),10):null});return n&&console.log(` LinkedIn reports: ${n.toLocaleString()} connections`),n}async function je(e){return e.evaluate(()=>{let o=(document.querySelector("main")||document.body).querySelectorAll('a[href*="/in/"]'),n={};for(let i of o){let l=i.getAttribute("href");if(!l)continue;let c;try{let a=new URL(l,location.origin);c=a.origin+a.pathname.replace(/\/+$/,"")}catch{continue}n[c]||(n[c]=[]),n[c].push(i)}let s=[],r=i=>((i&&(i.innerText||i.textContent)||"").trim().split(`
|
|
55
|
+
`)[0]||"").trim();for(let[i,l]of Object.entries(n)){let c=null;for(let d of l){let w=r(d);!w||d.querySelector("img")||(!c||w.length<r(c).length)&&(c=d)}let a=r(c)||null,f=c||l[0];for(let d=0;d<10&&f?.parentElement;d++){f=f.parentElement;let w=f.innerText||"";if((w.includes("Connected on")||w.includes("Message"))&&(w.match(/Connected on/g)||[]).length<=1)break}let u=(f?.innerText||"").split(`
|
|
56
|
+
`).map(d=>d.trim()).filter(Boolean),m=null,g=null,v=u.indexOf(a);if(v>=0&&v+1<u.length){let d=u[v+1];!d.startsWith("Connected on")&&d!=="Message"&&(m=d)}for(let d of u)if(d.startsWith("Connected on")){g=d;break}s.push({profileUrl:i,name:a,title:m,time:g})}return s})}async function Ne(e){return e.evaluate(()=>{let t=document.querySelector("main")||document.body,o=null,n=[t,...t.querySelectorAll("div, section")];for(let r of n){let i=getComputedStyle(r);if((i.overflowY==="auto"||i.overflowY==="scroll")&&r.scrollHeight>r.clientHeight+10){o=r;break}}o&&o.scrollBy(0,800),window.scrollBy(0,800);let s=document.querySelectorAll("button");for(let r of s){let i=r.textContent?.trim().toLowerCase()||"";if((i.includes("load more")||i.includes("show more"))&&r.getBoundingClientRect().height>0)return r.click(),"clicked"}return o?"scrolled":"window-scroll"})}async function ho(e,t){let{max:o,verbose:n,dryRun:s}=t,r=new Map,i=0,l=0,c=3,a=10;for(;;){i++;let f=await je(e),u=0;for(let g of f)g.profileUrl&&(r.has(g.profileUrl)||(r.set(g.profileUrl,g),u++));if(n?console.log(` Round #${i}: ${u} new | Total: ${r.size}`):process.stdout.write(`\r Connections found: ${r.size} (page #${i})`),!s&&i%a===0&&(Me(Array.from(r.values()),!1),n&&console.log(` \u{1F4BE} Saved progress (${r.size} connections)`)),r.size>=o){console.log(`
|
|
56
57
|
Reached --max=${o}, stopping.`);break}if(u===0){if(l++,l>=c){console.log(`
|
|
57
|
-
${c} rounds with no new cards \u2014 end of list.`);break}}else l=0;let
|
|
58
|
-
`),Array.from(r.values())}async function go(e,t){let{max:o,verbose:n}=t,s=U(),r=new Set;for(let[f,u]of Object.entries(s))u.connectionStatus==="connected"&&u.sources?.includes("sync-connections")&&r.add(f);console.log(` Known synced connections in DB: ${r.size}`);let i=new Map,l=0,c=0,a=3;for(;;){l++;let f=await je(e),u=0,
|
|
59
|
-
Reached --max=${o}, stopping.`);break}if(u===0&&
|
|
58
|
+
${c} rounds with no new cards \u2014 end of list.`);break}}else l=0;let m=await Ne(e);n&&m==="clicked"&&console.log(' \u2192 Clicked "Load more"'),await P(2e3)}return n||process.stdout.write(`
|
|
59
|
+
`),Array.from(r.values())}async function go(e,t){let{max:o,verbose:n}=t,s=U(),r=new Set;for(let[f,u]of Object.entries(s))u.connectionStatus==="connected"&&u.sources?.includes("sync-connections")&&r.add(f);console.log(` Known synced connections in DB: ${r.size}`);let i=new Map,l=0,c=0,a=3;for(;;){l++;let f=await je(e),u=0,m=0;for(let d of f)d.profileUrl&&(i.has(d.profileUrl)||(i.set(d.profileUrl,d),r.has(d.profileUrl)?m++:u++));let g=Array.from(i.values()).filter(d=>!r.has(d.profileUrl)).length;if(n?console.log(` Round #${l}: ${u} new, ${m} known | New total: ${g}`):process.stdout.write(`\r New connections: ${g} (page #${l})`),g>=o){console.log(`
|
|
60
|
+
Reached --max=${o}, stopping.`);break}if(u===0&&m>0){if(c++,c>=a){console.log(`
|
|
60
61
|
${a} consecutive pages of known connections \u2014 caught up.`);break}}else if(u>0)c=0;else if(c++,c>=a){console.log(`
|
|
61
|
-
${a} empty rounds \u2014 end of list.`);break}let
|
|
62
|
-
`),Array.from(i.values())}var Fe=new Set(["pending","sent_with_note","sent_without_note","sent_without_note_upsell"]);function _e(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Le(e){let t=new Map;for(let[o,n]of Object.entries(e)){let s=H(n.profileUrl||o);s&&!t.has(s)&&t.set(s,o)}for(let[o,n]of Object.entries(e))for(let s of n.aliases||[])s&&!t.has(s)&&t.set(s,o);return t}function yo(e,t){let o=[],n=Le(t);for(let s of e){if(!s.profileUrl)continue;let r=n.get(H(s.profileUrl)),i=r?t[r]:void 0;i&&Fe.has(i.connectionStatus)&&o.push({...s,previousStatus:i.connectionStatus})}return o}function Me(e,t){let o=U(),n=new Date().toISOString(),s=n.slice(0,10),r={newPeople:0,updatedToConnected:0,alreadyConnected:0,flaggedDuplicates:0,flagged:[]},i=Le(o),l=new Map;for(let[c,a]of Object.entries(o)){if(!Fe.has(a.connectionStatus))continue;let f=_e(a.name);f&&(l.has(f)||l.set(f,[]),l.get(f).push(c))}for(let c of e){if(!c.profileUrl)continue;let a=H(c.profileUrl),f=a?i.get(a):null,u=f?o[f]:void 0;if(u){if(u.connectionStatus!=="connected"){u.connectionStatus="connected";let
|
|
62
|
+
${a} empty rounds \u2014 end of list.`);break}let v=await Ne(e);n&&v==="clicked"&&console.log(' \u2192 Clicked "Load more"'),await P(2e3)}return n||process.stdout.write(`
|
|
63
|
+
`),Array.from(i.values())}var Fe=new Set(["pending","sent_with_note","sent_without_note","sent_without_note_upsell"]);function _e(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function Le(e){let t=new Map;for(let[o,n]of Object.entries(e)){let s=H(n.profileUrl||o);s&&!t.has(s)&&t.set(s,o)}for(let[o,n]of Object.entries(e))for(let s of n.aliases||[])s&&!t.has(s)&&t.set(s,o);return t}function yo(e,t){let o=[],n=Le(t);for(let s of e){if(!s.profileUrl)continue;let r=n.get(H(s.profileUrl)),i=r?t[r]:void 0;i&&Fe.has(i.connectionStatus)&&o.push({...s,previousStatus:i.connectionStatus})}return o}function Me(e,t){let o=U(),n=new Date().toISOString(),s=n.slice(0,10),r={newPeople:0,updatedToConnected:0,alreadyConnected:0,flaggedDuplicates:0,flagged:[]},i=Le(o),l=new Map;for(let[c,a]of Object.entries(o)){if(!Fe.has(a.connectionStatus))continue;let f=_e(a.name);f&&(l.has(f)||l.set(f,[]),l.get(f).push(c))}for(let c of e){if(!c.profileUrl)continue;let a=H(c.profileUrl),f=a?i.get(a):null,u=f?o[f]:void 0;if(u){if(u.connectionStatus!=="connected"){u.connectionStatus="connected";let m=c.time?J(c.time.replace(/^Connected\s+on\s+/i,"")):null;u.connectedAt=m||n,u.connectionDate=(m||n).slice(0,10),u.lastUpdated=n,r.updatedToConnected++}else if(r.alreadyConnected++,c.time&&(!u.connectedAt||!u.connectionDate)){let m=J(c.time.replace(/^Connected\s+on\s+/i,""));m&&(u.connectedAt||(u.connectedAt=m),u.connectionDate||(u.connectionDate=m.slice(0,10)),u.lastUpdated=n)}c.name&&!u.name&&(u.name=c.name),c.title&&(u.title=c.title),u.sources||(u.sources=[]),u.sources.includes("sync-connections")||u.sources.push("sync-connections"),u.lastSeen=s,u.seenCount=(u.seenCount||1)+1,u.lastUpdated=n}else{let m={name:c.name,title:c.title,location:null,company:null,connectionDegree:"1st",connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1,firstSeen:s,lastSeen:s,seenCount:1,sources:["sync-connections"],connectionStatus:"connected",connectionDate:s,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:n},g=_e(c.name),v=g?l.get(g)||[]:[];v.length&&(m.possibleDuplicateOf=[...v],r.flaggedDuplicates++,r.flagged.push({name:c.name,candidates:v.length})),o[c.profileUrl]=m,a&&i.set(a,c.profileUrl),r.newPeople++}}return t||ue(o),r}function So(e,t,o,n,s,r){if(console.log(`
|
|
63
64
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` Sync Connections Summary (${r})`),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"),s&&console.log(` LinkedIn header: ${s.toLocaleString()}`),console.log(` Connections scraped: ${e.length}`),console.log(` New people added: ${o.newPeople}`),console.log(` Updated to connected: ${o.updatedToConnected}`),console.log(` Already connected: ${o.alreadyConnected}`),t.length>0){console.log(`
|
|
64
65
|
Newly accepted (${t.length}):`);for(let i of t)console.log(` \u2713 ${i.name||"Unknown"} (was: ${i.previousStatus})`)}if(o.flaggedDuplicates>0){console.log(`
|
|
65
66
|
\u26A0 Possible duplicates (${o.flaggedDuplicates}) \u2014 new connection shares a name with a still-pending person (likely the same person accepting under a vanity url we couldn't match by slug). Flagged for review, NOT merged:`);for(let i of o.flagged||[])console.log(` ? ${i.name||"Unknown"}${i.candidates>1?` (${i.candidates} candidates)`:""}`)}n&&console.log(`
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.17.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.17.2";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.17.
|
|
3
|
+
"version": "1.17.2",
|
|
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