ilml-plugin-linkedin 1.20.12 → 1.20.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/applyQueue.mjs +26 -26
- package/dist/connect.mjs +49 -49
- package/dist/daily.mjs +33 -33
- package/dist/enrichProfile.mjs +11 -11
- package/dist/enrichProfiles.mjs +38 -38
- package/dist/funnelRunner.mjs +39 -39
- package/dist/messageBot.mjs +40 -40
- package/dist/migrationCli.mjs +43 -43
- package/dist/profileHistory.mjs +8 -8
- package/dist/quota.mjs +32 -32
- package/dist/run.mjs +64 -61
- package/dist/scout.mjs +40 -39
- package/dist/src/saveLoginState.mjs +4 -4
- package/dist/syncAll.mjs +73 -73
- package/dist/syncConnections.mjs +30 -30
- package/dist/verifyAbout.mjs +14 -14
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +43 -43
- package/dist/visit.mjs +35 -35
- package/dist/warmScan.mjs +3 -3
- package/ilml-plugin.json +11 -2
- package/package.json +2 -2
package/dist/syncConnections.mjs
CHANGED
|
@@ -1,71 +1,71 @@
|
|
|
1
|
-
var
|
|
1
|
+
var mt=Object.defineProperty;var W=(e,t)=>{for(var n in t)mt(e,n,{get:t[n],enumerable:!0})};import{pathToFileURL as Xn}from"url";import b from"fs";import R from"path";var ht="cookies.json";function X(){let e=process.env.ILML_SCOPE_DIR;return e?R.join(e,"plugins-state","linkedin","cookies.json"):ht}function gt(){let e=X(),t=R.dirname(e);return t&&t!=="."&&!b.existsSync(t)&&b.mkdirSync(t,{recursive:!0}),e}function ge(e){let t=gt();return b.writeFileSync(t,JSON.stringify(e)),t}function ye(){let e=X();if(!b.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=b.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function Se(){return b.existsSync(X())}function yt(){let e=process.env.ILML_SCOPE_DIR;return e?R.join(e,"plugins-state","linkedin"):"."}function we(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function St(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?we(t[1]):"default"}function be(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return b.existsSync(t)||b.mkdirSync(t,{recursive:!0}),R.resolve(t);let n=we(e||St()),o=R.join(yt(),"chrome-profile",n);return b.existsSync(o)||b.mkdirSync(o,{recursive:!0}),R.resolve(o)}var ve=".ilml-seeded";function ke(e){return!b.existsSync(R.join(e,ve))}function Ae(e){try{b.writeFileSync(R.join(e,ve),new Date().toISOString())}catch{}}function Ce(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{b.rmSync(R.join(e,n),{force:!0}),t++}catch{}return t}var Z={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11},wt={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};function U(e){let t=e.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);if(!t)return null;let n=parseInt(t[1],10),o=parseInt(t[2],10),r=t[3].toUpperCase()==="PM";return r&&n!==12&&(n+=12),!r&&n===12&&(n=0),{hours:n,minutes:o}}function Y(e,t){if(!e)return null;let n=e.trim();if(!n)return null;if(t=t||new Date,/^just\s*now$/i.test(n))return t.toISOString();if(/^today\b/i.test(n)||/^\d{1,2}:\d{2}\s*(AM|PM)$/i.test(n)){let l=U(n),c=new Date(t);return l?c.setHours(l.hours,l.minutes,0,0):c.setHours(0,0,0,0),c.toISOString()}let o=n.match(/^(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*(.*)/i);if(o){let l=wt[o[1].toLowerCase()],c=U(o[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 r=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),?\s+(\d{4})\s*(.*)/i);if(r){let l=Z[r[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(r[2],10),a=parseInt(r[3],10),f=U(r[4]||"");return new Date(a,l,c,f?.hours||0,f?.minutes||0,0,0).toISOString()}let s=n.match(/^([A-Z][a-z]+)\s+(\d{1,2}),\s*(.*)/i);if(s){let l=Z[s[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(s[2],10),a=U(s[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=n.match(/^([A-Z][a-z]+)\s+(\d{1,2})\s*(.*)/i);if(i){let l=Z[i[1].toLowerCase().slice(0,3)];if(l===void 0)return null;let c=parseInt(i[2],10),a=U(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 V(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function bt(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(l=>!!document.querySelector(l),t)){let l=Date.now()-s;return l>6e3&&console.log(` (waited ${Math.round(l/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}var $e=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function vt(e){return $e.test(e||"")}async function kt(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let c="wait";try{c=await e.evaluate(a=>!new RegExp(a).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",$e.source)}catch{}if(c==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(u=>u.name==="li_at")){let u=ge(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${u}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(a){console.log(` \u2713 Session recovered (cookie re-save skipped: ${a.message}).`)}return!0}if(c==="creds"){if(!o){let a=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}i||(i=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(a=>setTimeout(a,2500))}let l=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function
|
|
3
|
+
`))}await new Promise(a=>setTimeout(a,2500))}let l=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function Ee(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await bt(e,t,{timeout:o,label:n});if(!r&&vt(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function ee(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await Ee(e,{readySelector:n,label:o,timeout:r})}catch(l){if(i&&l.code==="SESSION_EXPIRED"){await kt(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await Ee(e,{readySelector:n,label:o,timeout:r})}throw l}}import{getPluginConfig as Et}from"@ilivemylife/graph-sdk";var At={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},_e=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Ct(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function xe(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),_e(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),_e(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let i=Ct(e.JOB_SEARCH_COMPANY_IDS);i.length&&n.set("f_C",i.join(","));let l=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();l&&n.set("f_TPR",At[l]||l),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let c="https://www.linkedin.com/jobs/search/?"+n.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(c+="&"+a),c}var $t=await Et();for(let[e,t]of Object.entries($t))process.env[e]===void 0&&(process.env[e]=t);var Ie=xe(process.env);Ie&&(process.env.LINKEDIN_SEARCH_URL=Ie);var _t=process.env.LINKEDIN_NAME,N=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),yo=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.NEEDS_REVIEW])),xt=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.REJECTED,N.NEEDS_REVIEW]));import"dotenv/config";import*as y from"fs";import*as S from"path";import{fileURLToPath as It}from"url";var Rt=It(import.meta.url),Tt=S.dirname(S.dirname(Rt)),T=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"collected-profiles"):S.join(Tt,"collected-profiles"),te=S.join(T,"people.json"),ko=S.join(T,"jobs.json"),Ao=S.join(T,"quota.json"),Co=S.join(T,"conversations.json"),Eo=S.join(T,"sync-state.json"),$o=S.join(T,"application-questions.json"),_o=S.join(T,"profile-history"),Re=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},xo=Re(process.env.CONNECT_MAX_DAILY,20),Io=Re(process.env.CONNECT_MAX_WEEKLY,100),M=null,Dt=null,Ot=null,jt=null,Nt=null,Ft=null;function Te(){M=null,Dt=null,Ot=null,jt=null,Nt=null,Ft=null}function De(){y.existsSync(T)||y.mkdirSync(T,{recursive:!0})}function Lt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";y.writeFileSync(o,n);for(let r=0;r<3;r++)try{y.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Pt(e,t){if(!y.existsSync(e))return null;try{let n=JSON.parse(y.readFileSync(e,"utf-8"));try{y.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${S.resolve(e)}`);let o=e+".backup";if(y.existsSync(o))try{let r=JSON.parse(y.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{y.copyFileSync(o,e)}catch{}return r}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 G(e){if(!e)return null;let t=e.match(/\/in\/([^/?#]+)/);return t?t[1].toLowerCase():null}function q(){return M||(De(),M=Pt(te,"people.json")||{},M)}function Oe(e){De(),M=e;try{Lt(te,e)}catch(t){console.error(`[!] Failed to save people.json: ${t.message}`),console.error(` Path: ${S.resolve(te)}`)}}import Wt from"puppeteer";import{addExtra as Yt}from"puppeteer-extra";import Vt from"puppeteer-extra-plugin-stealth";import ne from"fs";import Mt from"path";var Ut={headless:!1,defaultViewport:null,protocolTimeout:3e5},J=new Set,je=!1;async function K(){let e=[...J].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});J.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function qt(){if(je)return;je=!0;let e=t=>async()=>{await K(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await K(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await K(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await K(),process.exit(0))}),process.on("exit",()=>{for(let t of J)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function oe(e){return Mt.join(e,".ilml-browser-session.json")}function Pe(e,t={}){try{ne.writeFileSync(oe(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Bt(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Pe(e,n?{wsEndpoint:n}:{})}catch{}}function Jt(e){let t=Me(e);t&&t.ownerPid===process.pid&&B(e)}function B(e){try{ne.rmSync(oe(e),{force:!0})}catch{}}function Me(e){try{return JSON.parse(ne.readFileSync(oe(e),"utf-8"))}catch{return null}}function Ne(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Fe(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Le(e,t,{probeTimeoutMs:n=4e3}={}){let o=Me(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ne(o.ownerPid)?"live":(B(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Fe(s,n,r);if(i===r)return s.then(c=>{if(c)try{c.disconnect()}catch{}}),"live";if(!i)return B(t),"free";if(Ne(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Fe(i.close().then(()=>!0).catch(()=>!1),n,!1))return B(t),"free";try{i.disconnect()}catch{}return"live"}function Ht(e,t){e&&(qt(),J.add(e),e.on("disconnected",()=>{J.delete(e),t&&B(t)}))}async function Ue(e,t={}){let n=be(),o={...Ut,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Le(e,n)==="live")throw new Error(r);Pe(n);let s;try{s=await e.launch(o)}catch{if(await Le(e,n)==="live")throw new Error(r);Ce(n);try{s=await e.launch(o)}catch(l){throw Jt(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${l.message})`)}}return Ht(s,n),Bt(n,s),{browser:s,profileDir:n,needsSeed:ke(n)}}async function qe(e,t){if(!t||!t.needsSeed)return!1;if(!Se())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...ye()),Ae(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Be=Yt(Wt);Be.use(Vt());async function Je(){let{browser:e,profileDir:t,needsSeed:n}=await Ue(Be),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await qe(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}import"dotenv/config";import*as C from"fs";import*as O from"path";import{fileURLToPath as Zt}from"url";import"dotenv/config";import{createGraphClient as Gt,resolveToken as Kt}from"@ilivemylife/graph-sdk";import{config as zt}from"dotenv";zt();var He=Kt()||process.env.TOKEN;He||(console.error(`
|
|
4
4
|
[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.
|
|
5
5
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
6
6
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
7
|
-
`),process.exit(1));var
|
|
7
|
+
`),process.exit(1));var We=Gt({token:He});function Qt(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),o=t%60;return o?`${n}m ${o}s`:`${n}m`}function Xt({scriptName:e,mode:t,status:n,error:o,duration:r}){let s=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),l=r?` ${Qt(r)}`:"",c=n==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${s} ${e}${a} \u2014 ${c} \u2014 ${i}${l}`}async function Ye({scriptName:e,mode:t,status:n,summaryLines:o,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let c=`**${Xt({scriptName:e,mode:t,status:n,error:r,duration:s})}**
|
|
8
8
|
|
|
9
9
|
${o.join(`
|
|
10
|
-
`)}`;try{await Be.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Kt=Gt(import.meta.url),zt=O.dirname(O.dirname(Kt)),re=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"collected-profiles"):O.join(zt,"collected-profiles"),se=O.join(re,"run-log.json");function Qt(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";C.writeFileSync(o,n);for(let r=0;r<3;r++)try{C.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function He(){try{if(!C.existsSync(se))return{runs:[]};let e=JSON.parse(C.readFileSync(se,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function We(e){C.existsSync(re)||C.mkdirSync(re,{recursive:!0});try{Qt(se,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ve(e,t="default"){let n=He();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),We(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ie(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=He(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=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=n,c.error=o,r=c.duration)}We(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Je({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as p from"fs";import*as me from"os";import*as h from"path";import{fileURLToPath as Tn}from"url";var ae={};W(ae,{NAME:()=>Zt,VERSION:()=>Xt,up:()=>nn});import*as $ from"fs";import*as z from"path";var Xt=1,Zt="normalize-jobs-and-questions",en=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],tn=50;function ce(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function le(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{$.writeFileSync(o,n)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,e)}catch(r){try{$.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function nn(e,t){let n=z.join(e,"jobs.json"),o=z.join(t,"scouted-jobs.json"),r=z.join(e,"application-questions.json"),s=ce(n)||{},i=ce(o)||{},l=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let u=i[f],m=s[f];for(let g of en)u[g]!=null&&m[g]==null&&(m[g]=u[g]);c.push(f),l++}l>0?(le(n,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=ce(r);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 k=(m.questions||[]).map(d=>{let w={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=tn?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||k.length,questions:k})}le(r,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];le(o,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 ue={};W(ue,{NAME:()=>rn,VERSION:()=>on,up:()=>ln});import*as E from"fs";import*as Ye from"path";var on=2,rn="reset-unread-flags";function sn(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function cn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{E.writeFileSync(o,n)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function ln(e){let t=Ye.join(e,"conversations.json"),n=sn(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}cn(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var fe={};W(fe,{NAME:()=>un,VERSION:()=>an,up:()=>hn});import*as x from"fs";import*as Ge from"path";var an=3,un="recompute-last-message-by",fn=new Set(["draft","confirmed","rejected","needs_review"]);function pn(e){return x.existsSync(e)?JSON.parse(x.readFileSync(e,"utf-8")):null}function dn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{x.writeFileSync(o,n)}catch(r){try{x.unlinkSync(o)}catch{}throw r}try{x.renameSync(o,e)}catch(r){try{x.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function mn(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!fn.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function hn(e){let t=Ge.join(e,"conversations.json"),n=pn(t);if(!n){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 r=0,s=0,i=0;for(let l of Object.keys(n)){let c=n[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let a=Array.isArray(c.messages)?c.messages:[],f=mn(a,o),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,r++}if(r===0){console.log(" No conversations to recompute.");return}dn(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var pe={};W(pe,{NAME:()=>yn,VERSION:()=>gn,up:()=>vn});import*as I from"fs";import*as Ke from"path";var gn=4,yn="split-connection-timestamps",Sn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function wn(e){if(!I.existsSync(e))return null;let t=I.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function bn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{I.writeFileSync(o,n)}catch(r){try{I.unlinkSync(o)}catch{}throw r}try{I.renameSync(o,e)}catch(r){try{I.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function vn(e){let t=Ke.join(e,"people.json"),n=wn(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,Sn.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}bn(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as A from"path";import{fileURLToPath as kn}from"url";var An=kn(import.meta.url),Cn=A.dirname(A.dirname(An)),H=process.env.DATA_DIR?A.resolve(process.env.DATA_DIR,"market-research"):A.join(Cn,"market-research"),tr=A.join(H,"scouted-jobs.json"),nr=A.join(H,"discovered-people.json"),or=A.join(H,"visit-log.json"),rr=A.join(H,"companies.json"),sr=A.join(H,"job-decisions.json");function ze(){$n=null,En=null,xn=null,In=null,_n=null}var $n=null;var En=null;var xn=null;var In=null;var _n=null;var Rn=Tn(import.meta.url),Dn=h.dirname(Rn),On=h.dirname(h.dirname(Dn));function jn(e){return e&&(e==="~"?me.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(me.homedir(),e.slice(2)):e)}var _=process.env.DATA_DIR?h.resolve(jn(process.env.DATA_DIR)):On,L=h.join(_,"collected-profiles"),P=h.join(_,"market-research"),v=h.join(_,".schema-version"),Qe=[h.join(L,".schema-version"),h.join(P,".schema-version")],j=4,D=[{version:1,module:ae},{version:2,module:ue},{version:3,module:fe},{version:4,module:pe}];(function(){D.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of D){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 r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=D.length?D[D.length-1].version:0;if(n!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<D.length;o++){let r=o+1;if(D[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${D[o].version}`)}})();function tt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
10
|
+
`)}`;try{await We.addMessage(i,c)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var en=Zt(import.meta.url),tn=O.dirname(O.dirname(en)),re=process.env.DATA_DIR?O.resolve(process.env.DATA_DIR,"collected-profiles"):O.join(tn,"collected-profiles"),se=O.join(re,"run-log.json");function nn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";C.writeFileSync(o,n);for(let r=0;r<3;r++)try{C.renameSync(o,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function Ve(){try{if(!C.existsSync(se))return{runs:[]};let e=JSON.parse(C.readFileSync(se,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ge(e){C.existsSync(re)||C.mkdirSync(re,{recursive:!0});try{nn(se,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Ke(e,t="default"){let n=Ve();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let o=new Date,r={timestamp:o.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>s),Ge(n),{script:e,mode:t,startTime:o.getTime(),runIndex:n.runs.length-1}}function ie(e,t,n=null,o=null){if(!e)return;let r=null;try{let i=Ve(),l=i.runs[e.runIndex];if(l&&l.status==="running"&&l.script===e.script)l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=n,l.error=o,r=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=n,c.error=o,r=c.duration)}Ge(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=t==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Ye({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:o,duration:r??Date.now()-e.startTime}).catch(l=>console.error(`[runLog] postRunReport failed: ${l.message}`))}}import"dotenv/config";import*as p from"fs";import*as me from"os";import*as h from"path";import{fileURLToPath as Nn}from"url";var ae={};W(ae,{NAME:()=>rn,VERSION:()=>on,up:()=>ln});import*as E from"fs";import*as z from"path";var on=1,rn="normalize-jobs-and-questions",sn=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],cn=50;function ce(e){return E.existsSync(e)?JSON.parse(E.readFileSync(e,"utf-8")):null}function le(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{E.writeFileSync(o,n)}catch(r){try{E.unlinkSync(o)}catch{}throw r}try{E.renameSync(o,e)}catch(r){try{E.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function ln(e,t){let n=z.join(e,"jobs.json"),o=z.join(t,"scouted-jobs.json"),r=z.join(e,"application-questions.json"),s=ce(n)||{},i=ce(o)||{},l=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let u=i[f],m=s[f];for(let g of sn)u[g]!=null&&m[g]==null&&(m[g]=u[g]);c.push(f),l++}l>0?(le(n,s),console.log(` Phase 1: Merged ${l} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=ce(r);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 k=(m.questions||[]).map(d=>{let w={type:d.type||"input",question:d.question||"",answer:d.answer||""};return d.options&&(d.options.length<=cn?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||k.length,questions:k})}le(r,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];le(o,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 ue={};W(ue,{NAME:()=>un,VERSION:()=>an,up:()=>dn});import*as $ from"fs";import*as ze from"path";var an=2,un="reset-unread-flags";function fn(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function pn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{$.writeFileSync(o,n)}catch(r){try{$.unlinkSync(o)}catch{}throw r}try{$.renameSync(o,e)}catch(r){try{$.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function dn(e){let t=ze.join(e,"conversations.json"),n=fn(t);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let r of Object.keys(n))n[r].unread===!0&&(n[r].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}pn(t,n),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var fe={};W(fe,{NAME:()=>hn,VERSION:()=>mn,up:()=>bn});import*as _ from"fs";import*as Qe from"path";var mn=3,hn="recompute-last-message-by",gn=new Set(["draft","confirmed","rejected","needs_review"]);function yn(e){return _.existsSync(e)?JSON.parse(_.readFileSync(e,"utf-8")):null}function Sn(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{_.writeFileSync(o,n)}catch(r){try{_.unlinkSync(o)}catch{}throw r}try{_.renameSync(o,e)}catch(r){try{_.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function wn(e,t){if(!e||e.length===0)return"them";let n=e.filter(s=>!gn.has(s.status));if(n.length===0)return"them";let o=n.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=o.length>0?o:[...n].reverse();for(let s of r){let i=s.sender;if(i===t)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function bn(e){let t=Qe.join(e,"conversations.json"),n=yn(t);if(!n){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 r=0,s=0,i=0;for(let l of Object.keys(n)){let c=n[l];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let a=Array.isArray(c.messages)?c.messages:[],f=wn(a,o),u=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=u,r++}if(r===0){console.log(" No conversations to recompute.");return}Sn(t,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var pe={};W(pe,{NAME:()=>kn,VERSION:()=>vn,up:()=>$n});import*as x from"fs";import*as Xe from"path";var vn=4,kn="split-connection-timestamps",An=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Cn(e){if(!x.existsSync(e))return null;let t=x.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function En(e,t){let n=JSON.stringify(t,null,2),o=e+".tmp";try{x.writeFileSync(o,n)}catch(r){try{x.unlinkSync(o)}catch{}throw r}try{x.renameSync(o,e)}catch(r){try{x.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function $n(e){let t=Xe.join(e,"people.json"),n=Cn(t);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let o=0,r=0;for(let s of Object.keys(n)){let i=n[s];!i||typeof i!="object"||(r++,An.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,o++))}if(o===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}En(t,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${o} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}import"dotenv/config";import*as A from"path";import{fileURLToPath as _n}from"url";var xn=_n(import.meta.url),In=A.dirname(A.dirname(xn)),H=process.env.DATA_DIR?A.resolve(process.env.DATA_DIR,"market-research"):A.join(In,"market-research"),lr=A.join(H,"scouted-jobs.json"),ar=A.join(H,"discovered-people.json"),ur=A.join(H,"visit-log.json"),fr=A.join(H,"companies.json"),pr=A.join(H,"job-decisions.json");function Ze(){Rn=null,Tn=null,Dn=null,On=null,jn=null}var Rn=null;var Tn=null;var Dn=null;var On=null;var jn=null;var Fn=Nn(import.meta.url),Ln=h.dirname(Fn),Pn=h.dirname(h.dirname(Ln));function Mn(e){return e&&(e==="~"?me.homedir():e.startsWith("~/")||e.startsWith("~\\")?h.join(me.homedir(),e.slice(2)):e)}var I=process.env.DATA_DIR?h.resolve(Mn(process.env.DATA_DIR)):Pn,L=h.join(I,"collected-profiles"),P=h.join(I,"market-research"),v=h.join(I,".schema-version"),et=[h.join(L,".schema-version"),h.join(P,".schema-version")],j=4,D=[{version:1,module:ae},{version:2,module:ue},{version:3,module:fe},{version:4,module:pe}];(function(){D.sort((o,r)=>o.version-r.version);let t=new Set;for(let o of D){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 r=o.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=D.length?D[D.length-1].version:0;if(n!==j)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${j}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<D.length;o++){let r=o+1;if(D[o].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${o} but found v${D[o].version}`)}})();function rt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
11
11
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
12
|
-
`),process.exit(1));try{p.mkdirSync(
|
|
13
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
14
|
-
`),process.exit(1))}let e;try{e=p.statSync(
|
|
15
|
-
[FATAL] DATA_DIR (${
|
|
12
|
+
`),process.exit(1));try{p.mkdirSync(I,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
13
|
+
[FATAL] Cannot create DATA_DIR (${I}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
14
|
+
`),process.exit(1))}let e;try{e=p.statSync(I)}catch(t){console.error(`
|
|
15
|
+
[FATAL] DATA_DIR (${I}) is not accessible: ${t.message}
|
|
16
16
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
17
|
-
[FATAL] DATA_DIR (${
|
|
17
|
+
[FATAL] DATA_DIR (${I}) 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.
|
|
18
18
|
`),process.exit(1));for(let t of[L,P]){let n;try{n=p.lstatSync(t)}catch(o){if(o.code==="ENOENT")continue;throw o}n.isSymbolicLink()&&(console.error(`
|
|
19
19
|
[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.
|
|
20
|
-
`),process.exit(1))}}var F=h.join(
|
|
20
|
+
`),process.exit(1))}}var F=h.join(I,".migration-lock");function Un(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return p.writeFileSync(F,e,{flag:"wx"}),!0}catch(o){if(o.code!=="EEXIST")throw o}let t;try{t=JSON.parse(p.readFileSync(F,"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 r=24*60*60*1e3,s=1/0;if(t.startedAt){let i=Date.parse(t.startedAt);Number.isNaN(i)||(s=Date.now()-i)}o&&s<r&&(console.error(`
|
|
21
21
|
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${F}
|
|
22
22
|
`),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.
|
|
23
|
-
`),process.exit(1)),o&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=F+".tmp";try{return p.writeFileSync(n,e),p.renameSync(n,F),!0}catch(o){try{p.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function he(){try{if(JSON.parse(p.readFileSync(F,"utf-8")).pid!==process.pid)return;p.unlinkSync(F)}catch{}}var
|
|
23
|
+
`),process.exit(1)),o&&s>=r&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let n=F+".tmp";try{return p.writeFileSync(n,e),p.renameSync(n,F),!0}catch(o){try{p.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${o.message}`)}}function he(){try{if(JSON.parse(p.readFileSync(F,"utf-8")).pid!==process.pid)return;p.unlinkSync(F)}catch{}}var tt=!1;function qn(){if(tt)return;tt=!0;let e=()=>{try{he()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function Bn(){if(p.existsSync(v))return;let e=[],t=[];for(let s of et)if(p.existsSync(s))try{e.push({file:s,schema:Q(s)})}catch(i){t.push({file:s,err:i.message})}if(t.length>0){console.error(`
|
|
24
24
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of t)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
25
25
|
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.
|
|
26
26
|
`),process.exit(1)}if(e.length===0)return;let n=e.map(s=>s.schema.version);if(new Set(n).size>1){console.error(`
|
|
27
27
|
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.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.
|
|
28
|
-
`),process.exit(1)}let o=e[0].schema,r=v+".tmp";try{p.writeFileSync(r,JSON.stringify(o,null,2)),p.renameSync(r,v)}catch(s){try{p.unlinkSync(r)}catch{}throw s}for(let s of
|
|
28
|
+
`),process.exit(1)}let o=e[0].schema,r=v+".tmp";try{p.writeFileSync(r,JSON.stringify(o,null,2)),p.renameSync(r,v)}catch(s){try{p.unlinkSync(r)}catch{}throw s}for(let s of et)if(p.existsSync(s))try{p.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${v}`)}function Jn(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 Q(e){let t=p.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function nt(){if(Bn(),!p.existsSync(v))return{version:0,migrations:[]};let e;try{e=Q(v)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
29
29
|
[FATAL] ${v} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
30
|
-
`),process.exit(1)}let t=
|
|
30
|
+
`),process.exit(1)}let t=Jn(e);return t===null&&(console.error(`
|
|
31
31
|
[FATAL] ${v} 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.
|
|
32
|
-
`),process.exit(1)),t}function
|
|
32
|
+
`),process.exit(1)),t}function st(e){try{p.chmodSync(e,384)}catch{}}function Hn(e){if(rt(),p.existsSync(v))try{if(p.lstatSync(v).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${v}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let t=v+".tmp";try{p.writeFileSync(t,JSON.stringify(e,null,2)),st(t),p.renameSync(t,v)}catch(n){try{p.unlinkSync(t)}catch{}throw n}}function ot(e,t){if(!p.existsSync(e))return;let n=`.pre-v${String(t).padStart(3,"0")}.backup`,o=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}}),r=0,s=0,i=[];for(let l of o){let c=h.join(e,l),a=h.join(e,l+n);if(p.existsSync(a)){s++;continue}try{ct(c,a),r++}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(r>0||s>0){let l=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${h.basename(e)}/ (${n})${l}`)}}var de=!1;async function it(){if(de)return;rt(),Kn();let t=nt().version;if(t===j){de=!0;return}qn(),Un(),process.on("exit",he),t>j&&(console.error(`
|
|
33
33
|
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${j}.`),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.
|
|
34
34
|
`),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${j}.
|
|
35
35
|
`),process.exit(1)),console.log(`
|
|
36
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${j}`);let n=
|
|
36
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${j}`);let n=zn();if(!n.ok){console.error(`
|
|
37
37
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of n.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
38
38
|
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'.
|
|
39
39
|
`),process.exit(1)}let o=D.filter(r=>r.version>t);for(let r of o){console.log(`
|
|
40
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{
|
|
40
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{ot(L,r.version),ot(P,r.version)}catch(c){console.error(`
|
|
41
41
|
[FATAL] Pre-migration backup failed for ${s}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
42
42
|
`),process.exit(1)}let l=r.module;try{await l.up(L,P)}catch(c){console.error(`
|
|
43
|
-
[FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=
|
|
43
|
+
[FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let a=Qn(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.
|
|
44
44
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
45
45
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
46
|
-
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:r.version,name:l.NAME||s,appliedAt:c},f=
|
|
46
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),a={version:r.version,name:l.NAME||s,appliedAt:c},f=nt();f.version=r.version,f.migratedAt=c,f.migrations=f.migrations||[],f.migrations.push(a),Hn(f)}catch(c){console.error(`
|
|
47
47
|
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
48
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{
|
|
48
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{Te()}catch{}try{Ze()}catch{}de=!0,he(),console.log(`
|
|
49
49
|
\u2713 Schema is now at v${j}
|
|
50
|
-
`)}var
|
|
50
|
+
`)}var Wn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Yn(e){let t=e.toLowerCase();return Wn.some(n=>n.test(t))}var Vn=6e4;function Gn(){let e=Date.now(),t=[];for(let n of[I,L,P]){if(!p.existsSync(n))continue;let o;try{o=p.readdirSync(n)}catch{continue}for(let r of o){if(!Yn(r))continue;let s=h.join(n,r);try{let i=p.statSync(s);if(!i.isFile()||e-i.mtimeMs<Vn)continue;t.push({dir:n,file:r,fullPath:s})}catch{}}}return t}function Kn({verbose:e=!1}={}){let t=Gn();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let o of t)try{p.unlinkSync(o.fullPath),n++,e&&console.log(` Removed orphan: ${h.basename(o.dir)}/${o.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${r.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function zn(){let e=[];for(let t of[L,P]){if(!p.existsSync(t))continue;let n=p.readdirSync(t).filter(o=>{let r=o.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let o of n){let r=h.join(t,o);try{Q(r)}catch(s){e.push({dir:h.basename(t),file:o,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Qn(e){let t=[],n=[];for(let s of[L,P]){if(!p.existsSync(s))continue;let i=p.readdirSync(s).filter(l=>l.endsWith(e));for(let l of i){let c=h.join(s,l),a=l.slice(0,-e.length),f=h.join(s,a);try{a.toLowerCase().endsWith(".json")?Q(c):p.accessSync(c,p.constants.R_OK),t.push({backupPath:c,originalPath:f,fileName:l,dir:s})}catch(u){n.push(`${h.basename(s)}/${l}: ${u.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let o=0,r=[];for(let{backupPath:s,originalPath:i,fileName:l,dir:c}of t)try{ct(s,i),o++}catch(a){r.push(`${h.basename(c)}/${l}: ${a.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:o}:{ok:!0,restored:o}}function ct(e,t){let n=t+".tmp";try{p.copyFileSync(e,n),st(n)}catch(o){try{p.unlinkSync(n)}catch{}throw o}try{p.renameSync(n,t)}catch(o){try{p.unlinkSync(n)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let r=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 r.code=o.code,r}throw o}}function Zn(){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 eo(){let e=q(),t=Object.values(e),n=t.length,o={};for(let s of t){let i=s.connectionStatus||"(none)";o[i]=(o[i]||0)+1}let r={};for(let s of t){for(let i of s.sources||[])r[i]=(r[i]||0)+1;(!s.sources||s.sources.length===0)&&(r["(no source)"]=(r["(no source)"]||0)+1)}console.log(`
|
|
51
51
|
=== People Database: ${n} entries ===
|
|
52
52
|
`),console.log("By connection status:");for(let[s,i]of Object.entries(o).sort((l,c)=>c[1]-l[1]))console.log(` ${s.padEnd(30)} ${i}`);console.log(`
|
|
53
|
-
By source:`);for(let[s,i]of Object.entries(r).sort((l,c)=>c[1]-l[1]))console.log(` ${s.padEnd(30)} ${i}`);console.log()}async function
|
|
53
|
+
By source:`);for(let[s,i]of Object.entries(r).sort((l,c)=>c[1]-l[1]))console.log(` ${s.padEnd(30)} ${i}`);console.log()}async function to(e){let t="https://www.linkedin.com/mynetwork/invite-connect/connections/";console.log(`Navigating to ${t}`),await ee(e,t,{readySelector:'main a[href*="/in/"]',label:"connections"})||console.warn("\u26A0 No connection cards found after 45s. Page may have changed layout.");let o=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 o&&console.log(` LinkedIn reports: ${o.toLocaleString()} connections`),o}async function at(e){return e.evaluate(()=>{let n=(document.querySelector("main")||document.body).querySelectorAll('a[href*="/in/"]'),o={};for(let i of n){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}o[c]||(o[c]=[]),o[c].push(i)}let r=[],s=i=>((i&&(i.innerText||i.textContent)||"").trim().split(`
|
|
54
54
|
`)[0]||"").trim();for(let[i,l]of Object.entries(o)){let c=null;for(let d of l){let w=s(d);!w||d.querySelector("img")||(!c||w.length<s(c).length)&&(c=d)}let a=s(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(`
|
|
55
|
-
`).map(d=>d.trim()).filter(Boolean),m=null,g=null,k=u.indexOf(a);if(k>=0&&k+1<u.length){let d=u[k+1];!d.startsWith("Connected on")&&d!=="Message"&&(m=d)}for(let d of u)if(d.startsWith("Connected on")){g=d;break}r.push({profileUrl:i,name:a,title:m,time:g})}return r})}async function
|
|
55
|
+
`).map(d=>d.trim()).filter(Boolean),m=null,g=null,k=u.indexOf(a);if(k>=0&&k+1<u.length){let d=u[k+1];!d.startsWith("Connected on")&&d!=="Message"&&(m=d)}for(let d of u)if(d.startsWith("Connected on")){g=d;break}r.push({profileUrl:i,name:a,title:m,time:g})}return r})}async function ut(e){return e.evaluate(()=>{let t=document.querySelector("main")||document.body,n=null,o=[t,...t.querySelectorAll("div, section")];for(let s of o){let i=getComputedStyle(s);if((i.overflowY==="auto"||i.overflowY==="scroll")&&s.scrollHeight>s.clientHeight+10){n=s;break}}n&&n.scrollBy(0,800),window.scrollBy(0,800);let r=document.querySelectorAll("button");for(let s of r){let i=s.textContent?.trim().toLowerCase()||"";if((i.includes("load more")||i.includes("show more"))&&s.getBoundingClientRect().height>0)return s.click(),"clicked"}return n?"scrolled":"window-scroll"})}async function no(e,t){let{max:n,verbose:o,dryRun:r}=t,s=new Map,i=0,l=0,c=3,a=10;for(;;){i++;let f=await at(e),u=0;for(let g of f)g.profileUrl&&(s.has(g.profileUrl)||(s.set(g.profileUrl,g),u++));if(o?console.log(` Round #${i}: ${u} new | Total: ${s.size}`):process.stdout.write(`\r Connections found: ${s.size} (page #${i})`),!r&&i%a===0&&(dt(Array.from(s.values()),!1),o&&console.log(` \u{1F4BE} Saved progress (${s.size} connections)`)),s.size>=n){console.log(`
|
|
56
56
|
Reached --max=${n}, 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 m=await
|
|
58
|
-
`),Array.from(s.values())}async function
|
|
57
|
+
${c} rounds with no new cards \u2014 end of list.`);break}}else l=0;let m=await ut(e);o&&m==="clicked"&&console.log(' \u2192 Clicked "Load more"'),await V(2e3)}return o||process.stdout.write(`
|
|
58
|
+
`),Array.from(s.values())}async function oo(e,t){let{max:n,verbose:o}=t,r=q(),s=new Set;for(let[f,u]of Object.entries(r))u.connectionStatus==="connected"&&u.sources?.includes("sync-connections")&&s.add(f);console.log(` Known synced connections in DB: ${s.size}`);let i=new Map,l=0,c=0,a=3;for(;;){l++;let f=await at(e),u=0,m=0;for(let d of f)d.profileUrl&&(i.has(d.profileUrl)||(i.set(d.profileUrl,d),s.has(d.profileUrl)?m++:u++));let g=Array.from(i.values()).filter(d=>!s.has(d.profileUrl)).length;if(o?console.log(` Round #${l}: ${u} new, ${m} known | New total: ${g}`):process.stdout.write(`\r New connections: ${g} (page #${l})`),g>=n){console.log(`
|
|
59
59
|
Reached --max=${n}, stopping.`);break}if(u===0&&m>0){if(c++,c>=a){console.log(`
|
|
60
60
|
${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 k=await
|
|
62
|
-
`),Array.from(i.values())}var
|
|
61
|
+
${a} empty rounds \u2014 end of list.`);break}let k=await ut(e);o&&k==="clicked"&&console.log(' \u2192 Clicked "Load more"'),await V(2e3)}return o||process.stdout.write(`
|
|
62
|
+
`),Array.from(i.values())}var ft=new Set(["pending","sent_with_note","sent_without_note","sent_without_note_upsell"]);function lt(e){return typeof e=="string"?e.replace(/\s+/g," ").trim().toLowerCase():""}function pt(e){let t=new Map;for(let[n,o]of Object.entries(e)){let r=G(o.profileUrl||n);r&&!t.has(r)&&t.set(r,n)}for(let[n,o]of Object.entries(e))for(let r of o.aliases||[])r&&!t.has(r)&&t.set(r,n);return t}function ro(e,t){let n=[],o=pt(t);for(let r of e){if(!r.profileUrl)continue;let s=o.get(G(r.profileUrl)),i=s?t[s]:void 0;i&&ft.has(i.connectionStatus)&&n.push({...r,previousStatus:i.connectionStatus})}return n}function dt(e,t){let n=q(),o=new Date().toISOString(),r=o.slice(0,10),s={newPeople:0,updatedToConnected:0,alreadyConnected:0,flaggedDuplicates:0,flagged:[]},i=pt(n),l=new Map;for(let[c,a]of Object.entries(n)){if(!ft.has(a.connectionStatus))continue;let f=lt(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=G(c.profileUrl),f=a?i.get(a):null,u=f?n[f]:void 0;if(u){if(u.connectionStatus!=="connected"){u.connectionStatus="connected";let m=c.time?Y(c.time.replace(/^Connected\s+on\s+/i,"")):null;u.connectedAt=m||o,u.connectionDate=(m||o).slice(0,10),u.lastUpdated=o,s.updatedToConnected++}else if(s.alreadyConnected++,c.time&&(!u.connectedAt||!u.connectionDate)){let m=Y(c.time.replace(/^Connected\s+on\s+/i,""));m&&(u.connectedAt||(u.connectedAt=m),u.connectionDate||(u.connectionDate=m.slice(0,10)),u.lastUpdated=o)}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=r,u.seenCount=(u.seenCount||1)+1,u.lastUpdated=o}else{let m={name:c.name,title:c.title,location:null,company:null,connectionDegree:"1st",connectionsCount:null,mutualConnections:null,photoUrl:null,hasVerifiedBadge:!1,firstSeen:r,lastSeen:r,seenCount:1,sources:["sync-connections"],connectionStatus:"connected",connectionDate:r,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:o},g=lt(c.name),k=g?l.get(g)||[]:[];k.length&&(m.possibleDuplicateOf=[...k],s.flaggedDuplicates++,s.flagged.push({name:c.name,candidates:k.length})),n[c.profileUrl]=m,a&&i.set(a,c.profileUrl),s.newPeople++}}return t||Oe(n),s}function so(e,t,n,o,r,s){if(console.log(`
|
|
63
63
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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 (${s})`),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"),r&&console.log(` LinkedIn header: ${r.toLocaleString()}`),console.log(` Connections scraped: ${e.length}`),console.log(` New people added: ${n.newPeople}`),console.log(` Updated to connected: ${n.updatedToConnected}`),console.log(` Already connected: ${n.alreadyConnected}`),t.length>0){console.log(`
|
|
64
64
|
Newly accepted (${t.length}):`);for(let i of t)console.log(` \u2713 ${i.name||"Unknown"} (was: ${i.previousStatus})`)}if(n.flaggedDuplicates>0){console.log(`
|
|
65
65
|
\u26A0 Possible duplicates (${n.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 n.flagged||[])console.log(` ? ${i.name||"Unknown"}${i.candidates>1?` (${i.candidates} candidates)`:""}`)}o&&console.log(`
|
|
66
66
|
[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
|
|
67
|
-
`)}async function
|
|
67
|
+
`)}async function io(){let e=Zn();if(await it(),e.list){eo();return}let t=e.full?"full":"incremental",n=Ke("sync",t);console.log(`
|
|
68
68
|
\u{1F504} Sync LinkedIn Connections (${t})
|
|
69
|
-
`),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let{browser:o,page:r}=await
|
|
70
|
-
Extracted ${i.length} connections.`);let l=q(),c=
|
|
71
|
-
\u2717 Error:`,s.message),e.verbose&&console.error(s.stack),ie(n,"error",null,s.message)}finally{await o.close().catch(()=>{})}}process.argv[1]&&import.meta.url===
|
|
69
|
+
`),e.dryRun&&console.log(" [DRY RUN mode]"),e.max!==1/0&&console.log(` Max: ${e.max}`);let{browser:o,page:r}=await Je();try{let s=await to(r),i=e.full?await no(r,{max:e.max,verbose:e.verbose,dryRun:e.dryRun}):await oo(r,{max:e.max,verbose:e.verbose});console.log(`
|
|
70
|
+
Extracted ${i.length} connections.`);let l=q(),c=ro(i,l),a=dt(i,e.dryRun);so(i,c,a,e.dryRun,s,t),ie(n,"success",{scraped:i.length,newPeople:a.newPeople,updatedToConnected:a.updatedToConnected})}catch(s){console.error(`
|
|
71
|
+
\u2717 Error:`,s.message),e.verbose&&console.error(s.stack),ie(n,"error",null,s.message)}finally{await o.close().catch(()=>{})}}process.argv[1]&&import.meta.url===Xn(process.argv[1]).href&&io();export{pt as buildSlugIndex,ro as detectNewlyAccepted,lt as normName,dt as syncToDatabaseBatch};
|
package/dist/verifyAbout.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ut=Object.defineProperty;var B=(e,t)=>()=>(e&&(t=e(e=0)),t);var dt=(e,t)=>{for(var n in t)ut(e,n,{get:t[n],enumerable:!0})};import _ from"fs";import $ from"path";function re(){let e=process.env.ILML_SCOPE_DIR;return e?$.join(e,"plugins-state","linkedin","cookies.json"):ft}function mt(){let e=re(),t=$.dirname(e);return t&&t!=="."&&!_.existsSync(t)&&_.mkdirSync(t,{recursive:!0}),e}function _e(e){let t=mt();return _.writeFileSync(t,JSON.stringify(e)),t}function Ee(){let e=re();if(!_.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=_.readFileSync(e,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${e}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}function Ae(){return _.existsSync(re())}function pt(){let e=process.env.ILML_SCOPE_DIR;return e?$.join(e,"plugins-state","linkedin"):"."}function Ie(e){let t=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(t)?t:"default"}function ht(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?Ie(t[1]):"default"}function $e(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return _.existsSync(t)||_.mkdirSync(t,{recursive:!0}),$.resolve(t);let n=Ie(e||ht()),o=$.join(pt(),"chrome-profile",n);return _.existsSync(o)||_.mkdirSync(o,{recursive:!0}),$.resolve(o)}function Te(e){return!_.existsSync($.join(e,De))}function Re(e){try{_.writeFileSync($.join(e,De),new Date().toISOString())}catch{}}function Pe(e){let t=0;for(let n of["SingletonLock","SingletonCookie","SingletonSocket"])try{_.rmSync($.join(e,n),{force:!0}),t++}catch{}return t}var ft,De,X=B(()=>{ft="cookies.json";De=".ilml-seeded"});async function p(e){let t=Math.floor(Math.random()*2001),n=e+t;return new Promise(o=>setTimeout(o,n))}async function wt(e,t,{timeout:n=45e3,poll:o=1e3,label:r="page"}={}){let s=Date.now();for(;Date.now()-s<n;){try{if(await e.evaluate(l=>!!document.querySelector(l),t)){let l=Date.now()-s;return l>6e3&&console.log(` (waited ${Math.round(l/1e3)}s for LinkedIn to finish loading ${r})`),!0}}catch{}await new Promise(i=>setTimeout(i,o))}return!1}function gt(e){return Me.test(e||"")}async function yt(e,{credentialWaitMs:t=36e4,label:n="page"}={}){console.log(` \u26A0 Auth wall on ${n} \u2014 attempting self-recovery (cookies may just need a refresh)...`);try{await e.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4})}catch{}let o=!!(process.stdin&&process.stdin.isTTY),r=o?t:Math.min(t,45e3),s=Date.now(),i=!1;for(;Date.now()-s<r;){let y="wait";try{y=await e.evaluate(m=>!new RegExp(m).test(location.href)&&document.querySelector("#global-nav, nav.global-nav")?"in":document.querySelector('input#username, input[name="session_key"], input#password')?"creds":"wait",Me.source)}catch{}if(y==="in"){try{let m=await e.cookies();if(Array.isArray(m)&&m.some(b=>b.name==="li_at")){let b=_e(m);console.log(` \u2713 Session recovered \u2014 re-saved ${m.length} cookies (${b}).`)}else console.log(" \u2713 Session recovered (kept existing cookie snapshot \u2014 refreshed set had no li_at).")}catch(m){console.log(` \u2713 Session recovered (cookie re-save skipped: ${m.message}).`)}return!0}if(y==="creds"){if(!o){let m=new Error(`Session expired (${n}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw m.code="SESSION_EXPIRED",m}i||(i=!0,console.log(`
|
|
2
2
|
\u26A0 LinkedIn is asking for your login + password (cookies not enough this time).`),console.log(" \u2192 Sign in MANUALLY in the browser window that is already open."),console.log(` I will wait and resume automatically \u2014 do NOT close the window or re-run the command.
|
|
3
|
-
`))}await new Promise(m=>setTimeout(m,2500))}let
|
|
3
|
+
`))}await new Promise(m=>setTimeout(m,2500))}let l=new Error(`Session expired (${n}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw l.code="SESSION_EXPIRED",l}async function Le(e,{readySelector:t,label:n="page",timeout:o=45e3}={}){let r=await wt(e,t,{timeout:o,label:n});if(!r&>(e.url())){let s=new Error(`Session expired (${n}) \u2014 redirected to login. Run: ilml linkedin login`);throw s.code="SESSION_EXPIRED",s}return r}async function H(e,t,{readySelector:n,label:o="page",timeout:r=45e3,gotoTimeout:s=6e4,autoRecover:i=!0}={}){await e.goto(t,{waitUntil:"domcontentloaded",timeout:s});try{return await Le(e,{readySelector:n,label:o,timeout:r})}catch(l){if(i&&l.code==="SESSION_EXPIRED"){await yt(e,{label:o});try{await e.goto(t,{waitUntil:"domcontentloaded",timeout:s})}catch{}return await Le(e,{readySelector:n,label:o,timeout:r})}throw l}}async function qe(e){return await e.evaluate(()=>{let t=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of t){let r=o.innerText||"",s=r.includes("Premium")||r.includes("premium")||r.includes("Upgrade")||r.includes("upgrade"),i=r.includes("Try for")||r.includes("free trial")||r.includes("/month")||r.includes("per month")||r.includes("Start my")||r.includes("Subscribe"),l=r.includes("Get hired faster")||r.includes("Get hired 2x");if(s||i||l){let y=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(y)return y.click(),{dismissed:!0,matched:r.substring(0,80)};let m=o.querySelectorAll("button");for(let u of m){let b=u.innerText?.trim().toLowerCase()||"",w=u.getAttribute("aria-label")?.toLowerCase()||"";if(b==="not now"||b==="no thanks"||b==="dismiss"||w.includes("dismiss"))return u.click(),{dismissed:!0,matched:r.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var Me,V=B(()=>{X();Me=/\/authwall|\/login|\/checkpoint|\/uas\/login/});function St(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function Oe(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let n=new URLSearchParams;n.set("keywords",t);let o=(e.JOB_SEARCH_LOCATION||"").trim();o&&n.set("location",o);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&n.set("geoId",r);let s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&n.set("distance",String(s)),Fe(e.JOB_SEARCH_EASY_APPLY)&&n.set("f_AL","true"),Fe(e.JOB_SEARCH_IN_NETWORK)&&n.set("f_JIYN","true");let i=St(e.JOB_SEARCH_COMPANY_IDS);i.length&&n.set("f_C",i.join(","));let l=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();l&&n.set("f_TPR",bt[l]||l),n.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let y="https://www.linkedin.com/jobs/search/?"+n.toString(),m=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return m&&(y+="&"+m),y}var bt,Fe,Ne=B(()=>{bt={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},Fe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim())});import{getPluginConfig as vt}from"@ilivemylife/graph-sdk";var Ct,je,kt,O,an,xt,ie=B(async()=>{Ne();Ct=await vt();for(let[e,t]of Object.entries(Ct))process.env[e]===void 0&&(process.env[e]=t);je=Oe(process.env);je&&(process.env.LINKEDIN_SEARCH_URL=je);kt=process.env.LINKEDIN_NAME,O=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),an=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.NEEDS_REVIEW])),xt=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.REJECTED,O.NEEDS_REVIEW]))});import"dotenv/config";import*as S from"fs";import*as C from"path";import{fileURLToPath as Lt}from"url";function Ot(){S.existsSync(D)||S.mkdirSync(D,{recursive:!0})}function Nt(e,t){if(!S.existsSync(e))return null;try{let n=JSON.parse(S.readFileSync(e,"utf-8"));try{S.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${t} is corrupted: ${n.message}`),console.error(` File: ${C.resolve(e)}`);let o=e+".backup";if(S.existsSync(o))try{let r=JSON.parse(S.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{S.copyFileSync(o,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{S.copyFileSync(e,e+".corrupted")}catch{}return null}}function le(){return ee||(Ot(),ee=Nt(Ft,"people.json")||{},ee)}var Mt,qt,D,Ft,In,$n,Dn,Tn,Rn,Pn,Qe,Ln,Mn,ee,ce=B(async()=>{await ie();Mt=Lt(import.meta.url),qt=C.dirname(C.dirname(Mt)),D=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"collected-profiles"):C.join(qt,"collected-profiles"),Ft=C.join(D,"people.json"),In=C.join(D,"jobs.json"),$n=C.join(D,"quota.json"),Dn=C.join(D,"conversations.json"),Tn=C.join(D,"sync-state.json"),Rn=C.join(D,"application-questions.json"),Pn=C.join(D,"profile-history"),Qe=(e,t)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:t},Ln=Qe(process.env.CONNECT_MAX_DAILY,20),Mn=Qe(process.env.CONNECT_MAX_WEEKLY,100),ee=null});var Xe={};dt(Xe,{extractCertificationsFromDetails:()=>Vt,extractEducationFromDetails:()=>Ht,extractExperienceFromDetails:()=>jt,extractFeaturedFromDetails:()=>Bt,extractRecommendationsFromDetails:()=>Jt,extractSkillsFromDetails:()=>Ut});async function jt(e,t){let n=t.replace(/\/+$/,"")+"/details/experience/";try{await H(e,n,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:"experience details"}),await p(1e3);let o=e.url();if(!o.toLowerCase().includes("/details/experience/"))throw new Error(`Section /details/experience/ not available on profile (landed on ${o})`);for(let s=0;s<5;s++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await p(900);await p(1e3);let r=0;for(;r<5&&await e.evaluate(()=>{for(let i of document.querySelectorAll("button"))if(/^Load more$/i.test((i.textContent||"").trim()))return i.click(),!0;return!1});)r++,await p(1500),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await p(700);return await e.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function i(u){let b=[];for(let w of u.querySelectorAll("div")){let g=Array.from(w.children).filter(A=>A.tagName==="DIV");if(g.length<3)continue;let v=g.filter(A=>(A.textContent||"").trim().length>50);v.length<3||(w.textContent||"").length<500||b.push({el:w,count:v.length,totalText:(w.textContent||"").length})}return b.sort((w,g)=>g.count-w.count||w.totalText-g.totalText),b[0]?.el}let l=i(s);if(!l)return[];let y=Array.from(l.children).filter(u=>u.tagName==="DIV").filter(u=>(u.textContent||"").trim().length>50);function m(u){let b=u[0]||null,w=null,g=null;if(u[1]){let f=u[1].split("\xB7").map(k=>k.trim());w=f[0]||null,f[1]&&(g=f[1])}let v=u.findIndex(f=>/(\d{4}|present)/i.test(f)&&/(-|–|—)/i.test(f)&&f.length<80),A=null,P=null;if(v>=0){let f=u[v].split("\xB7").map(k=>k.trim());A=f[0]||null,f[1]&&(P=f[1])}let L=null,M=-1;if(v>=0&&u[v+1]){let f=u[v+1],k=/^[>*\-•]|^>/.test(f),N=/https?:\/\//.test(f),j=/\d{4}/.test(f),x=/,/.test(f)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(f);!k&&!N&&!j&&f.length<100&&x&&(L=f,M=v+1)}let te=null,h=-1,q=u[u.length-1];if(q&&/and\s+\+\d+\s+skills?$/i.test(q)){h=u.length-1;let f=q.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);f&&(te={listed:f[1].split(",").map(k=>k.trim()),additional:parseInt(f[2],10)})}let F=new Set([0,1,v,M,h].filter(f=>f>=0)),T=u.filter((f,k)=>!F.has(k)),E=T.length>0?T.join(`
|
|
4
4
|
|
|
5
|
-
`):null;return{title:
|
|
6
|
-
`).map(g=>g.trim()).filter(g=>g&&g.length<5e3);return m(w)}).filter(
|
|
5
|
+
`):null;return{title:b,company:w,employmentType:g,dates:A,duration:P,location:L,description:E,skills:te,_raw:u}}return y.map(u=>{let w=(u.innerText||"").trim().split(`
|
|
6
|
+
`).map(g=>g.trim()).filter(g=>g&&g.length<5e3);return m(w)}).filter(u=>u.title)})}catch(o){if(o.code==="SESSION_EXPIRED"||/^session expired/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${t}: ${o.message?.slice(0,120)}`),[]}}async function Y(e,t,n){let o=t.replace(/\/+$/,"")+`/details/${n}/`;await H(e,o,{readySelector:"main .pvs-list, .scaffold-layout__main, main.scaffold-layout__main, section.artdeco-card",label:`details/${n}`}),await p(1e3);let r=e.url();if(!r.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${r})`);for(let i=0;i<4;i++)await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await p(700);await p(800);let s=0;for(;s<5&&await e.evaluate(()=>{for(let l of document.querySelectorAll("button"))if(/^Load more$/i.test((l.textContent||"").trim()))return l.click(),!0;return!1});)s++,await p(1300),await e.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await p(600)}async function G(e,t,n,o){try{return await o()}catch(r){let s=r.message||"";if(r.code==="SESSION_EXPIRED"||/^session expired/i.test(s))throw r;return/not available on profile/i.test(s)?(console.log(` (${t}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${e}: ${s.slice(0,120)}`),[])}}async function Bt(e,t){return G(t,"featured","extractFeaturedFromDetails",async()=>(await Y(e,t,"featured"),await e.evaluate(`(() => {
|
|
7
7
|
${K}
|
|
8
8
|
|
|
9
9
|
const main = document.querySelector('main');
|
|
@@ -44,7 +44,7 @@ var st=Object.defineProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var at=(e,t)=>{f
|
|
|
44
44
|
if (e.caption && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.caption.trim())) return false;
|
|
45
45
|
return true;
|
|
46
46
|
});
|
|
47
|
-
})()`)))}async function
|
|
47
|
+
})()`)))}async function Ht(e,t){return G(t,"education","extractEducationFromDetails",async()=>(await Y(e,t,"education"),await e.evaluate(`(() => {
|
|
48
48
|
${K}
|
|
49
49
|
|
|
50
50
|
const main = document.querySelector('main');
|
|
@@ -81,7 +81,7 @@ var st=Object.defineProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var at=(e,t)=>{f
|
|
|
81
81
|
if (e.degree && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.degree.trim())) return false;
|
|
82
82
|
return true;
|
|
83
83
|
});
|
|
84
|
-
})()`)))}async function
|
|
84
|
+
})()`)))}async function Ut(e,t){return G(t,"skills","extractSkillsFromDetails",async()=>(await Y(e,t,"skills"),await e.evaluate(`(() => {
|
|
85
85
|
${K}
|
|
86
86
|
|
|
87
87
|
const main = document.querySelector('main');
|
|
@@ -113,7 +113,7 @@ var st=Object.defineProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var at=(e,t)=>{f
|
|
|
113
113
|
skills.push({ name, endorsements, _raw: lines });
|
|
114
114
|
}
|
|
115
115
|
return skills;
|
|
116
|
-
})()`)))}async function
|
|
116
|
+
})()`)))}async function Vt(e,t){return G(t,"certifications","extractCertificationsFromDetails",async()=>(await Y(e,t,"certifications"),await e.evaluate(`(() => {
|
|
117
117
|
${K}
|
|
118
118
|
|
|
119
119
|
const main = document.querySelector('main');
|
|
@@ -138,7 +138,7 @@ var st=Object.defineProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var at=(e,t)=>{f
|
|
|
138
138
|
|
|
139
139
|
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
140
140
|
}).filter(e => e.name);
|
|
141
|
-
})()`)))}async function
|
|
141
|
+
})()`)))}async function Jt(e,t){return G(t,"recommendations","extractRecommendationsFromDetails",async()=>(await Y(e,t,"recommendations"),await e.evaluate(`(() => {
|
|
142
142
|
${K}
|
|
143
143
|
|
|
144
144
|
const main = document.querySelector('main');
|
|
@@ -174,7 +174,7 @@ var st=Object.defineProperty;var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var at=(e,t)=>{f
|
|
|
174
174
|
if (e.recommenderTitle && /^\xB7\\s*\\d+(?:st|nd|rd|th)\\+?$/i.test(e.recommenderTitle.trim())) return false;
|
|
175
175
|
return true;
|
|
176
176
|
});
|
|
177
|
-
})()`)))}var K,
|
|
177
|
+
})()`)))}var K,Ze=B(()=>{V();K=`
|
|
178
178
|
function findEntryContainer(root) {
|
|
179
179
|
const candidates = [];
|
|
180
180
|
for (const div of root.querySelectorAll('div')) {
|
|
@@ -237,9 +237,9 @@ function findEntryContainer(root) {
|
|
|
237
237
|
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
238
238
|
return candidates[0]?.el;
|
|
239
239
|
}
|
|
240
|
-
`});import _t from"puppeteer";import{addExtra as Et}from"puppeteer-extra";import At from"puppeteer-extra-plugin-stealth";V();await re();Z();Z();import se from"fs";import bt from"path";var St={headless:!1,defaultViewport:null,protocolTimeout:3e5},J=new Set,Fe=!1;async function X(){let e=[...J].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});J.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function vt(){if(Fe)return;Fe=!0;let e=t=>async()=>{await X(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await X(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await X(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await X(),process.exit(0))}),process.on("exit",()=>{for(let t of J)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function ae(e){return bt.join(e,".ilml-browser-session.json")}function Be(e,t={}){try{se.writeFileSync(ae(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function Ct(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Be(e,n?{wsEndpoint:n}:{})}catch{}}function kt(e){let t=He(e);t&&t.ownerPid===process.pid&&W(e)}function W(e){try{se.rmSync(ae(e),{force:!0})}catch{}}function He(e){try{return JSON.parse(se.readFileSync(ae(e),"utf-8"))}catch{return null}}function Ne(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Oe(e,t,n){let o,i=new Promise(r=>{o=setTimeout(()=>r(n),t)}),s=Promise.resolve(e).then(r=>(clearTimeout(o),r),r=>{throw clearTimeout(o),r});return Promise.race([s,i])}async function je(e,t,{probeTimeoutMs:n=4e3}={}){let o=He(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&Ne(o.ownerPid)?"live":(W(t),"free");let i=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),r=await Oe(s,n,i);if(r===i)return s.then(C=>{if(C)try{C.disconnect()}catch{}}),"live";if(!r)return W(t),"free";if(Ne(o.ownerPid)){try{r.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Oe(r.close().then(()=>!0).catch(()=>!1),n,!1))return W(t),"free";try{r.disconnect()}catch{}return"live"}function xt(e,t){e&&(vt(),J.add(e),e.on("disconnected",()=>{J.delete(e),t&&W(t)}))}async function Ue(e,t={}){let n=$e(),o={...St,...t,userDataDir:n},i=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await je(e,n)==="live")throw new Error(i);Be(n);let s;try{s=await e.launch(o)}catch{if(await je(e,n)==="live")throw new Error(i);Pe(n);try{s=await e.launch(o)}catch(u){throw kt(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${u.message})`)}}return xt(s,n),Ct(n,s),{browser:s,profileDir:n,needsSeed:Te(n)}}async function Ve(e,t){if(!t||!t.needsSeed)return!1;if(!Ae())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Ee()),Le(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var We=Et(_t);We.use(At());async function Je(){let{browser:e,profileDir:t,needsSeed:n}=await Ue(We),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ve(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}V();await ce();async function jt(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await p(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function ze(e,t,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:r=!1,extractRecommendations:u=!1,extractCertifications:C=!1}=n;try{await B(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await p(1500),await qe(e)&&(console.log(" Dismissed Premium overlay"),await p(1500),await jt(e,t));let c=0;for(let h=0;h<2;h++){let q=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(E=>window.scrollTo(0,E),q*T/6),await p(900);let F=await e.evaluate(()=>document.body.scrollHeight);if(F===c)break;c=F}await p(800);let y=null;try{let h=e.url();h&&/\/in\/[^/?#]/.test(h)&&(y=h.split("?")[0].replace(/\/+$/,""))}catch{}let w=await e.evaluate(()=>{let h=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),q=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),F=a=>{let l=(a||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(l)},T={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},E=document.querySelector("main");if(!E)return T;let f=[...Array.from(E.querySelectorAll("h1")),...Array.from(E.querySelectorAll("h2"))],k=Array.from(E.querySelectorAll("h2")),O=f.find(a=>{let l=a.textContent&&a.textContent.trim(),d=(l||"").replace(/\s*\(\d+\)$/,"").trim();return l&&l.length>1&&l.length<100&&!h.has(d)&&!q.has(d)}),j=O?O.textContent.trim():null,x=O?O.parentElement:null;for(;x&&x!==E&&!Array.from(x.children).filter(l=>l.tagName==="P").some(l=>{let d=l.textContent&&l.textContent.trim();return d&&d.length>5&&!F(d)});)x=x.parentElement;let de=null,fe=null,me=null,ne=null;if(x&&x!==E){let a=Array.from(x.children).filter(d=>d.tagName==="P").filter(d=>{let L=d.textContent&&d.textContent.trim();return L&&L.length>5&&!F(L)});if(a[0]&&(de=a[0].textContent.trim()),a[1]){let d=a[1].textContent.trim().split(/\s*[·•]\s*/);fe=d[0]||null,d.length>1&&(me=d.slice(1).join(" \xB7 "))}let l=Array.from(x.children).filter(d=>d.tagName==="DIV");for(let d=l.length-1;d>=0;d--){let L=l[d].textContent&&l[d].textContent.trim();if(L&&!(j&&L.startsWith(j))&&(ne=L.split(/[·•]/)[0].trim(),ne))break}}let pe=null;if(x){let a=x.querySelectorAll("p, span, div");for(let l of a){let d=(l.textContent||"").trim().replace(/^[·•]\s*/,"");if(d==="1st"||d==="2nd"||d==="3rd"){pe=d;break}}}let Xe=!!E.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),he=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),et=he&&he.src||null,z=E.textContent||"",we=null,ge=z.match(/(\d+\+?)\s+connections\b/i);ge&&(we=ge[1]+" connections");let Q=null,ye=z.match(/(\d+)\s+mutual connection/i),be=z.match(/and\s+(\d+)\s+other mutual/i),tt=z.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ye?Q=parseInt(ye[1],10):be?Q=2+parseInt(be[1],10):tt&&(Q=2);let Se=null,ve=null,Ce=k.find(a=>a.textContent&&a.textContent.trim()==="About");if(Ce){let a=Ce.parentElement;for(;a&&a.tagName!=="SECTION";)a=a.parentElement;if(a){let l=(a.textContent||"").trim();l=l.replace(/^About\s*/,"").trim();let d=l.match(/Top skills\s*(.+?)$/i);if(d){let oe=d[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(rt=>rt.trim()).filter(Boolean);oe.length>0&&oe.length<10&&(ve=oe)}l=l.split(/\n?…\s*more/i)[0].trim(),l=l.split(/\n?\.\.\.\s*more/i)[0].trim(),l=l.split(/\bTop skills\b/i)[0].trim(),l=l.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Se=l||null}}let ke=null,xe=k.find(a=>a.textContent&&a.textContent.trim()==="Activity");if(xe){let a=xe.parentElement;for(;a&&a.tagName!=="SECTION";)a=a.parentElement;if(a){let l=(a.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);l&&(ke=parseInt(l[1].replace(/,/g,""),10))}}let nt=[...new Set(k.map(a=>(a.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(a=>a&&a.length>1&&a.length<60&&a!==j).filter(a=>h.has(a)))],H=document.body.textContent||"",ot=/#OpenToWork\b/i.test(H)||/\bOpen to work\b/.test(H),it=/#Hiring\b/i.test(H)||/\bI'?m hiring\b/i.test(H)||/\bWe are hiring\b/i.test(H);return{name:j,title:de,location:ne,currentCompany:fe,currentSchool:me,connectionDegree:pe,hasVerifiedBadge:Xe,photoUrl:et,connectionsLevel:we,mutualConnectionsCount:Q,followers:ke,openToWork:ot,hiring:it,about:Se,topSkills:ve,availableSections:nt}});console.log(`Viewed: ${w.name} - ${w.title}`);let g=null,S=null,A=null,P=null,R=null,M=null;if(o||i||s||r||u||C){let h=await Promise.resolve().then(()=>(Ge(),Ke));o&&(g=await h.extractExperienceFromDetails(e,t),console.log(` + Experience: ${g.length} entries`)),i&&(S=await h.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${S.length} entries`)),s&&(A=await h.extractEducationFromDetails(e,t),console.log(` + Education: ${A.length} entries`)),r&&(P=await h.extractSkillsFromDetails(e,t),console.log(` + Skills: ${P.length} entries`)),u&&(R=await h.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${R.length} entries`)),C&&(M=await h.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${M.length} entries`))}return{...w,profileUrl:t,resolvedUrl:y,...g!==null&&{experience:g},...S!==null&&{featured:S},...A!==null&&{education:A},...P!==null&&{skillsFull:P},...R!==null&&{recommendations:R},...M!==null&&{certifications:M}}}catch(m){console.error(`Error viewing profile ${t}:`,m.message);try{await e.goto("about:blank",{timeout:1e4}),await p(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(m.message||""))throw m;return null}}await ce();V();var ue=process.argv.slice(2),Qe=ue.filter(e=>e.startsWith("http")),Ze=parseInt(ue.find(e=>e.startsWith("--pick="))?.split("=")[1]||"0"),Bt=ue.includes("--has-about");function Ht(e,t){return[...e].sort(()=>Math.random()-.5).slice(0,t)}function Ut(){if(Qe.length>0)return Qe.map(t=>({url:t,name:"(arg)"}));if(Ze>0){let t=le(),n=Object.entries(t).filter(([o])=>o.startsWith("http")).filter(([,o])=>Bt?!!(o.about&&o.about.trim()):!o.about);return Ht(n,Ze).map(([o,i])=>({url:o,name:i.name}))}let e=process.env.MY_LINKEDIN_URL;return e||(console.error("Pass a URL, use --pick=N, or set MY_LINKEDIN_URL in .env"),process.exit(1)),[{url:e,name:"(self)"}]}function I(e,t,n=80){if(t==null){console.log(` ${e.padEnd(20)} (null)`);return}let o=String(t),i=o.length>n?o.slice(0,n)+`\u2026 (+${o.length-n} chars)`:o;console.log(` ${e.padEnd(20)} ${i} [len=${o.length}]`)}async function Vt(){let e=Ut();console.log(`
|
|
240
|
+
`});import Tt from"puppeteer";import{addExtra as Rt}from"puppeteer-extra";import Pt from"puppeteer-extra-plugin-stealth";V();await ie();X();X();import se from"fs";import _t from"path";var Et={headless:!1,defaultViewport:null,protocolTimeout:3e5},W=new Set,Be=!1;async function Z(){let e=[...W].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});W.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function At(){if(Be)return;Be=!0;let e=t=>async()=>{await Z(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await Z(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await Z(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await Z(),process.exit(0))}),process.on("exit",()=>{for(let t of W)try{let n=t.process&&t.process();n&&n.kill("SIGKILL")}catch{}})}function ae(e){return _t.join(e,".ilml-browser-session.json")}function Je(e,t={}){try{se.writeFileSync(ae(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function It(e,t){try{let n=t.wsEndpoint&&t.wsEndpoint();Je(e,n?{wsEndpoint:n}:{})}catch{}}function $t(e){let t=We(e);t&&t.ownerPid===process.pid&&J(e)}function J(e){try{se.rmSync(ae(e),{force:!0})}catch{}}function We(e){try{return JSON.parse(se.readFileSync(ae(e),"utf-8"))}catch{return null}}function He(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function Ue(e,t,n){let o,r=new Promise(i=>{o=setTimeout(()=>i(n),t)}),s=Promise.resolve(e).then(i=>(clearTimeout(o),i),i=>{throw clearTimeout(o),i});return Promise.race([s,r])}async function Ve(e,t,{probeTimeoutMs:n=4e3}={}){let o=We(t);if(!o)return"free";if(!o.wsEndpoint)return o.ownerPid&&o.ownerPid!==process.pid&&He(o.ownerPid)?"live":(J(t),"free");let r=Symbol("timeout"),s=e.connect({browserWSEndpoint:o.wsEndpoint,defaultViewport:null}).catch(()=>null),i=await Ue(s,n,r);if(i===r)return s.then(y=>{if(y)try{y.disconnect()}catch{}}),"live";if(!i)return J(t),"free";if(He(o.ownerPid)){try{i.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await Ue(i.close().then(()=>!0).catch(()=>!1),n,!1))return J(t),"free";try{i.disconnect()}catch{}return"live"}function Dt(e,t){e&&(At(),W.add(e),e.on("disconnected",()=>{W.delete(e),t&&J(t)}))}async function Ye(e,t={}){let n=$e(),o={...Et,...t,userDataDir:n},r=`Could not open the LinkedIn automation Chrome profile at ${n}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await Ve(e,n)==="live")throw new Error(r);Je(n);let s;try{s=await e.launch(o)}catch{if(await Ve(e,n)==="live")throw new Error(r);Pe(n);try{s=await e.launch(o)}catch(l){throw $t(n),new Error(`Could not open the LinkedIn automation Chrome profile at ${n}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${l.message})`)}}return Dt(s,n),It(n,s),{browser:s,profileDir:n,needsSeed:Te(n)}}async function Ke(e,t){if(!t||!t.needsSeed)return!1;if(!Ae())return console.warn(" \u26A0 No saved LinkedIn session found. If this command comes back empty or redirects to login, run: ilml linkedin login"),!1;try{return await e.setCookie(...Ee()),Re(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var Ge=Rt(Tt);Ge.use(Pt());async function ze(){let{browser:e,profileDir:t,needsSeed:n}=await Ye(Ge),o=await e.newPage();return await o.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await Ke(o,{profileDir:t,needsSeed:n}),console.log(" Browser launched (persistent profile)."),{browser:e,page:o}}V();await ce();async function Wt(e,t){let n=e.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: ilml linkedin login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await p(3e3);let o=e.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function et(e,t,n={}){let{extractExperience:o=!1,extractFeatured:r=!1,extractEducation:s=!1,extractSkills:i=!1,extractRecommendations:l=!1,extractCertifications:y=!1}=n;try{await H(e,t,{readySelector:".scaffold-layout__main, main.scaffold-layout__main, .pv-top-card, section.pv-top-card",label:"profile"}),await p(1500),await qe(e)&&(console.log(" Dismissed Premium overlay"),await p(1500),await Wt(e,t));let u=0;for(let h=0;h<2;h++){let q=await e.evaluate(()=>document.body.scrollHeight);for(let T=1;T<=6;T++)await e.evaluate(E=>window.scrollTo(0,E),q*T/6),await p(900);let F=await e.evaluate(()=>document.body.scrollHeight);if(F===u)break;u=F}await p(800);let b=null;try{let h=e.url();h&&/\/in\/[^/?#]/.test(h)&&(b=h.split("?")[0].replace(/\/+$/,""))}catch{}let w=await e.evaluate(()=>{let h=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),q=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),F=a=>{let c=(a||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(c)},T={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},E=document.querySelector("main");if(!E)return T;let f=[...Array.from(E.querySelectorAll("h1")),...Array.from(E.querySelectorAll("h2"))],k=Array.from(E.querySelectorAll("h2")),N=f.find(a=>{let c=a.textContent&&a.textContent.trim(),d=(c||"").replace(/\s*\(\d+\)$/,"").trim();return c&&c.length>1&&c.length<100&&!h.has(d)&&!q.has(d)}),j=N?N.textContent.trim():null,x=N?N.parentElement:null;for(;x&&x!==E&&!Array.from(x.children).filter(c=>c.tagName==="P").some(c=>{let d=c.textContent&&c.textContent.trim();return d&&d.length>5&&!F(d)});)x=x.parentElement;let de=null,fe=null,me=null,ne=null;if(x&&x!==E){let a=Array.from(x.children).filter(d=>d.tagName==="P").filter(d=>{let R=d.textContent&&d.textContent.trim();return R&&R.length>5&&!F(R)});if(a[0]&&(de=a[0].textContent.trim()),a[1]){let d=a[1].textContent.trim().split(/\s*[·•]\s*/);fe=d[0]||null,d.length>1&&(me=d.slice(1).join(" \xB7 "))}let c=Array.from(x.children).filter(d=>d.tagName==="DIV");for(let d=c.length-1;d>=0;d--){let R=c[d].textContent&&c[d].textContent.trim();if(R&&!(j&&R.startsWith(j))&&(ne=R.split(/[·•]/)[0].trim(),ne))break}}let pe=null;if(x){let a=x.querySelectorAll("p, span, div");for(let c of a){let d=(c.textContent||"").trim().replace(/^[·•]\s*/,"");if(d==="1st"||d==="2nd"||d==="3rd"){pe=d;break}}}let ot=!!E.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),he=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),rt=he&&he.src||null,z=E.textContent||"",we=null,ge=z.match(/(\d+\+?)\s+connections\b/i);ge&&(we=ge[1]+" connections");let Q=null,ye=z.match(/(\d+)\s+mutual connection/i),be=z.match(/and\s+(\d+)\s+other mutual/i),it=z.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);ye?Q=parseInt(ye[1],10):be?Q=2+parseInt(be[1],10):it&&(Q=2);let Se=null,ve=null,Ce=k.find(a=>a.textContent&&a.textContent.trim()==="About");if(Ce){let a=Ce.parentElement;for(;a&&a.tagName!=="SECTION";)a=a.parentElement;if(a){let c=(a.textContent||"").trim();c=c.replace(/^About\s*/,"").trim();let d=c.match(/Top skills\s*(.+?)$/i);if(d){let oe=d[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(ct=>ct.trim()).filter(Boolean);oe.length>0&&oe.length<10&&(ve=oe)}c=c.split(/\n?…\s*more/i)[0].trim(),c=c.split(/\n?\.\.\.\s*more/i)[0].trim(),c=c.split(/\bTop skills\b/i)[0].trim(),c=c.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Se=c||null}}let ke=null,xe=k.find(a=>a.textContent&&a.textContent.trim()==="Activity");if(xe){let a=xe.parentElement;for(;a&&a.tagName!=="SECTION";)a=a.parentElement;if(a){let c=(a.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);c&&(ke=parseInt(c[1].replace(/,/g,""),10))}}let st=[...new Set(k.map(a=>(a.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(a=>a&&a.length>1&&a.length<60&&a!==j).filter(a=>h.has(a)))],U=document.body.textContent||"",at=/#OpenToWork\b/i.test(U)||/\bOpen to work\b/.test(U),lt=/#Hiring\b/i.test(U)||/\bI'?m hiring\b/i.test(U)||/\bWe are hiring\b/i.test(U);return{name:j,title:de,location:ne,currentCompany:fe,currentSchool:me,connectionDegree:pe,hasVerifiedBadge:ot,photoUrl:rt,connectionsLevel:we,mutualConnectionsCount:Q,followers:ke,openToWork:at,hiring:lt,about:Se,topSkills:ve,availableSections:st}});console.log(`Viewed: ${w.name} - ${w.title}`);let g=null,v=null,A=null,P=null,L=null,M=null;if(o||r||s||i||l||y){let h=await Promise.resolve().then(()=>(Ze(),Xe));o&&(g=await h.extractExperienceFromDetails(e,t),console.log(` + Experience: ${g.length} entries`)),r&&(v=await h.extractFeaturedFromDetails(e,t),console.log(` + Featured: ${v.length} entries`)),s&&(A=await h.extractEducationFromDetails(e,t),console.log(` + Education: ${A.length} entries`)),i&&(P=await h.extractSkillsFromDetails(e,t),console.log(` + Skills: ${P.length} entries`)),l&&(L=await h.extractRecommendationsFromDetails(e,t),console.log(` + Recommendations: ${L.length} entries`)),y&&(M=await h.extractCertificationsFromDetails(e,t),console.log(` + Certifications: ${M.length} entries`))}return{...w,profileUrl:t,resolvedUrl:b,...g!==null&&{experience:g},...v!==null&&{featured:v},...A!==null&&{education:A},...P!==null&&{skillsFull:P},...L!==null&&{recommendations:L},...M!==null&&{certifications:M}}}catch(m){console.error(`Error viewing profile ${t}:`,m.message);try{await e.goto("about:blank",{timeout:1e4}),await p(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test(m.message||""))throw m;return null}}await ce();V();var ue=process.argv.slice(2),tt=ue.filter(e=>e.startsWith("http")),nt=parseInt(ue.find(e=>e.startsWith("--pick="))?.split("=")[1]||"0"),Yt=ue.includes("--has-about");function Kt(e,t){return[...e].sort(()=>Math.random()-.5).slice(0,t)}function Gt(){if(tt.length>0)return tt.map(t=>({url:t,name:"(arg)"}));if(nt>0){let t=le(),n=Object.entries(t).filter(([o])=>o.startsWith("http")).filter(([,o])=>Yt?!!(o.about&&o.about.trim()):!o.about);return Kt(n,nt).map(([o,r])=>({url:o,name:r.name}))}let e=process.env.MY_LINKEDIN_URL;return e||(console.error("Pass a URL, use --pick=N, or set MY_LINKEDIN_URL in .env"),process.exit(1)),[{url:e,name:"(self)"}]}function I(e,t,n=80){if(t==null){console.log(` ${e.padEnd(20)} (null)`);return}let o=String(t),r=o.length>n?o.slice(0,n)+`\u2026 (+${o.length-n} chars)`:o;console.log(` ${e.padEnd(20)} ${r} [len=${o.length}]`)}async function zt(){let e=Gt();console.log(`
|
|
241
241
|
About-selector verification \u2014 ${e.length} profile(s)
|
|
242
|
-
`);let{browser:t,page:n}=await
|
|
243
|
-
`);continue}I("name",
|
|
244
|
-
Verdict: ${
|
|
245
|
-
`),o<e.length-1&&await p(3e3+Math.random()*2e3)}}finally{await t.close().catch(()=>{})}}
|
|
242
|
+
`);let{browser:t,page:n}=await ze();try{for(let o=0;o<e.length;o++){let{url:r,name:s}=e[o];console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),console.log(` [${o+1}/${e.length}] ${s}`),console.log(` ${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\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let i=await et(n,r);if(!i){console.log(` \u26A0 viewProfile returned null \u2014 selector failed entirely
|
|
243
|
+
`);continue}I("name",i.name),I("title",i.title),I("location",i.location),I("company",i.company),I("connectionDegree",i.connectionDegree),I("connectionsCount",i.connectionsCount),I("mutualConnections",i.mutualConnections),I("hasVerifiedBadge",i.hasVerifiedBadge),I("photoUrl",i.photoUrl,60),console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 about \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),I("about",i.about,200);let l=[];i.name||l.push("NAME MISSING"),i.title||l.push("TITLE MISSING"),i.location||l.push("LOCATION MISSING"),i.about||l.push("ABOUT MISSING"),console.log(`
|
|
244
|
+
Verdict: ${l.length===0?"OK \u2014 all core fields present":l.join(", ")}
|
|
245
|
+
`),o<e.length-1&&await p(3e3+Math.random()*2e3)}}finally{await t.close().catch(()=>{})}}zt().catch(e=>{console.error("verify-about failed:",e),process.exit(1)});
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.20.13";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()}`);
|