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/scout.mjs
CHANGED
|
@@ -1,60 +1,61 @@
|
|
|
1
|
-
var
|
|
1
|
+
var no=Object.defineProperty;var pe=(e,t)=>{for(var o in t)no(e,o,{get:t[o],enumerable:!0})};import ko from"puppeteer";import{addExtra as vo}from"puppeteer-extra";import Ao from"puppeteer-extra-plugin-stealth";import _ from"fs";import U from"path";var ro="cookies.json";function ve(){let e=process.env.ILML_SCOPE_DIR;return e?U.join(e,"plugins-state","linkedin","cookies.json"):ro}function so(){let e=ve(),t=U.dirname(e);return t&&t!=="."&&!_.existsSync(t)&&_.mkdirSync(t,{recursive:!0}),e}function Je(e){let t=so();return _.writeFileSync(t,JSON.stringify(e)),t}function He(){let e=ve();if(!_.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let t;try{t=_.readFileSync(e,"utf-8")}catch(r){throw new Error(`Failed to read cookies at ${e}: ${r.message}. Run: ilml linkedin login`)}let o;try{o=JSON.parse(t)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(o)||o.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return o}function Ge(){return _.existsSync(ve())}function io(){let e=process.env.ILML_SCOPE_DIR;return e?U.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 co(){let e=process.env.MY_LINKEDIN_URL,t=e&&e.match(/\/in\/([^/?#]+)/);return t&&t[1]?We(t[1]):"default"}function Ve(e){let t=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(t)return _.existsSync(t)||_.mkdirSync(t,{recursive:!0}),U.resolve(t);let o=We(e||co()),r=U.join(io(),"chrome-profile",o);return _.existsSync(r)||_.mkdirSync(r,{recursive:!0}),U.resolve(r)}var Ke=".ilml-seeded";function Ye(e){return!_.existsSync(U.join(e,Ke))}function ze(e){try{_.writeFileSync(U.join(e,Ke),new Date().toISOString())}catch{}}function Qe(e){let t=0;for(let o of["SingletonLock","SingletonCookie","SingletonSocket"])try{_.rmSync(U.join(e,o),{force:!0}),t++}catch{}return t}async function j(e){let t=Math.floor(Math.random()*2001),o=e+t;return new Promise(r=>setTimeout(r,o))}async function Xe(e,t,{timeout:o=45e3,poll:r=1e3,label:n="page"}={}){let i=Date.now();for(;Date.now()-i<o;){try{if(await e.evaluate(c=>!!document.querySelector(c),t)){let c=Date.now()-i;return c>6e3&&console.log(` (waited ${Math.round(c/1e3)}s for LinkedIn to finish loading ${n})`),!0}}catch{}await new Promise(s=>setTimeout(s,r))}return!1}var Ze=/\/authwall|\/login|\/checkpoint|\/uas\/login/;function de(e){return Ze.test(e||"")}async function et(e,{credentialWaitMs:t=36e4,label:o="page"}={}){console.log(` \u26A0 Auth wall on ${o} \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 r=!!(process.stdin&&process.stdin.isTTY),n=r?t:Math.min(t,45e3),i=Date.now(),s=!1;for(;Date.now()-i<n;){let l="wait";try{l=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",Ze.source)}catch{}if(l==="in"){try{let a=await e.cookies();if(Array.isArray(a)&&a.some(m=>m.name==="li_at")){let m=Je(a);console.log(` \u2713 Session recovered \u2014 re-saved ${a.length} cookies (${m}).`)}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(l==="creds"){if(!r){let a=new Error(`Session expired (${o}) \u2014 credentials required and no interactive terminal. Run: ilml linkedin login`);throw a.code="SESSION_EXPIRED",a}s||(s=!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 c=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}import{getPluginConfig as so}from"@ilivemylife/graph-sdk";var io=await so();for(let[e,t]of Object.entries(io))process.env[e]===void 0&&(process.env[e]=t);var co=process.env.LINKEDIN_NAME,G=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Vn=Object.freeze(new Set([G.DRAFT,G.CONFIRMED,G.NEEDS_REVIEW])),lo=Object.freeze(new Set([G.DRAFT,G.CONFIRMED,G.REJECTED,G.NEEDS_REVIEW]));import Ae from"fs";import ao from"path";var uo={headless:!1,defaultViewport:null,protocolTimeout:3e5},ee=new Set,tt=!1;async function pe(){let e=[...ee].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ee.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function fo(){if(tt)return;tt=!0;let e=t=>async()=>{await pe(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await pe(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await pe(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await pe(),process.exit(0))}),process.on("exit",()=>{for(let t of ee)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function _e(e){return ao.join(e,".ilml-browser-session.json")}function st(e,t={}){try{Ae.writeFileSync(_e(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function po(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();st(e,o?{wsEndpoint:o}:{})}catch{}}function mo(e){let t=it(e);t&&t.ownerPid===process.pid&&Z(e)}function Z(e){try{Ae.rmSync(_e(e),{force:!0})}catch{}}function it(e){try{return JSON.parse(Ae.readFileSync(_e(e),"utf-8"))}catch{return null}}function ot(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function nt(e,t,o){let n,r=new Promise(s=>{n=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(n),s),s=>{throw clearTimeout(n),s});return Promise.race([i,r])}async function rt(e,t,{probeTimeoutMs:o=4e3}={}){let n=it(t);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&ot(n.ownerPid)?"live":(Z(t),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await nt(i,o,r);if(s===r)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return Z(t),"free";if(ot(n.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await nt(s.close().then(()=>!0).catch(()=>!1),o,!1))return Z(t),"free";try{s.disconnect()}catch{}return"live"}function ho(e,t){e&&(fo(),ee.add(e),e.on("disconnected",()=>{ee.delete(e),t&&Z(t)}))}async function ct(e,t={}){let o=Ve(),n={...uo,...t,userDataDir:o},r=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await rt(e,o)==="live")throw new Error(r);st(o);let i;try{i=await e.launch(n)}catch{if(await rt(e,o)==="live")throw new Error(r);Qe(o);try{i=await e.launch(n)}catch(c){throw mo(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return ho(i,o),po(o,i),{browser:i,profileDir:o,needsSeed:Ye(o)}}async function lt(e,t){if(!t||!t.needsSeed)return!1;if(!We())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(...He()),ze(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var at=go(yo);at.use(So());async function ut(){let{browser:e,profileDir:t,needsSeed:o}=await ct(at),n=await e.newPage();return await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await lt(n,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:n}}async function ft(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async n=>{let r=null,i=null;for(let m of n)if(r=document.querySelector(m),r){i=m;break}if(!r){let m=document.querySelector("li.scaffold-layout__list-item");if(m){let f=m.parentElement;for(;f&&f!==document.body;){if(f.scrollHeight>f.clientHeight){r=f,i="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!r)return{found:!1,triedSelectors:n};let s=r.scrollTop,c=300,l=300,a=50,p=0;for(;p<a&&(r.scrollBy(0,c),await new Promise(m=>setTimeout(m,l)),!(r.scrollTop+r.clientHeight>=r.scrollHeight));)p++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:r.scrollTop,scrollHeight:r.scrollHeight,attempts:p}},t)}async function pt(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let n=document.querySelectorAll("li.scaffold-layout__list-item");return Array.from(n).map(r=>{let s=(r.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),c=r.querySelector("a.job-card-container__link");if(c){let l=c.getAttribute("href").split("?")[0],a=r.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),p=r.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),m=r.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),f=r.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim();return{id:l,isEasyApply:s,applyType:s?"easy-apply":"external",dataId:c.getAttribute("data-control-id"),href:`https://linkedin.com${l}`,jobTitle:a,companyName:p,location:m,salary:f||null,jobLink:s?c.href:null}}return{isEasyApply:!1}})});return t?o.filter(n=>n.isEasyApply&&n.href):o.filter(n=>n.href)}async function dt(e){let t=await e.evaluate(()=>{let o=document.querySelector('button[aria-label="View next page"]')||document.querySelector(".jobs-search-pagination__button--next");if(o&&!o.disabled){let n=document.querySelector(".jobs-search-pagination__page-state")?.textContent?.trim();return o.click(),{success:!0,pageState:n}}return{success:!1,reason:"No next page button found"}});return console.log(" Pagination:",t.success?t.pageState:t.reason),t.success&&await j(2e3),t.success}async function mt(e,t){let o=e.url();if(!fe(o)&&o.includes("/jobs/"))return!1;if(fe(o)){if(!await Xe(e,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&fe(e.url())&&await et(e,{label:"job search"}),e.url().includes("/jobs/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(2e3)),!e.url().includes("/jobs/"))throw new Error(`Session expired \u2014 could not return to job search (landed on ${e.url().slice(0,60)}). Run: ilml linkedin login`);return!0}console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let n=e.url();if(!n.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${n.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function ht(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),c=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:c?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let n=t.querySelector(".jobs-poster__name");if(n){let s=n.closest('a[href*="/in/"]')||n.parentElement?.querySelector('a[href*="/in/"]')||n.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:n.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let r=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(r){let s=r.querySelector('a[href*="/in/"]');if(s)return{name:(r.querySelector(".jobs-poster__name")||r.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let c=s.textContent?.trim();if(c&&c.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(c))return{name:c,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function yt(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,n=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",r={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let W of i){let ve=W.querySelector(".job-criteria__subheader")?.textContent?.trim(),Be=W.querySelector(".job-criteria__text")?.textContent?.trim();ve&&Be&&(r[ve.toLowerCase()]=Be)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],c=[];for(let W of s)new RegExp("\\b"+W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(n)&&c.push(W.replace(/\\\+/g,"+"));let a=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,m=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,f=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),d=f?.innerText?.trim()||null,S=(f?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,g=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",U=g.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,q=g.match(/(\d[\d,]*)\s+applicant/i),Se=q?parseInt(q[1].replace(/,/g,"")):null,be=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),ce=Array.from(be).map(W=>W.innerText?.trim()?.replace(/\s+/g," ")),we=ce.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,B=ce.join(" ")+" "+g,Xt=/\bremote\b/i.test(B)?"remote":/\bhybrid\b/i.test(B)?"hybrid":/\bon-?site\b/i.test(B)?"onsite":null,Zt=/\bcontract\b/i.test(B)?"contract":/\bfull-?time\b/i.test(B)?"full-time":/\bpart-?time\b/i.test(B)?"part-time":/\bfreelance\b/i.test(B)?"freelance":/\btemporary\b/i.test(B)?"temporary":null,Ue=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",ae=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",D=(Ue+" "+n+" "+ae).toLowerCase(),O=Ue.toLowerCase(),h=[];/\bremote\b/.test(D)&&h.push("remote"),/\bhybrid\b/.test(D)&&h.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(D)&&h.push("onsite"),(h.length===0||!h.includes("remote")&&!h.includes("hybrid")&&!h.includes("onsite"))&&/remote/i.test(ae)&&h.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(O)&&h.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(O)&&h.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(O)&&!h.includes("managerial")&&h.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(O)?h.push("junior"):/\b(senior|sr\.?)\b/i.test(O)?h.push("senior"):/\b(staff|principal|distinguished)\b/i.test(O)?h.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(O)?h.push("executive"):/\b(lead|team lead)\b/i.test(O)&&h.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(D)&&h.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(D)&&h.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(D)&&h.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(D)&&h.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(D)&&h.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(D)&&h.push("mobile"),/\b(architect)\b/i.test(O)&&h.push("architect"),/\b(consultant|consulting)\b/i.test(O)&&h.push("consultant");let qe=(r["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(qe)||/\bcontract\b/i.test(D))&&h.push("contract"),/full.?time|permanent/i.test(qe)&&h.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(ae)&&h.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(ae)&&h.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(n))&&h.push("has-salary"),{description:n.substring(0,5e3),externalApplyUrl:m,companyName:d,companyUrl:S?S.startsWith("/")?"https://www.linkedin.com"+S:S:null,aboutCompany:a,seniority:r["seniority level"]||null,employmentType:r["employment type"]||null,industries:r.industries||null,jobFunction:r["job function"]||null,postedTime:U,applicantCount:Se,companySize:we,workplaceType:Xt,contractType:Zt,techStack:[...new Set(c)],jobTags:[...new Set(h)]}})}import"dotenv/config";import*as x from"fs";import*as E from"path";import{fileURLToPath as bo}from"url";function gt(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}var wo=bo(import.meta.url),vo=E.dirname(E.dirname(wo)),K=process.env.DATA_DIR?E.resolve(process.env.DATA_DIR,"market-research"):E.join(vo,"market-research"),St=E.join(K,"scouted-jobs.json"),bt=E.join(K,"discovered-people.json"),ko=E.join(K,"visit-log.json"),wt=E.join(K,"companies.json"),vr=E.join(K,"job-decisions.json");function Ee(){x.existsSync(K)||x.mkdirSync(K,{recursive:!0})}function je(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";x.writeFileSync(n,o);for(let r=0;r<3;r++)try{x.renameSync(n,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function me(e){try{if(x.existsSync(e))return JSON.parse(x.readFileSync(e,"utf-8"))}catch{}return null}function vt(){te=null,Ao=null,oe=null,ne=null,V=null}var te=null;function he(){return te||(te=me(St)||{},te)}function kt(e,t){if(!e)return;Ee();let o=he(),n=new Date().toISOString().slice(0,10);if(o[e]){for(let[r,i]of Object.entries(t))i!=null&&(o[e][r]=i);o[e].lastSeen=n}else o[e]={...t,scoutedAt:n,lastSeen:n};try{je(St,o)}catch(r){console.error(`[!] Failed to save scouted-jobs.json: ${r.message}`)}}var Ao=null;var oe=null;function At(){return oe||(oe=me(bt)||{},oe)}function de(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function _o(e,t){let o=gt(t)||t;if(e[o])return o;let n=de(t);if(!n)return o;let r=null;for(let[i,s]of Object.entries(e)){if(de(s&&(s.canonicalUrl||s.profileUrl)||i)===n)return i;!r&&s&&Array.isArray(s.aliases)&&s.aliases.includes(n)&&(r=i)}return r||o}function _t(e,t){if(!e)return;Ee();let o=At(),n=new Date().toISOString().slice(0,10),r=_o(o,e),i=de(e);if(o[r]){let s=o[r];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&de(s.canonicalUrl||s.profileUrl||r)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=n,s.seenCount=(s.seenCount||1)+1}else o[r]={canonicalUrl:r,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:n,lastSeen:n,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{je(bt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}var ne=null;function Eo(){return ne||(ne=me(wt)||{},ne)}function Et(e,t){if(!e)return;Ee();let o=Eo(),n=new Date().toISOString().slice(0,10);if(o[e]){let r=o[e];t.name&&(r.name=t.name),t.about&&(r.about=t.about),t.size&&(r.size=t.size),t.industries&&(r.industries=t.industries),t.jobId&&(r.jobIds||(r.jobIds=[]),r.jobIds.includes(t.jobId)||r.jobIds.push(t.jobId)),t.recruiterUrl&&(r.recruiterUrls||(r.recruiterUrls=[]),r.recruiterUrls.includes(t.recruiterUrl)||r.recruiterUrls.push(t.recruiterUrl)),r.lastSeen=n,r.jobCount=r.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:n,lastSeen:n,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{je(wt,o)}catch(r){console.error(`[!] Failed to save companies.json: ${r.message}`)}}var V=null;function jo(){return V||(V=me(ko)||{visits:[]},Array.isArray(V.visits)||(V.visits=[]),V)}function jt(){let e=he(),t=At(),o=Object.values(e),n=Object.values(t),r={};for(let f of o)f.company&&(r[f.company]=(r[f.company]||0)+1);let i=Object.entries(r).sort((f,d)=>d[1]-f[1]).slice(0,5).map(([f,d])=>`${f} (${d})`),s={};for(let f of o)for(let d of f.techStack||[])s[d]=(s[d]||0)+1;let c=Object.entries(s).sort((f,d)=>d[1]-f[1]).slice(0,8).map(([f,d])=>`${f} (${d})`),l=jo(),a=new Date().toISOString().slice(0,10),p=l.visits.filter(f=>f.date.startsWith(a)).length,m=new Set(l.visits.map(f=>f.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:n.length,topCompanies:i,topTech:c,totalVisited:m,todayVisited:p,lastScoutDate:o.length>0?o.sort((f,d)=>(d.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}import"dotenv/config";import*as b from"fs";import*as v from"path";import{fileURLToPath as xo}from"url";var Co=xo(import.meta.url),$o=v.dirname(v.dirname(Co)),P=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"collected-profiles"):v.join($o,"collected-profiles"),To=v.join(P,"people.json"),Io=v.join(P,"jobs.json"),jr=v.join(P,"quota.json"),xr=v.join(P,"conversations.json"),Cr=v.join(P,"sync-state.json"),$r=v.join(P,"application-questions.json"),Tr=v.join(P,"profile-history"),xt=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},Ir=xt(process.env.CONNECT_MAX_DAILY,20),Rr=xt(process.env.CONNECT_MAX_WEEKLY,100),re=null,se=null,Ro=null,Do=null,Oo=null,No=null;function Ct(){re=null,se=null,Ro=null,Do=null,Oo=null,No=null}function $t(){b.existsSync(P)||b.mkdirSync(P,{recursive:!0})}function Tt(e,t){if(!b.existsSync(e))return null;try{let o=JSON.parse(b.readFileSync(e,"utf-8"));try{b.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${v.resolve(e)}`);let n=e+".backup";if(b.existsSync(n))try{let r=JSON.parse(b.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{b.copyFileSync(n,e)}catch{}return r}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{b.copyFileSync(e,e+".corrupted")}catch{}return null}}function It(){return re||($t(),re=Tt(To,"people.json")||{},re)}function Rt(){return se||($t(),se=Tt(Io,"jobs.json")||{},se)}import"dotenv/config";import*as C from"fs";import*as J from"path";import{fileURLToPath as qo}from"url";import"dotenv/config";import{createGraphClient as Lo,resolveToken as Fo}from"@ilivemylife/graph-sdk";import{config as Po}from"dotenv";Po();var Dt=Fo()||process.env.TOKEN;Dt||(console.error(`
|
|
3
|
+
`))}await new Promise(a=>setTimeout(a,2500))}let c=new Error(`Session expired (${o}) \u2014 not signed in within the wait window. Run: ilml linkedin login`);throw c.code="SESSION_EXPIRED",c}import{getPluginConfig as uo}from"@ilivemylife/graph-sdk";var lo={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},tt=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function ao(e){return String(e??"").split(/[,\s|]+/).map(t=>t.trim()).filter(Boolean)}function ot(e=process.env){let t=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!t)return null;let o=new URLSearchParams;o.set("keywords",t);let r=(e.JOB_SEARCH_LOCATION||"").trim();r&&o.set("location",r);let n=(e.JOB_SEARCH_GEO_ID||"").trim();n&&o.set("geoId",n);let i=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&o.set("distance",String(i)),tt(e.JOB_SEARCH_EASY_APPLY)&&o.set("f_AL","true"),tt(e.JOB_SEARCH_IN_NETWORK)&&o.set("f_JIYN","true");let s=ao(e.JOB_SEARCH_COMPANY_IDS);s.length&&o.set("f_C",s.join(","));let c=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();c&&o.set("f_TPR",lo[c]||c),o.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let l="https://www.linkedin.com/jobs/search/?"+o.toString(),a=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return a&&(l+="&"+a),l}var fo=await uo();for(let[e,t]of Object.entries(fo))process.env[e]===void 0&&(process.env[e]=t);var nt=ot(process.env);nt&&(process.env.LINKEDIN_SEARCH_URL=nt);var po=process.env.LINKEDIN_NAME,V=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),er=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.NEEDS_REVIEW])),mo=Object.freeze(new Set([V.DRAFT,V.CONFIRMED,V.REJECTED,V.NEEDS_REVIEW]));import Ae from"fs";import ho from"path";var yo={headless:!1,defaultViewport:null,protocolTimeout:3e5},ne=new Set,rt=!1;async function me(){let e=[...ne].map(t=>{try{return Promise.resolve(t.close()).catch(()=>{})}catch{return Promise.resolve()}});ne.clear(),await Promise.race([Promise.all(e),new Promise(t=>setTimeout(t,5e3))])}function go(){if(rt)return;rt=!0;let e=t=>async()=>{await me(),process.exit(t)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async t=>{await me(),console.error(t&&t.stack||t),process.exit(1)}),process.once("unhandledRejection",async t=>{await me(),console.error(t),process.exit(1)}),process.stdout.on("error",async t=>{t&&t.code==="EPIPE"&&(await me(),process.exit(0))}),process.on("exit",()=>{for(let t of ne)try{let o=t.process&&t.process();o&&o.kill("SIGKILL")}catch{}})}function _e(e){return ho.join(e,".ilml-browser-session.json")}function lt(e,t={}){try{Ae.writeFileSync(_e(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...t}))}catch{}}function So(e,t){try{let o=t.wsEndpoint&&t.wsEndpoint();lt(e,o?{wsEndpoint:o}:{})}catch{}}function bo(e){let t=at(e);t&&t.ownerPid===process.pid&&oe(e)}function oe(e){try{Ae.rmSync(_e(e),{force:!0})}catch{}}function at(e){try{return JSON.parse(Ae.readFileSync(_e(e),"utf-8"))}catch{return null}}function st(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return!t||t.code!=="ESRCH"}}function it(e,t,o){let r,n=new Promise(s=>{r=setTimeout(()=>s(o),t)}),i=Promise.resolve(e).then(s=>(clearTimeout(r),s),s=>{throw clearTimeout(r),s});return Promise.race([i,n])}async function ct(e,t,{probeTimeoutMs:o=4e3}={}){let r=at(t);if(!r)return"free";if(!r.wsEndpoint)return r.ownerPid&&r.ownerPid!==process.pid&&st(r.ownerPid)?"live":(oe(t),"free");let n=Symbol("timeout"),i=e.connect({browserWSEndpoint:r.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await it(i,o,n);if(s===n)return i.then(l=>{if(l)try{l.disconnect()}catch{}}),"live";if(!s)return oe(t),"free";if(st(r.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await it(s.close().then(()=>!0).catch(()=>!1),o,!1))return oe(t),"free";try{s.disconnect()}catch{}return"live"}function wo(e,t){e&&(go(),ne.add(e),e.on("disconnected",()=>{ne.delete(e),t&&oe(t)}))}async function ut(e,t={}){let o=Ve(),r={...yo,...t,userDataDir:o},n=`Could not open the LinkedIn automation Chrome profile at ${o}. Another LinkedIn automation command is already running (or its window is still open) \u2014 wait for it to finish or close that window, then retry.`;if(await ct(e,o)==="live")throw new Error(n);lt(o);let i;try{i=await e.launch(r)}catch{if(await ct(e,o)==="live")throw new Error(n);Qe(o);try{i=await e.launch(r)}catch(c){throw bo(o),new Error(`Could not open the LinkedIn automation Chrome profile at ${o}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${c.message})`)}}return wo(i,o),So(o,i),{browser:i,profileDir:o,needsSeed:Ye(o)}}async function ft(e,t){if(!t||!t.needsSeed)return!1;if(!Ge())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(...He()),ze(t.profileDir),console.log(" (seeded persistent profile from saved cookies \u2014 one-time)"),!0}catch{return!1}}var pt=vo(ko);pt.use(Ao());async function dt(){let{browser:e,profileDir:t,needsSeed:o}=await ut(pt),r=await e.newPage();return await r.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})}),await ft(r,{profileDir:t,needsSeed:o}),console.log(" Browser launched (persistent profile)."),{browser:e,page:r}}async function mt(e){let t=[".jobs-search-results-list",".scaffold-layout__list-container",".jobs-search-two-pane__results","div.jobs-search-results-list"];return await e.evaluate(async r=>{let n=null,i=null;for(let m of r)if(n=document.querySelector(m),n){i=m;break}if(!n){let m=document.querySelector("li.scaffold-layout__list-item");if(m){let f=m.parentElement;for(;f&&f!==document.body;){if(f.scrollHeight>f.clientHeight){n=f,i="parent of li.scaffold-layout__list-item";break}f=f.parentElement}}}if(!n)return{found:!1,triedSelectors:r};let s=n.scrollTop,c=300,l=300,a=50,u=0;for(;u<a&&(n.scrollBy(0,c),await new Promise(m=>setTimeout(m,l)),!(n.scrollTop+n.clientHeight>=n.scrollHeight));)u++;return{found:!0,usedSelector:i,initialScroll:s,finalScroll:n.scrollTop,scrollHeight:n.scrollHeight,attempts:u}},t)}async function ht(e,{easyApplyOnly:t=!0}={}){let o=await e.evaluate(()=>{let n=document.querySelectorAll("li.scaffold-layout__list-item");if(n.length)return{ui:"old",jobs:Array.from(n).map(u=>{let f=(u.querySelector(".job-card-list__footer-wrapper")?.innerText??"").includes("Easy Apply"),d=u.querySelector("a.job-card-container__link");if(!d)return{isEasyApply:!1};let b=d.getAttribute("href").split("?")[0];return{id:b,isEasyApply:f,applyType:f?"easy-apply":"external",dataId:d.getAttribute("data-control-id"),href:`https://linkedin.com${b}`,jobTitle:u.querySelector(".job-card-list__title--link")?.getAttribute("aria-label")?.replace(/ with verification$/,""),companyName:u.querySelector(".artdeco-entity-lockup__subtitle")?.innerText.trim(),location:u.querySelector(".artdeco-entity-lockup__caption")?.innerText.trim(),salary:u.querySelector(".artdeco-entity-lockup__metadata")?.innerText.trim()||null,jobLink:f?d.href:null,cardIndex:null}})};let i=Array.from(document.querySelectorAll('button[aria-label^="Dismiss"]')),s=a=>{let u=a;for(let m=0;m<14&&u&&u.parentElement;m++){u=u.parentElement;let d=Array.from(u.parentElement.children).filter(b=>{try{return b.querySelectorAll('button[aria-label^="Dismiss"]').length===1}catch{return!1}});if(d.length>=5&&d.includes(u))return u}return null},c=new Set,l=[];return i.forEach((a,u)=>{let m=s(a);if(!m||c.has(m))return;c.add(m);let f=m.innerText||"",d=m.matches&&m.matches("[componentkey]")?m:m.querySelector("[componentkey]")||m.closest("[componentkey]"),g=((d&&d.getAttribute("componentkey")||"").match(/(\d{6,})/)||[])[1]||null,w=(a.getAttribute("aria-label")||"").replace(/^Dismiss\s+/,"").replace(/\s+job$/,"").trim(),A=f.split(`
|
|
4
|
+
`).map(x=>x.trim()).filter(Boolean).filter(x=>x&&x!==w),T=A[0]||null,L=A.find(x=>x!==T&&/\((Remote|Hybrid|On-?site)\)|,\s*[A-Za-z]/.test(x))||A[1]||null,te=(f.match(/\$[\d,]+[^\n]*?(?:\/yr|\/hr|per year|per hour|K\b)|[\d,]+\s*(?:CAD|USD|EUR|GBP)[^\n]*?\/(?:hr|yr)/i)||[])[0]||null,Z=/Easy Apply/i.test(f);l.push({id:g?`https://www.linkedin.com/jobs/view/${g}/`:null,href:g?`https://www.linkedin.com/jobs/view/${g}/`:null,jobId:g,cardIndex:u,isEasyApply:Z,isApplied:/(^|\s)Applied(\s|$)/.test(f),applyType:Z?"easy-apply":"external",jobTitle:w||null,companyName:T,location:L,salary:te||null,under10Applicants:/Under 10 applicants/i.test(f),activelyReviewing:/Actively reviewing/i.test(f),promoted:/Promoted/i.test(f),postedText:(f.match(/Posted[^\n]*/i)||[])[0]||null})}),{ui:"new",jobs:l}}),r=o.jobs||[];return o.ui==="new"?t?r.filter(n=>n.isEasyApply):r:t?r.filter(n=>n.isEasyApply&&n.href):r.filter(n=>n.href)}async function yt(e){let t=()=>parseInt((e.url().match(/[?&]start=(\d+)/)||[])[1]||"0",10),o=t(),r=await e.evaluate(()=>{let n=[...document.querySelectorAll('button[aria-label^="Page "]')],i=a=>parseInt((a.getAttribute("aria-label")||"").replace(/[^\d]/g,""),10),s=n.find(a=>a.getAttribute("aria-current")==="true"||a.getAttribute("aria-current")==="page");if(s){let a=i(s),u=n.find(m=>i(m)===a+1);return u&&!u.disabled?(u.scrollIntoView({block:"center"}),u.click(),{clicked:!0,to:`page ${a+1}`}):{clicked:!1,reason:`last page (${a})`}}let c=[...document.querySelectorAll("button")].find(a=>(/^Next$/i.test((a.innerText||"").trim())||/view next|next page/i.test(a.getAttribute("aria-label")||""))&&!a.disabled&&a.offsetParent!==null);if(c)return c.scrollIntoView({block:"center"}),c.click(),{clicked:!0,to:"next"};let l=document.querySelector('button[aria-label="View next page"], .jobs-search-pagination__button--next');return l&&!l.disabled?(l.click(),{clicked:!0,to:"legacy-next"}):{clicked:!1,reason:"No next page button found"}});if(!r.clicked)return console.log(" Pagination:",r.reason),!1;for(let n=0;n<16&&(await j(500),t()===o);n++);return await j(1500),t()===o?(console.log(" Pagination: clicked but page did not advance \u2014 stopping"),!1):(console.log(` Pagination \u2192 ${r.to}`),!0)}async function gt(e,t){let o=e.url();if(!de(o)&&o.includes("/jobs/"))return!1;if(de(o)){if(!await Xe(e,".scaffold-layout__main, main.scaffold-layout__main, .jobs-search-results-list",{timeout:45e3,label:"job search"})&&de(e.url())&&await et(e,{label:"job search"}),e.url().includes("/jobs/")||(await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(2e3)),!e.url().includes("/jobs/"))throw new Error(`Session expired \u2014 could not return to job search (landed on ${e.url().slice(0,60)}). Run: ilml linkedin login`);return!0}console.log(` Off-track: ${o.slice(0,80)}`),console.log(" Navigating back to job search..."),await e.goto(t,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let r=e.url();if(!r.includes("/jobs/"))throw new Error(`Could not return to job search. Current URL: ${r.slice(0,80)}`);return console.log(" Recovered to job search page"),!0}async function St(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,o=t.querySelector(".hirer-card__hirer-information");if(o){let s=o.querySelector('a[href*="/in/"]'),c=o.querySelector(".jobs-poster__name")||o.querySelector("strong")||o.querySelector('[class*="name"]');if(s)return{name:c?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"hiring_team"}}let r=t.querySelector(".jobs-poster__name");if(r){let s=r.closest('a[href*="/in/"]')||r.parentElement?.querySelector('a[href*="/in/"]')||r.parentElement?.parentElement?.querySelector('a[href*="/in/"]');if(s)return{name:r.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"poster_name"}}let n=t.querySelector(".job-details-people-who-can-help__section--two-pane")||t.querySelector('[class*="people-who-can-help"]');if(n){let s=n.querySelector('a[href*="/in/"]');if(s)return{name:(n.querySelector(".jobs-poster__name")||n.querySelector("strong"))?.textContent?.trim()||s.textContent?.trim(),profileUrl:s.href?.split("?")[0],source:"people_section"}}let i=t.querySelectorAll('a[href*="/in/"]');for(let s of i){let c=s.textContent?.trim();if(c&&c.length>3&&!["View","Connect","Follow","Message","Apply","Save"].includes(c))return{name:c,profileUrl:s.href?.split("?")[0],source:"details_link"}}return null})}async function bt(e){return e.evaluate(()=>{let t=document.querySelector(".scaffold-layout__detail")||document.querySelector(".jobs-search__job-details")||document.querySelector(".jobs-details")||document.body,r=(t.querySelector(".jobs-description__content")||t.querySelector(".jobs-box__html-content")||t.querySelector(".jobs-description"))?.innerText?.trim()||"",n={},i=t.querySelectorAll(".jobs-unified-top-card__job-insight, li.job-criteria__item");for(let W of i){let ke=W.querySelector(".job-criteria__subheader")?.textContent?.trim(),Be=W.querySelector(".job-criteria__text")?.textContent?.trim();ke&&Be&&(n[ke.toLowerCase()]=Be)}let s=["Java","Python","JavaScript","TypeScript","React","Angular","Vue","Node.js","C#",".NET","C\\+\\+","Go","Rust","Scala","Kotlin","AWS","Azure","GCP","Docker","Kubernetes","Terraform","SQL","PostgreSQL","MongoDB","Redis","Kafka","RabbitMQ","Spring","Django","Flask","Express","Next.js","CI/CD","Jenkins","GitHub Actions","GraphQL","REST","Microservices","Machine Learning","AI","Data Engineering","Spark","Hadoop","Snowflake","Databricks","Airflow","iOS","Android","React Native","Flutter","Agile","Scrum","DevOps","SRE"],c=[];for(let W of s)new RegExp("\\b"+W.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"\\b","i").test(r)&&c.push(W.replace(/\\\+/g,"+"));let a=t.querySelector('.jobs-company__box, [class*="jobs-company"], [class*="company-card"]')?.innerText?.trim()?.slice(0,1e3)||null,m=t.querySelector('a.jobs-apply-button[href], a[data-tracking-control-name="public_jobs_apply-link-offsite_sign-up"]')?.getAttribute("href")||null,f=t.querySelector(".job-details-jobs-unified-top-card__company-name, .jobs-unified-top-card__company-name"),d=f?.innerText?.trim()||null,g=(f?.querySelector('a[href*="/company/"]')||t.querySelector('a[href*="/company/"]'))?.getAttribute("href")?.split("?")[0]||null,S=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container")?.innerText?.trim()||"",T=S.match(/(\d+\s+(?:hour|day|week|month)s?\s+ago|Reposted|Just now)/i)?.[0]||null,L=S.match(/(\d[\d,]*)\s+applicant/i),te=L?parseInt(L[1].replace(/,/g,"")):null,Z=t.querySelectorAll(".job-details-jobs-unified-top-card__job-insight"),x=Array.from(Z).map(W=>W.innerText?.trim()?.replace(/\s+/g," ")),we=x.join(" ").match(/([\d,]+-[\d,]+\s+employees|[\d,]+\+?\s+employees)/i)?.[0]||null,J=x.join(" ")+" "+S,to=/\bremote\b/i.test(J)?"remote":/\bhybrid\b/i.test(J)?"hybrid":/\bon-?site\b/i.test(J)?"onsite":null,oo=/\bcontract\b/i.test(J)?"contract":/\bfull-?time\b/i.test(J)?"full-time":/\bpart-?time\b/i.test(J)?"part-time":/\bfreelance\b/i.test(J)?"freelance":/\btemporary\b/i.test(J)?"temporary":null,Ue=t.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()||"",fe=t.querySelector(".job-details-jobs-unified-top-card__primary-description-container, .jobs-unified-top-card__subtitle-primary-grouping")?.innerText?.trim()||"",P=(Ue+" "+r+" "+fe).toLowerCase(),F=Ue.toLowerCase(),h=[];/\bremote\b/.test(P)&&h.push("remote"),/\bhybrid\b/.test(P)&&h.push("hybrid"),/\bon-?site\b|\bin-?office\b/.test(P)&&h.push("onsite"),(h.length===0||!h.includes("remote")&&!h.includes("hybrid")&&!h.includes("onsite"))&&/remote/i.test(fe)&&h.push("remote"),/\b(manager|director|vp|vice president|head of|chief|cto|cio|lead.*team|managing)\b/i.test(F)&&h.push("managerial"),/\b(architect|principal|staff|distinguished)\b/i.test(F)&&h.push("senior-ic"),/\b(developer|engineer|programmer|analyst)\b/i.test(F)&&!h.includes("managerial")&&h.push("ic"),/\b(junior|jr\.?|entry)\b/i.test(F)?h.push("junior"):/\b(senior|sr\.?)\b/i.test(F)?h.push("senior"):/\b(staff|principal|distinguished)\b/i.test(F)?h.push("staff+"):/\b(director|vp|chief|cto|cio)\b/i.test(F)?h.push("executive"):/\b(lead|team lead)\b/i.test(F)&&h.push("lead"),/\b(backend|back-end|server-side|api)\b/i.test(P)&&h.push("backend"),/\b(frontend|front-end|ui|ux)\b/i.test(P)&&h.push("frontend"),/\b(full.?stack|fullstack)\b/i.test(P)&&h.push("fullstack"),/\b(devops|sre|infrastructure|platform)\b/i.test(P)&&h.push("devops"),/\b(data engineer|data science|machine learning|ml engineer)\b/i.test(P)&&h.push("data"),/\b(mobile|ios|android|react native|flutter)\b/i.test(P)&&h.push("mobile"),/\b(architect)\b/i.test(F)&&h.push("architect"),/\b(consultant|consulting)\b/i.test(F)&&h.push("consultant");let qe=(n["employment type"]||"").toLowerCase();return(/contract|freelance|temporary/i.test(qe)||/\bcontract\b/i.test(P))&&h.push("contract"),/full.?time|permanent/i.test(qe)&&h.push("permanent"),/\bcanada\b|toronto|vancouver|montreal|ontario|british columbia|quebec|alberta|calgary|ottawa/i.test(fe)&&h.push("canada"),/\bunited states\b|\busa\b|new york|california|texas|seattle|san francisco/i.test(fe)&&h.push("usa"),(t.querySelector(".jobs-unified-top-card__job-insight--highlight, .compensation__salary")?.innerText?.trim()||""||/\$[\d,]+/.test(r))&&h.push("has-salary"),{description:r.substring(0,5e3),externalApplyUrl:m,companyName:d,companyUrl:g?g.startsWith("/")?"https://www.linkedin.com"+g:g:null,aboutCompany:a,seniority:n["seniority level"]||null,employmentType:n["employment type"]||null,industries:n.industries||null,jobFunction:n["job function"]||null,postedTime:T,applicantCount:te,companySize:we,workplaceType:to,contractType:oo,techStack:[...new Set(c)],jobTags:[...new Set(h)]}})}import"dotenv/config";import*as $ from"fs";import*as C from"path";import{fileURLToPath as _o}from"url";function wt(e){if(!e||typeof e!="string"||/custom-invite|\/search\//i.test(e)||/\/in\/[^/?#]+\/(overlay|details)(\/|$)/i.test(e))return null;let t=e.match(/\/in\/([^/?#]+)/i);if(!t||!t[1])return null;let o=t[1].trim();return o?`https://www.linkedin.com/in/${o}/`:null}var Eo=_o(import.meta.url),xo=C.dirname(C.dirname(Eo)),Y=process.env.DATA_DIR?C.resolve(process.env.DATA_DIR,"market-research"):C.join(xo,"market-research"),kt=C.join(Y,"scouted-jobs.json"),vt=C.join(Y,"discovered-people.json"),jo=C.join(Y,"visit-log.json"),At=C.join(Y,"companies.json"),Cr=C.join(Y,"job-decisions.json");function Ee(){$.existsSync(Y)||$.mkdirSync(Y,{recursive:!0})}function xe(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";$.writeFileSync(r,o);for(let n=0;n<3;n++)try{$.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function ye(e){try{if($.existsSync(e))return JSON.parse($.readFileSync(e,"utf-8"))}catch{}return null}function _t(){re=null,Co=null,se=null,ie=null,K=null}var re=null;function ge(){return re||(re=ye(kt)||{},re)}function Et(e,t){if(!e)return;Ee();let o=ge(),r=new Date().toISOString().slice(0,10);if(o[e]){for(let[n,i]of Object.entries(t))i!=null&&(o[e][n]=i);o[e].lastSeen=r}else o[e]={...t,scoutedAt:r,lastSeen:r};try{xe(kt,o)}catch(n){console.error(`[!] Failed to save scouted-jobs.json: ${n.message}`)}}var Co=null;var se=null;function xt(){return se||(se=ye(vt)||{},se)}function he(e){let t=String(e||"").match(/\/in\/([^/?#]+)/i);return t?t[1].toLowerCase():null}function To(e,t){let o=wt(t)||t;if(e[o])return o;let r=he(t);if(!r)return o;let n=null;for(let[i,s]of Object.entries(e)){if(he(s&&(s.canonicalUrl||s.profileUrl)||i)===r)return i;!n&&s&&Array.isArray(s.aliases)&&s.aliases.includes(r)&&(n=i)}return n||o}function jt(e,t){if(!e)return;Ee();let o=xt(),r=new Date().toISOString().slice(0,10),n=To(o,e),i=he(e);if(o[n]){let s=o[n];t.name&&(s.name=t.name),t.title&&(s.title=t.title),t.company&&(s.company=t.company),t.location&&(s.location=t.location),t.role&&(s.role=t.role),t.isConnected!=null&&(s.isConnected=t.isConnected),t.jobId&&(s.jobIds||(s.jobIds=[]),s.jobIds.includes(t.jobId)||s.jobIds.push(t.jobId)),i&&he(s.canonicalUrl||s.profileUrl||n)!==i&&(Array.isArray(s.aliases)||(s.aliases=[]),s.aliases.includes(i)||s.aliases.push(i)),s.lastSeen=r,s.seenCount=(s.seenCount||1)+1}else o[n]={canonicalUrl:n,aliases:[],name:t.name||null,title:t.title||null,company:t.company||null,location:t.location||null,role:t.role||null,source:t.source||"scout",isConnected:t.isConnected||!1,discoveredAt:r,lastSeen:r,seenCount:1,jobIds:t.jobId?[t.jobId]:[]};try{xe(vt,o)}catch(s){console.error(`[!] Failed to save discovered-people.json: ${s.message}`)}}var ie=null;function $o(){return ie||(ie=ye(At)||{},ie)}function Ct(e,t){if(!e)return;Ee();let o=$o(),r=new Date().toISOString().slice(0,10);if(o[e]){let n=o[e];t.name&&(n.name=t.name),t.about&&(n.about=t.about),t.size&&(n.size=t.size),t.industries&&(n.industries=t.industries),t.jobId&&(n.jobIds||(n.jobIds=[]),n.jobIds.includes(t.jobId)||n.jobIds.push(t.jobId)),t.recruiterUrl&&(n.recruiterUrls||(n.recruiterUrls=[]),n.recruiterUrls.includes(t.recruiterUrl)||n.recruiterUrls.push(t.recruiterUrl)),n.lastSeen=r,n.jobCount=n.jobIds?.length||0}else o[e]={name:t.name||null,about:t.about||null,size:t.size||null,industries:t.industries||null,discoveredAt:r,lastSeen:r,jobIds:t.jobId?[t.jobId]:[],recruiterUrls:t.recruiterUrl?[t.recruiterUrl]:[],jobCount:t.jobId?1:0};try{xe(At,o)}catch(n){console.error(`[!] Failed to save companies.json: ${n.message}`)}}var K=null;function Io(){return K||(K=ye(jo)||{visits:[]},Array.isArray(K.visits)||(K.visits=[]),K)}function Tt(){let e=ge(),t=xt(),o=Object.values(e),r=Object.values(t),n={};for(let f of o)f.company&&(n[f.company]=(n[f.company]||0)+1);let i=Object.entries(n).sort((f,d)=>d[1]-f[1]).slice(0,5).map(([f,d])=>`${f} (${d})`),s={};for(let f of o)for(let d of f.techStack||[])s[d]=(s[d]||0)+1;let c=Object.entries(s).sort((f,d)=>d[1]-f[1]).slice(0,8).map(([f,d])=>`${f} (${d})`),l=Io(),a=new Date().toISOString().slice(0,10),u=l.visits.filter(f=>f.date.startsWith(a)).length,m=new Set(l.visits.map(f=>f.profileUrl)).size;return{totalJobs:o.length,totalRecruiters:r.length,topCompanies:i,topTech:c,totalVisited:m,todayVisited:u,lastScoutDate:o.length>0?o.sort((f,d)=>(d.scoutedAt||"").localeCompare(f.scoutedAt||""))[0]?.scoutedAt:null}}import"dotenv/config";import*as k from"fs";import*as v from"path";import{fileURLToPath as Ro}from"url";var Do=Ro(import.meta.url),Oo=v.dirname(v.dirname(Do)),q=process.env.DATA_DIR?v.resolve(process.env.DATA_DIR,"collected-profiles"):v.join(Oo,"collected-profiles"),No=v.join(q,"people.json"),Lo=v.join(q,"jobs.json"),Dr=v.join(q,"quota.json"),Or=v.join(q,"conversations.json"),Nr=v.join(q,"sync-state.json"),Lr=v.join(q,"application-questions.json"),Pr=v.join(q,"profile-history"),$t=(e,t)=>{let o=parseInt(e,10);return Number.isInteger(o)&&o>=0?o:t},Fr=$t(process.env.CONNECT_MAX_DAILY,20),Mr=$t(process.env.CONNECT_MAX_WEEKLY,100),ce=null,le=null,Po=null,Fo=null,Mo=null,Uo=null;function It(){ce=null,le=null,Po=null,Fo=null,Mo=null,Uo=null}function Rt(){k.existsSync(q)||k.mkdirSync(q,{recursive:!0})}function Dt(e,t){if(!k.existsSync(e))return null;try{let o=JSON.parse(k.readFileSync(e,"utf-8"));try{k.copyFileSync(e,e+".backup")}catch{}return o}catch(o){console.error(`[!] ${t} is corrupted: ${o.message}`),console.error(` File: ${v.resolve(e)}`);let r=e+".backup";if(k.existsSync(r))try{let n=JSON.parse(k.readFileSync(r,"utf-8"));console.error(` Restored from ${r}`);try{k.copyFileSync(r,e)}catch{}return n}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{k.copyFileSync(e,e+".corrupted")}catch{}return null}}function Ot(){return ce||(Rt(),ce=Dt(No,"people.json")||{},ce)}function Nt(){return le||(Rt(),le=Dt(Lo,"jobs.json")||{},le)}import"dotenv/config";import*as I from"fs";import*as H from"path";import{fileURLToPath as Wo}from"url";import"dotenv/config";import{createGraphClient as qo,resolveToken as Bo}from"@ilivemylife/graph-sdk";import{config as Jo}from"dotenv";Jo();var Lt=Bo()||process.env.TOKEN;Lt||(console.error(`
|
|
4
5
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
5
6
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
6
7
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
7
|
-
`),process.exit(1));var
|
|
8
|
+
`),process.exit(1));var Pt=qo({token:Lt});function Ho(e){if(!e||e<1e3)return`${e||0}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let o=Math.floor(t/60),r=t%60;return r?`${o}m ${r}s`:`${o}m`}function Go({scriptName:e,mode:t,status:o,error:r,duration:n}){let i=o==="error"?"\u2717":o==="quota-reached"?"\u26A0":"\u2713",s=new Date().toISOString().slice(0,16).replace("T"," "),c=n?` ${Ho(n)}`:"",l=o==="error"?`error${r?`: ${String(r).slice(0,80)}`:""}`:o==="quota-reached"?"daily quota reached":"done",a=t&&t!=="default"?` (${t})`:"";return`${i} ${e}${a} \u2014 ${l} \u2014 ${s}${c}`}async function Ft({scriptName:e,mode:t,status:o,summaryLines:r,error:n,duration:i}){let s=process.env.NODE_RUN_REPORTS;if(!s||!Array.isArray(r)||r.length===0)return;let l=`**${Go({scriptName:e,mode:t,status:o,error:n,duration:i})}**
|
|
8
9
|
|
|
9
|
-
${
|
|
10
|
-
`)}`;try{await Ot.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Bo=qo(import.meta.url),Jo=J.dirname(J.dirname(Bo)),xe=process.env.DATA_DIR?J.resolve(process.env.DATA_DIR,"collected-profiles"):J.join(Jo,"collected-profiles"),Ce=J.join(xe,"run-log.json");function Ho(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";C.writeFileSync(n,o);for(let r=0;r<3;r++)try{C.renameSync(n,e);return}catch(i){if(r<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Lt(){try{if(!C.existsSync(Ce))return{runs:[]};let e=JSON.parse(C.readFileSync(Ce,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ft(e){C.existsSync(xe)||C.mkdirSync(xe,{recursive:!0});try{Ho(Ce,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function Pt(e,t="default"){let o=Lt();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let n=new Date,r={timestamp:n.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(r);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),Ft(o),{script:e,mode:t,startTime:n.getTime(),runIndex:o.runs.length-1}}function $e(e,t,o=null,n=null){if(!e)return;let r=null;try{let s=Lt(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=n,r=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=n,r=l.duration)}Ft(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Nt({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:n,duration:r??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as u from"fs";import*as Fe from"os";import*as y from"path";import{fileURLToPath as hn}from"url";var Re={};ue(Re,{NAME:()=>Go,VERSION:()=>Wo,up:()=>Yo});import*as $ from"fs";import*as ye from"path";var Wo=1,Go="normalize-jobs-and-questions",Vo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Ko=50;function Te(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Ie(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{$.writeFileSync(n,o)}catch(r){try{$.unlinkSync(n)}catch{}throw r}try{$.renameSync(n,e)}catch(r){try{$.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function Yo(e,t){let o=ye.join(e,"jobs.json"),n=ye.join(t,"scouted-jobs.json"),r=ye.join(e,"application-questions.json"),i=Te(o)||{},s=Te(n)||{},c=0,l=[];for(let p of Object.keys(i)){if(!s[p])continue;let m=s[p],f=i[p];for(let d of Vo)m[d]!=null&&f[d]==null&&(f[d]=m[d]);l.push(p),c++}c>0?(Ie(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=Te(r);if(a&&Array.isArray(a.applications)){let p={},m=0;for(let f of a.applications){let d=f.jobId||"unknown";p[d]||(p[d]={applications:[]});let _=(f.questions||[]).map(S=>{let w={type:S.type||"input",question:S.question||"",answer:S.answer||""};return S.options&&(S.options.length<=Ko?w.options=S.options:(w.optionsOmitted=!0,m++)),S.page&&(w.page=S.page),S.wasPreFilled&&(w.wasPreFilled=!0),S.wasRetry&&(w.wasRetry=!0),w});p[d].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||_.length,questions:_})}Ie(r,p),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} 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(l.length>0){for(let p of l)delete s[p];Ie(n,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var De={};ue(De,{NAME:()=>Qo,VERSION:()=>zo,up:()=>en});import*as T from"fs";import*as Mt from"path";var zo=2,Qo="reset-unread-flags";function Xo(e){return T.existsSync(e)?JSON.parse(T.readFileSync(e,"utf-8")):null}function Zo(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{T.writeFileSync(n,o)}catch(r){try{T.unlinkSync(n)}catch{}throw r}try{T.renameSync(n,e)}catch(r){try{T.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function en(e){let t=Mt.join(e,"conversations.json"),o=Xo(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let r of Object.keys(o))o[r].unread===!0&&(o[r].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Zo(t,o),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Oe={};ue(Oe,{NAME:()=>on,VERSION:()=>tn,up:()=>ln});import*as I from"fs";import*as Ut from"path";var tn=3,on="recompute-last-message-by",nn=new Set(["draft","confirmed","rejected","needs_review"]);function rn(e){return I.existsSync(e)?JSON.parse(I.readFileSync(e,"utf-8")):null}function sn(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{I.writeFileSync(n,o)}catch(r){try{I.unlinkSync(n)}catch{}throw r}try{I.renameSync(n,e)}catch(r){try{I.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}function cn(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!nn.has(i.status));if(o.length===0)return"them";let n=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),r=n.length>0?n:[...o].reverse();for(let i of r){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function ln(e){let t=Ut.join(e,"conversations.json"),o=rn(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let n=process.env.LINKEDIN_NAME;if(!n||typeof n!="string"||!n.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let r=0,i=0,s=0;for(let c of Object.keys(o)){let l=o[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],p=cn(a,n),m=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&s++,l.lastMessageBy=p,l.conversationStatus=m,r++}if(r===0){console.log(" No conversations to recompute.");return}sn(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ne={};ue(Ne,{NAME:()=>un,VERSION:()=>an,up:()=>mn});import*as R from"fs";import*as qt from"path";var an=4,un="split-connection-timestamps",fn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function pn(e){if(!R.existsSync(e))return null;let t=R.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function dn(e,t){let o=JSON.stringify(t,null,2),n=e+".tmp";try{R.writeFileSync(n,o)}catch(r){try{R.unlinkSync(n)}catch{}throw r}try{R.renameSync(n,e)}catch(r){try{R.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let i=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=r.code,i}throw r}}async function mn(e){let t=qt.join(e,"people.json"),o=pn(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,r=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(r++,fn.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}dn(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${n} still-pending people (of ${r} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var yn=hn(import.meta.url),gn=y.dirname(yn),Sn=y.dirname(y.dirname(gn));function bn(e){return e&&(e==="~"?Fe.homedir():e.startsWith("~/")||e.startsWith("~\\")?y.join(Fe.homedir(),e.slice(2)):e)}var N=process.env.DATA_DIR?y.resolve(bn(process.env.DATA_DIR)):Sn,z=y.join(N,"collected-profiles"),Q=y.join(N,"market-research"),A=y.join(N,".schema-version"),Bt=[y.join(z,".schema-version"),y.join(Q,".schema-version")],H=4,M=[{version:1,module:Re},{version:2,module:De},{version:3,module:Oe},{version:4,module:Ne}];(function(){M.sort((n,r)=>n.version-r.version);let t=new Set;for(let n of M){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(t.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);t.add(n.version);let r=n.module;if(!r||typeof r.up!="function")throw new Error(`MIGRATION_REGISTRY: v${n.version} module is missing up()`);if(r.VERSION!==void 0&&r.VERSION!==n.version)throw new Error(`MIGRATION_REGISTRY: v${n.version} entry does not match module VERSION (${r.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=M.length?M[M.length-1].version:0;if(o!==H)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${H}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<M.length;n++){let r=n+1;if(M[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${M[n].version}`)}})();function Gt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
10
|
+
${r.join(`
|
|
11
|
+
`)}`;try{await Pt.addMessage(s,l)}catch(a){console.error(`[runReport] Failed to post end-of-session message: ${a.message}`)}}var Vo=Wo(import.meta.url),Ko=H.dirname(H.dirname(Vo)),je=process.env.DATA_DIR?H.resolve(process.env.DATA_DIR,"collected-profiles"):H.join(Ko,"collected-profiles"),Ce=H.join(je,"run-log.json");function Yo(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";I.writeFileSync(r,o);for(let n=0;n<3;n++)try{I.renameSync(r,e);return}catch(i){if(n<2&&(i.code==="EPERM"||i.code==="EBUSY")){let s=Date.now();for(;Date.now()-s<200;);continue}throw i}}function Mt(){try{if(!I.existsSync(Ce))return{runs:[]};let e=JSON.parse(I.readFileSync(Ce,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ut(e){I.existsSync(je)||I.mkdirSync(je,{recursive:!0});try{Yo(Ce,e)}catch(t){console.error(`[!] Failed to save run-log.json: ${t.message}`)}}function qt(e,t="default"){let o=Mt();for(let s of o.runs)s.status==="running"&&(s.status="interrupted",s.result="interrupted",s.timestamp&&(s.duration=Date.now()-new Date(s.timestamp).getTime()));let r=new Date,n={timestamp:r.toISOString(),script:e,mode:t,status:"running",result:null,duration:null,stats:null,error:null};o.runs.push(n);let i=Date.now()-30*24*60*60*1e3;return o.runs=o.runs.filter(s=>new Date(s.timestamp).getTime()>i),Ut(o),{script:e,mode:t,startTime:r.getTime(),runIndex:o.runs.length-1}}function Te(e,t,o=null,r=null){if(!e)return;let n=null;try{let s=Mt(),c=s.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=t,c.result=t,c.duration=Date.now()-e.startTime,c.stats=o,c.error=r,n=c.duration;else{let l=s.runs.find(a=>a.script===e.script&&a.status==="running"&&a.timestamp===new Date(e.startTime).toISOString());l&&(l.status=t,l.result=t,l.duration=Date.now()-e.startTime,l.stats=o,l.error=r,n=l.duration)}Ut(s)}catch(s){console.error(`[runLog] Failed to end run: ${s.message}`)}let i=o&&Array.isArray(o.summaryLines)?o.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let s=t==="error"?"error":o&&o.dailyLimitHit?"quota-reached":"done";Ft({scriptName:e.script,mode:e.mode,status:s,summaryLines:i,error:r,duration:n??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as p from"fs";import*as Pe from"os";import*as y from"path";import{fileURLToPath as wn}from"url";var Re={};pe(Re,{NAME:()=>Qo,VERSION:()=>zo,up:()=>en});import*as R from"fs";import*as Se from"path";var zo=1,Qo="normalize-jobs-and-questions",Xo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Zo=50;function $e(e){return R.existsSync(e)?JSON.parse(R.readFileSync(e,"utf-8")):null}function Ie(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{R.writeFileSync(r,o)}catch(n){try{R.unlinkSync(r)}catch{}throw n}try{R.renameSync(r,e)}catch(n){try{R.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function en(e,t){let o=Se.join(e,"jobs.json"),r=Se.join(t,"scouted-jobs.json"),n=Se.join(e,"application-questions.json"),i=$e(o)||{},s=$e(r)||{},c=0,l=[];for(let u of Object.keys(i)){if(!s[u])continue;let m=s[u],f=i[u];for(let d of Xo)m[d]!=null&&f[d]==null&&(f[d]=m[d]);l.push(u),c++}c>0?(Ie(o,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let a=$e(n);if(a&&Array.isArray(a.applications)){let u={},m=0;for(let f of a.applications){let d=f.jobId||"unknown";u[d]||(u[d]={applications:[]});let b=(f.questions||[]).map(g=>{let w={type:g.type||"input",question:g.question||"",answer:g.answer||""};return g.options&&(g.options.length<=Zo?w.options=g.options:(w.optionsOmitted=!0,m++)),g.page&&(w.page=g.page),g.wasPreFilled&&(w.wasPreFilled=!0),g.wasRetry&&(w.wasRetry=!0),w});u[d].applications.push({applicationId:f.applicationId,date:f.date,result:f.result||"submitted",formPages:f.formPages||null,duration:f.duration||null,retries:f.retries||0,failedField:f.failedField||null,questionCount:f.questionCount||b.length,questions:b})}Ie(n,u),console.log(` Phase 2: Rekeyed ${a.applications.length} applications by jobId (${Object.keys(u).length} unique jobs)`),m>0&&console.log(` Phase 2: Stripped bloated options from ${m} 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(l.length>0){for(let u of l)delete s[u];Ie(r,s),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(s).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var De={};pe(De,{NAME:()=>on,VERSION:()=>tn,up:()=>sn});import*as D from"fs";import*as Bt from"path";var tn=2,on="reset-unread-flags";function nn(e){return D.existsSync(e)?JSON.parse(D.readFileSync(e,"utf-8")):null}function rn(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{D.writeFileSync(r,o)}catch(n){try{D.unlinkSync(r)}catch{}throw n}try{D.renameSync(r,e)}catch(n){try{D.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function sn(e){let t=Bt.join(e,"conversations.json"),o=nn(t);if(!o){console.log(" conversations.json not found \u2014 nothing to reset.");return}let r=0;for(let n of Object.keys(o))o[n].unread===!0&&(o[n].unread=!1,r++);if(r===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}rn(t,o),console.log(` Reset unread=false on ${r} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var Oe={};pe(Oe,{NAME:()=>ln,VERSION:()=>cn,up:()=>dn});import*as O from"fs";import*as Jt from"path";var cn=3,ln="recompute-last-message-by",an=new Set(["draft","confirmed","rejected","needs_review"]);function un(e){return O.existsSync(e)?JSON.parse(O.readFileSync(e,"utf-8")):null}function fn(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{O.writeFileSync(r,o)}catch(n){try{O.unlinkSync(r)}catch{}throw n}try{O.renameSync(r,e)}catch(n){try{O.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}function pn(e,t){if(!e||e.length===0)return"them";let o=e.filter(i=>!an.has(i.status));if(o.length===0)return"them";let r=o.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,s)=>s.t-i.t).map(i=>i.m),n=r.length>0?r:[...o].reverse();for(let i of n){let s=i.sender;if(s===t)return"me";if(s!=="Unknown"&&s!=="")return"them"}return"them"}async function dn(e){let t=Jt.join(e,"conversations.json"),o=un(t);if(!o){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let r=process.env.LINKEDIN_NAME;if(!r||typeof r!="string"||!r.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let n=0,i=0,s=0;for(let c of Object.keys(o)){let l=o[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let a=Array.isArray(l.messages)?l.messages:[],u=pn(a,r),m=u==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==u&&s++,l.lastMessageBy=u,l.conversationStatus=m,n++}if(n===0){console.log(" No conversations to recompute.");return}fn(t,o),console.log(` Recomputed lastMessageBy + conversationStatus on ${n} conversations.`),console.log(` ${s} had stale lastMessageBy (now corrected).`),i>0&&console.log(` Cleaned ${i} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Ne={};pe(Ne,{NAME:()=>hn,VERSION:()=>mn,up:()=>bn});import*as N from"fs";import*as Ht from"path";var mn=4,hn="split-connection-timestamps",yn=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function gn(e){if(!N.existsSync(e))return null;let t=N.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Sn(e,t){let o=JSON.stringify(t,null,2),r=e+".tmp";try{N.writeFileSync(r,o)}catch(n){try{N.unlinkSync(r)}catch{}throw n}try{N.renameSync(r,e)}catch(n){try{N.unlinkSync(r)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let i=new Error(`File locked: ${e} (${n.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=n.code,i}throw n}}async function bn(e){let t=Ht.join(e,"people.json"),o=gn(t);if(!o||typeof o!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let r=0,n=0;for(let i of Object.keys(o)){let s=o[i];!s||typeof s!="object"||(n++,yn.has(s.connectionStatus)&&s.connectionDate&&!s.requestedConnectionAt&&(s.requestedConnectionAt=s.connectionDate,s.connectionDate=null,r++))}if(r===0){console.log(` Scanned ${n} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Sn(t,o),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${r} still-pending people (of ${n} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var kn=wn(import.meta.url),vn=y.dirname(kn),An=y.dirname(y.dirname(vn));function _n(e){return e&&(e==="~"?Pe.homedir():e.startsWith("~/")||e.startsWith("~\\")?y.join(Pe.homedir(),e.slice(2)):e)}var M=process.env.DATA_DIR?y.resolve(_n(process.env.DATA_DIR)):An,Q=y.join(M,"collected-profiles"),X=y.join(M,"market-research"),E=y.join(M,".schema-version"),Gt=[y.join(Q,".schema-version"),y.join(X,".schema-version")],G=4,B=[{version:1,module:Re},{version:2,module:De},{version:3,module:Oe},{version:4,module:Ne}];(function(){B.sort((r,n)=>r.version-n.version);let t=new Set;for(let r of B){if(!Number.isInteger(r.version)||r.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(r.version)} (must be positive integer)`);if(t.has(r.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${r.version}`);t.add(r.version);let n=r.module;if(!n||typeof n.up!="function")throw new Error(`MIGRATION_REGISTRY: v${r.version} module is missing up()`);if(n.VERSION!==void 0&&n.VERSION!==r.version)throw new Error(`MIGRATION_REGISTRY: v${r.version} entry does not match module VERSION (${n.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let o=B.length?B[B.length-1].version:0;if(o!==G)throw new Error(`MIGRATION_REGISTRY: highest version v${o} but CURRENT_SCHEMA_VERSION=${G}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let r=0;r<B.length;r++){let n=r+1;if(B[r].version!==n)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${n} at position ${r} but found v${B[r].version}`)}})();function Yt(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
11
12
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
12
|
-
`),process.exit(1));try{
|
|
13
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
14
|
-
`),process.exit(1))}let e;try{e=
|
|
15
|
-
[FATAL] DATA_DIR (${
|
|
13
|
+
`),process.exit(1));try{p.mkdirSync(M,{recursive:!0})}catch(t){t.code!=="EEXIST"&&(console.error(`
|
|
14
|
+
[FATAL] Cannot create DATA_DIR (${M}): ${t.message}`),console.error(` Fix the path or permissions and try again.
|
|
15
|
+
`),process.exit(1))}let e;try{e=p.statSync(M)}catch(t){console.error(`
|
|
16
|
+
[FATAL] DATA_DIR (${M}) is not accessible: ${t.message}
|
|
16
17
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
17
|
-
[FATAL] DATA_DIR (${
|
|
18
|
-
`),process.exit(1));for(let t of[
|
|
18
|
+
[FATAL] DATA_DIR (${M}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
19
|
+
`),process.exit(1));for(let t of[Q,X]){let o;try{o=p.lstatSync(t)}catch(r){if(r.code==="ENOENT")continue;throw r}o.isSymbolicLink()&&(console.error(`
|
|
19
20
|
[FATAL] Data subdirectory is a symbolic link: ${t}`),console.error(" Refusing to follow \u2014 backup code would copy whatever the link points at."),console.error(` If this is intentional, replace the symlink with the real directory.
|
|
20
|
-
`),process.exit(1))}}var
|
|
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: ${
|
|
21
|
+
`),process.exit(1))}}var z=y.join(M,".migration-lock");function En(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return p.writeFileSync(z,e,{flag:"wx"}),!0}catch(r){if(r.code!=="EEXIST")throw r}let t;try{t=JSON.parse(p.readFileSync(z,"utf-8"))}catch{t=null}if(t&&Number.isInteger(t.pid)){let r=!1;try{process.kill(t.pid,0),r=!0}catch(s){s.code==="EPERM"&&(r=!0)}let n=24*60*60*1e3,i=1/0;if(t.startedAt){let s=Date.parse(t.startedAt);Number.isNaN(s)||(i=Date.now()-s)}r&&i<n&&(console.error(`
|
|
22
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${t.pid}`),console.error(` Started at: ${t.startedAt||"(unknown)"}`),console.error(` Lock file: ${z}
|
|
22
23
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
23
|
-
`),process.exit(1)),
|
|
24
|
+
`),process.exit(1)),r&&i>=n&&console.log(` Lock holder PID ${t.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${t?.pid??"?"} found \u2014 taking over.`);let o=z+".tmp";try{return p.writeFileSync(o,e),p.renameSync(o,z),!0}catch(r){try{p.unlinkSync(o)}catch{}throw new Error(`Failed to take over stale migration lock: ${r.message}`)}}function Fe(){try{if(JSON.parse(p.readFileSync(z,"utf-8")).pid!==process.pid)return;p.unlinkSync(z)}catch{}}var Wt=!1;function xn(){if(Wt)return;Wt=!0;let e=()=>{try{Fe()}catch{}process.exit(1)};for(let t of["SIGINT","SIGTERM","SIGHUP"])try{process.on(t,e)}catch{}}function jn(){if(p.existsSync(E))return;let e=[],t=[];for(let i of Gt)if(p.existsSync(i))try{e.push({file:i,schema:be(i)})}catch(s){t.push({file:i,err:s.message})}if(t.length>0){console.error(`
|
|
24
25
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of t)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
25
26
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
26
27
|
`),process.exit(1)}if(e.length===0)return;let o=e.map(i=>i.schema.version);if(new Set(o).size>1){console.error(`
|
|
27
28
|
[FATAL] Legacy .schema-version files disagree:`);for(let i of e)console.error(` ${i.file}: v${i.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
|
|
29
|
-
[FATAL] ${
|
|
30
|
-
`),process.exit(1)}let t=
|
|
31
|
-
[FATAL] ${
|
|
32
|
-
`),process.exit(1)),t}function
|
|
33
|
-
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${
|
|
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${
|
|
29
|
+
`),process.exit(1)}let r=e[0].schema,n=E+".tmp";try{p.writeFileSync(n,JSON.stringify(r,null,2)),p.renameSync(n,E)}catch(i){try{p.unlinkSync(n)}catch{}throw i}for(let i of Gt)if(p.existsSync(i))try{p.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${E}`)}function Cn(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.version);return!Number.isFinite(t)||t<0||!Number.isInteger(t)?null:(e.version=t,Array.isArray(e.migrations)||(e.migrations=[]),e)}function be(e){let t=p.readFileSync(e,"utf-8");return t.charCodeAt(0)===65279&&(t=t.slice(1)),JSON.parse(t)}function Vt(){if(jn(),!p.existsSync(E))return{version:0,migrations:[]};let e;try{e=be(E)}catch(o){if(o.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
30
|
+
[FATAL] ${E} is not valid JSON: ${o.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
31
|
+
`),process.exit(1)}let t=Cn(e);return t===null&&(console.error(`
|
|
32
|
+
[FATAL] ${E} has invalid structure:`),console.error(` ${JSON.stringify(e)?.slice(0,200)||"(unparseable)"}`),console.error(' Expected shape: { "version": <integer>, "migrations": [...] }'),console.error(` Repair the file or restore from a backup.
|
|
33
|
+
`),process.exit(1)),t}function zt(e){try{p.chmodSync(e,384)}catch{}}function Tn(e){if(Yt(),p.existsSync(E))try{if(p.lstatSync(E).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${E}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(o){if(o.message?.includes("symbolic link"))throw o}let t=E+".tmp";try{p.writeFileSync(t,JSON.stringify(e,null,2)),zt(t),p.renameSync(t,E)}catch(o){try{p.unlinkSync(t)}catch{}throw o}}function Kt(e,t){if(!p.existsSync(e))return;let o=`.pre-v${String(t).padStart(3,"0")}.backup`,r=p.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return p.statSync(y.join(e,c)).isFile()}catch{return!1}}),n=0,i=0,s=[];for(let c of r){let l=y.join(e,c),a=y.join(e,c+o);if(p.existsSync(a)){i++;continue}try{Xt(l,a),n++}catch(u){s.push({file:c,err:u.message})}}if(s.length>0){let c=new Error(`Failed to back up ${s.length} file(s) in ${y.basename(e)}/: `+s.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(n>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${n} files in ${y.basename(e)}/ (${o})${c}`)}}var Le=!1;async function Qt(){if(Le)return;Yt(),On();let t=Vt().version;if(t===G){Le=!0;return}xn(),En(),process.on("exit",Fe),t>G&&(console.error(`
|
|
34
|
+
[FATAL] Your data schema is at v${t}, but this plugin build only understands up to v${G}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
35
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${G}.
|
|
35
36
|
`),process.exit(1)),console.log(`
|
|
36
|
-
\u{1F4E6} Schema migration: v${t} \u2192 v${
|
|
37
|
-
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let
|
|
37
|
+
\u{1F4E6} Schema migration: v${t} \u2192 v${G}`);let o=Nn();if(!o.ok){console.error(`
|
|
38
|
+
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let n of o.broken)console.error(` ${n.dir}/${n.file}: ${n.err}`);console.error(`
|
|
38
39
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
39
|
-
`),process.exit(1)}let
|
|
40
|
-
Running migration v${String(
|
|
40
|
+
`),process.exit(1)}let r=B.filter(n=>n.version>t);for(let n of r){console.log(`
|
|
41
|
+
Running migration v${String(n.version).padStart(3,"0")}...`);let i=`v${String(n.version).padStart(3,"0")}`,s=`.pre-${i}.backup`;try{Kt(Q,n.version),Kt(X,n.version)}catch(l){console.error(`
|
|
41
42
|
[FATAL] Pre-migration backup failed for ${i}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
42
|
-
`),process.exit(1)}let c=
|
|
43
|
-
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=
|
|
43
|
+
`),process.exit(1)}let c=n.module;try{await c.up(Q,X)}catch(l){console.error(`
|
|
44
|
+
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${s} files...`);try{let a=Ln(s);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
45
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${a.error}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
45
46
|
`))}catch(a){console.error(` [!] Auto-rollback CRASHED while restoring: ${a.message}`),console.error(` Manual recovery: copy *${s} files back over the originals.
|
|
46
|
-
`)}process.exit(1)}try{let l=new Date().toISOString(),a={version:
|
|
47
|
-
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${
|
|
48
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{
|
|
49
|
-
\u2713 Schema is now at v${
|
|
50
|
-
`)}var
|
|
47
|
+
`)}process.exit(1)}try{let l=new Date().toISOString(),a={version:n.version,name:c.NAME||i,appliedAt:l},u=Vt();u.version=n.version,u.migratedAt=l,u.migrations=u.migrations||[],u.migrations.push(a),Tn(u)}catch(l){console.error(`
|
|
48
|
+
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${n.version} state but .schema-version still shows v${t}.`),console.error(` On next plugin command the runner will try to re-apply ${i}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
49
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{It()}catch{}try{_t()}catch{}Le=!0,Fe(),console.log(`
|
|
50
|
+
\u2713 Schema is now at v${G}
|
|
51
|
+
`)}var $n=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function In(e){let t=e.toLowerCase();return $n.some(o=>o.test(t))}var Rn=6e4;function Dn(){let e=Date.now(),t=[];for(let o of[M,Q,X]){if(!p.existsSync(o))continue;let r;try{r=p.readdirSync(o)}catch{continue}for(let n of r){if(!In(n))continue;let i=y.join(o,n);try{let s=p.statSync(i);if(!s.isFile()||e-s.mtimeMs<Rn)continue;t.push({dir:o,file:n,fullPath:i})}catch{}}}return t}function On({verbose:e=!1}={}){let t=Dn();if(t.length===0)return e&&console.log(" No orphan .tmp files found."),0;let o=0;for(let r of t)try{p.unlinkSync(r.fullPath),o++,e&&console.log(` Removed orphan: ${y.basename(r.dir)}/${r.file}`)}catch(n){console.warn(` [!] Could not remove orphan ${r.fullPath}: ${n.message}`)}return!e&&o>0&&console.log(` Cleaned up ${o} orphan .tmp file(s) from previous run.`),o}function Nn(){let e=[];for(let t of[Q,X]){if(!p.existsSync(t))continue;let o=p.readdirSync(t).filter(r=>{let n=r.toLowerCase();return n.endsWith(".json")&&!n.includes(".backup")});for(let r of o){let n=y.join(t,r);try{be(n)}catch(i){e.push({dir:y.basename(t),file:r,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function Ln(e){let t=[],o=[];for(let i of[Q,X]){if(!p.existsSync(i))continue;let s=p.readdirSync(i).filter(c=>c.endsWith(e));for(let c of s){let l=y.join(i,c),a=c.slice(0,-e.length),u=y.join(i,a);try{a.toLowerCase().endsWith(".json")?be(l):p.accessSync(l,p.constants.R_OK),t.push({backupPath:l,originalPath:u,fileName:c,dir:i})}catch(m){o.push(`${y.basename(i)}/${c}: ${m.message}`)}}}if(o.length>0)return{ok:!1,error:o.join("; "),restored:0};let r=0,n=[];for(let{backupPath:i,originalPath:s,fileName:c,dir:l}of t)try{Xt(i,s),r++}catch(a){n.push(`${y.basename(l)}/${c}: ${a.message}`)}return n.length>0?{ok:!1,error:n.join("; "),restored:r}:{ok:!0,restored:r}}function Xt(e,t){let o=t+".tmp";try{p.copyFileSync(e,o),zt(o)}catch(r){try{p.unlinkSync(o)}catch{}throw r}try{p.renameSync(o,t)}catch(r){try{p.unlinkSync(o)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let n=new Error(`File locked: ${t} (${r.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw n.code=r.code,n}throw r}}await Qt();var ae=process.argv.slice(2),ee=parseInt(ae.find(e=>e.startsWith("--max="))?.split("=")[1]||"200"),Zt=parseInt(ae.find(e=>e.startsWith("--pages="))?.split("=")[1]||"20"),eo=ae.find(e=>e.startsWith("--url="))?.split("=").slice(1).join("="),Pn=ae.includes("--list"),Me=ae.includes("--verbose");function Fn(){if(eo)return[eo];let e=process.env.LINKEDIN_SCOUT_URLS;if(e)return e.split(",").map(o=>o.trim()).filter(Boolean);let t=process.env.LINKEDIN_SEARCH_URL;return t?[t]:[]}function Mn(){let e=Tt();console.log(`
|
|
51
52
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" MARKET RESEARCH STATS"),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(` Scouted jobs: ${e.totalJobs}`),console.log(` Discovered recruiters: ${e.totalRecruiters}`),console.log(` Last scout: ${e.lastScoutDate||"never"}`),console.log(` Profile visits: ${e.totalVisited} unique (${e.todayVisited} today)`),e.topTech.length>0&&console.log(` Top tech: ${e.topTech.join(", ")}`),e.topCompanies.length>0&&console.log(` Top companies: ${e.topCompanies.join(", ")}`),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
|
|
52
|
-
`)}async function
|
|
53
|
+
`)}async function Un(){if(console.log(`
|
|
53
54
|
LinkedIn Job Scout
|
|
54
|
-
`),
|
|
55
|
-
`);let{browser:s,page:c}=await
|
|
56
|
-
\u2550\u2550\u2550 Scout URL ${o.urlsProcessed}/${e.length}: ${l.slice(0,70)}... \u2550\u2550\u2550`),await c.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let a=0,
|
|
57
|
-
\u2500\u2500 Page ${m+1} \u2500\u2500`),await
|
|
55
|
+
`),Pn){Mn();return}let e=Fn();e.length===0&&(console.error("No search URL. Set LINKEDIN_SCOUT_URL or LINKEDIN_SCOUT_URLS in .env, or use --url=..."),process.exit(1));let t=qt("scout",`max=${ee},urls=${e.length}`),o={scouted:0,recruitersFound:0,skipped:0,skippedApplied:0,alreadyConnected:0,pages:0,errors:0,urlsProcessed:0},r=ge(),n=Nt(),i=Ot();console.log(` Scout URLs: ${e.length}`),e.forEach((l,a)=>console.log(` ${a+1}. ${l.slice(0,80)}...`)),console.log(` Max jobs: ${ee} | Max pages per URL: ${Zt}
|
|
56
|
+
`);let{browser:s,page:c}=await dt();try{for(let l of e){if(o.scouted>=ee)break;o.urlsProcessed++,console.log(`
|
|
57
|
+
\u2550\u2550\u2550 Scout URL ${o.urlsProcessed}/${e.length}: ${l.slice(0,70)}... \u2550\u2550\u2550`),await c.goto(l,{waitUntil:"domcontentloaded",timeout:6e4}),await j(3e3);let a=0,u=!1;for(let m=0;m<Zt&&o.scouted<ee&&!u;m++){o.pages++,console.log(`
|
|
58
|
+
\u2500\u2500 Page ${m+1} \u2500\u2500`),await gt(c,l),await mt(c),await j(1e3);let f=await ht(c,{easyApplyOnly:!1});console.log(` Found ${f.length} jobs on page`);for(let d of f){if(o.scouted>=ee)break;let b=d.href?.match(/jobs\/view\/(\d+)/)?.[1]||d.id?.match(/\d+/)?.[0];if(b&&r[b]){o.skipped++;continue}if(b&&n[b]){o.skippedApplied++;continue}try{let g=await c.$(`a[data-control-id="${d.dataId}"]`);if(!g)continue;let w=await c.evaluate(()=>document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24")?.innerText?.trim()?.slice(0,80)||"");await g.click(),await j(1500+Math.random()*1500);for(let T=0;T<8;T++){let L=await c.evaluate(te=>{let Z=document.querySelector(".job-details-jobs-unified-top-card__job-title, .jobs-unified-top-card__job-title, h2.t-24"),x=document.querySelector(".jobs-description__content"),ue=Z?.innerText?.trim()?.slice(0,80)||"",we=x?.innerText?.trim()?.length||0;return{title:ue,descLen:we,titleChanged:ue!==te&&ue.length>0}},w);if(L.titleChanged&&L.descLen>50)break;await j(600)}let S=await bt(c),A=await St(c);if(b&&(Et(b,{title:d.jobTitle,company:S.companyName||d.companyName,companyUrl:S.companyUrl,location:d.location,salary:d.salary,url:d.href,isEasyApply:d.isEasyApply,applyType:d.applyType||(d.isEasyApply?"easy-apply":"external"),externalApplyUrl:S.externalApplyUrl,description:S.description,techStack:S.techStack,jobTags:S.jobTags,seniority:S.seniority,employmentType:S.employmentType,industries:S.industries,jobFunction:S.jobFunction,postedTime:S.postedTime,applicantCount:S.applicantCount,companySize:S.companySize,workplaceType:S.workplaceType,contractType:S.contractType,recruiterUrl:A?.profileUrl||null}),o.scouted++),S.companyUrl&&Ct(S.companyUrl,{name:S.companyName||d.companyName,about:S.aboutCompany,size:S.companySize,industries:S.industries,jobId:b,recruiterUrl:A?.profileUrl}),A?.profileUrl){let L=i[A.profileUrl]?.connectionStatus==="connected";jt(A.profileUrl,{name:A.name,source:"scout",role:"recruiter",jobId:b,jobTitle:d.jobTitle,isConnected:L}),o.recruitersFound++,L&&o.alreadyConnected++}if(Me){let T=S.techStack?.slice(0,5).join(", ")||"none";console.log(` [${o.scouted}] ${d.jobTitle?.slice(0,40)} @ ${d.companyName?.slice(0,20)} | ${T}${A?" | \u{1F464} "+A.name:""}`)}else o.scouted%10===0&&console.log(` Scouted: ${o.scouted} (${o.recruitersFound} recruiters)`)}catch(g){o.errors++,a++,Me&&console.error(` Error: ${g.message?.slice(0,80)}`);let w=(g.message||"").toLowerCase();if(w.includes("detached")||w.includes("session closed")||w.includes("target closed")||w.includes("browser has disconnected")||w.includes("protocol error")){console.log(" \u26A0 Fatal browser error \u2014 stopping scout"),u=!0;break}if(a>=5){console.log(" \u26A0 5 consecutive errors \u2014 stopping scout"),u=!0;break}continue}a=0}if(u)break;if(o.scouted<ee)try{if(!await yt(c)){console.log(" No more pages.");break}await j(2e3)}catch(d){console.log(` \u26A0 Pagination failed: ${d.message?.slice(0,60)}`);break}}if(u)break}console.log(`
|
|
58
59
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" Scout Complete"),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(` URLs processed: ${o.urlsProcessed}/${e.length}`),console.log(` Pages scanned: ${o.pages}`),console.log(` Jobs scouted: ${o.scouted}`),console.log(` Skipped (existing): ${o.skipped}`),console.log(` Skipped (applied): ${o.skippedApplied}`),console.log(` Recruiters found: ${o.recruitersFound} (${o.alreadyConnected} already connected)`),console.log(` Errors: ${o.errors}`),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
|
|
59
|
-
`)
|
|
60
|
-
Error:`,l.message),Me&&console.error(l.stack)
|
|
60
|
+
`),Te(t,"success",o)}catch(l){console.error(`
|
|
61
|
+
Error:`,l.message),Me&&console.error(l.stack),Te(t,"error",o,l.message)}finally{await s.close().catch(()=>{})}}Un().catch(e=>{console.error("Scout failed:",e),process.exit(1)});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
`);var{browser:
|
|
3
|
-
\u2713 This profile is already logged in \u2014 no need to sign in again.`),console.log(" Press Enter here to (re)save the session cookies, or Ctrl+C to skip.");else{await d.goto("https://www.linkedin.com/login",{waitUntil:"domcontentloaded",timeout:6e4});let r=process.env.LINKEDIN_LOGIN,i=process.env.LINKEDIN_PASS;if(r&&i)try{await d.$('input[id="username"]')&&(await d.type('input[id="username"]',r,{delay:100}),await d.type('input[id="password"]',i,{delay:100}),console.log("Auto-filled credentials. Click Sign In or complete verification."))}catch{console.log("Auto-fill failed \u2014 log in manually.")}console.log("Waiting for you to log in..."),console.log("When you see your LinkedIn feed, press Enter here to save cookies.")}await new Promise(r=>{process.stdin.once("data",()=>r())}),process.stdin.pause();let
|
|
4
|
-
\u2713 Cookies saved to ${
|
|
1
|
+
import ee from"puppeteer";import{config as oe}from"dotenv";import{getPluginConfig as M}from"@ilivemylife/graph-sdk";var b={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},g=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function H(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function y(e=process.env){let o=(e.JOB_SEARCH_KEYWORDS||"").trim();if(!o)return null;let t=new URLSearchParams;t.set("keywords",o);let n=(e.JOB_SEARCH_LOCATION||"").trim();n&&t.set("location",n);let r=(e.JOB_SEARCH_GEO_ID||"").trim();r&&t.set("geoId",r);let i=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(i)&&i>0&&t.set("distance",String(i)),g(e.JOB_SEARCH_EASY_APPLY)&&t.set("f_AL","true"),g(e.JOB_SEARCH_IN_NETWORK)&&t.set("f_JIYN","true");let s=H(e.JOB_SEARCH_COMPANY_IDS);s.length&&t.set("f_C",s.join(","));let u=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();u&&t.set("f_TPR",b[u]||u),t.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let f="https://www.linkedin.com/jobs/search/?"+t.toString(),h=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return h&&(f+="&"+h),f}var U=await M();for(let[e,o]of Object.entries(U))process.env[e]===void 0&&(process.env[e]=o);var k=y(process.env);k&&(process.env.LINKEDIN_SEARCH_URL=k);var ie=process.env.LINKEDIN_NAME,l=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),se=Object.freeze(new Set([l.DRAFT,l.CONFIRMED,l.NEEDS_REVIEW])),ce=Object.freeze(new Set([l.DRAFT,l.CONFIRMED,l.REJECTED,l.NEEDS_REVIEW]));import c from"fs";import a from"path";var $="cookies.json";function K(){let e=process.env.ILML_SCOPE_DIR;return e?a.join(e,"plugins-state","linkedin","cookies.json"):$}function W(){let e=K(),o=a.dirname(e);return o&&o!=="."&&!c.existsSync(o)&&c.mkdirSync(o,{recursive:!0}),e}function _(e){let o=W();return c.writeFileSync(o,JSON.stringify(e)),o}function G(){let e=process.env.ILML_SCOPE_DIR;return e?a.join(e,"plugins-state","linkedin"):"."}function I(e){let o=String(e||"").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,80);return/[a-zA-Z0-9]/.test(o)?o:"default"}function Y(){let e=process.env.MY_LINKEDIN_URL,o=e&&e.match(/\/in\/([^/?#]+)/);return o&&o[1]?I(o[1]):"default"}function P(e){let o=process.env.LINKEDIN_CHROME_PROFILE_DIR;if(o)return c.existsSync(o)||c.mkdirSync(o,{recursive:!0}),a.resolve(o);let t=I(e||Y()),n=a.join(G(),"chrome-profile",t);return c.existsSync(n)||c.mkdirSync(n,{recursive:!0}),a.resolve(n)}var R=".ilml-seeded";function A(e){return!c.existsSync(a.join(e,R))}function C(e){try{c.writeFileSync(a.join(e,R),new Date().toISOString())}catch{}}function L(e){let o=0;for(let t of["SingletonLock","SingletonCookie","SingletonSocket"])try{c.rmSync(a.join(e,t),{force:!0}),o++}catch{}return o}import S from"fs";import z from"path";var V={headless:!1,defaultViewport:null,protocolTimeout:3e5},m=new Set,D=!1;async function w(){let e=[...m].map(o=>{try{return Promise.resolve(o.close()).catch(()=>{})}catch{return Promise.resolve()}});m.clear(),await Promise.race([Promise.all(e),new Promise(o=>setTimeout(o,5e3))])}function Z(){if(D)return;D=!0;let e=o=>async()=>{await w(),process.exit(o)};process.once("SIGINT",e(130)),process.once("SIGTERM",e(143)),process.once("SIGHUP",e(129)),process.once("uncaughtException",async o=>{await w(),console.error(o&&o.stack||o),process.exit(1)}),process.once("unhandledRejection",async o=>{await w(),console.error(o),process.exit(1)}),process.stdout.on("error",async o=>{o&&o.code==="EPIPE"&&(await w(),process.exit(0))}),process.on("exit",()=>{for(let o of m)try{let t=o.process&&o.process();t&&t.kill("SIGKILL")}catch{}})}function E(e){return z.join(e,".ilml-browser-session.json")}function T(e,o={}){try{S.writeFileSync(E(e),JSON.stringify({ownerPid:process.pid,startedAt:Date.now(),...o}))}catch{}}function X(e,o){try{let t=o.wsEndpoint&&o.wsEndpoint();T(e,t?{wsEndpoint:t}:{})}catch{}}function q(e){let o=v(e);o&&o.ownerPid===process.pid&&p(e)}function p(e){try{S.rmSync(E(e),{force:!0})}catch{}}function v(e){try{return JSON.parse(S.readFileSync(E(e),"utf-8"))}catch{return null}}function O(e){if(!e||e===process.pid)return!0;try{return process.kill(e,0),!0}catch(o){return!o||o.code!=="ESRCH"}}function N(e,o,t){let n,r=new Promise(s=>{n=setTimeout(()=>s(t),o)}),i=Promise.resolve(e).then(s=>(clearTimeout(n),s),s=>{throw clearTimeout(n),s});return Promise.race([i,r])}async function x(e,o,{probeTimeoutMs:t=4e3}={}){let n=v(o);if(!n)return"free";if(!n.wsEndpoint)return n.ownerPid&&n.ownerPid!==process.pid&&O(n.ownerPid)?"live":(p(o),"free");let r=Symbol("timeout"),i=e.connect({browserWSEndpoint:n.wsEndpoint,defaultViewport:null}).catch(()=>null),s=await N(i,t,r);if(s===r)return i.then(f=>{if(f)try{f.disconnect()}catch{}}),"live";if(!s)return p(o),"free";if(O(n.ownerPid)){try{s.disconnect()}catch{}return"live"}if(console.log(" (recovered an orphaned automation browser from a previous run \u2014 closing it)"),await N(s.close().then(()=>!0).catch(()=>!1),t,!1))return p(o),"free";try{s.disconnect()}catch{}return"live"}function Q(e,o){e&&(Z(),m.add(e),e.on("disconnected",()=>{m.delete(e),o&&p(o)}))}async function F(e,o={}){let t=P(),n={...V,...o,userDataDir:t},r=`Could not open the LinkedIn automation Chrome profile at ${t}. 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 x(e,t)==="live")throw new Error(r);T(t);let i;try{i=await e.launch(n)}catch{if(await x(e,t)==="live")throw new Error(r);L(t);try{i=await e.launch(n)}catch(u){throw q(t),new Error(`Could not open the LinkedIn automation Chrome profile at ${t}. If a LinkedIn automation window is already open, close it and retry. (Chrome: ${u.message})`)}}return Q(i,t),X(t,i),{browser:i,profileDir:t,needsSeed:A(t)}}function J(e){C(e)}oe();console.log(`Opening browser for LinkedIn login...
|
|
2
|
+
`);var{browser:B,profileDir:j}=await F(ee),d=await B.newPage();try{await d.goto("https://www.linkedin.com/feed/",{waitUntil:"domcontentloaded",timeout:6e4}),await new Promise(r=>setTimeout(r,2500));let e=d.url();if(e.includes("/feed")&&!/\/(login|authwall|checkpoint|uas)(\/|\?|$)/.test(e))console.log(`
|
|
3
|
+
\u2713 This profile is already logged in \u2014 no need to sign in again.`),console.log(" Press Enter here to (re)save the session cookies, or Ctrl+C to skip.");else{await d.goto("https://www.linkedin.com/login",{waitUntil:"domcontentloaded",timeout:6e4});let r=process.env.LINKEDIN_LOGIN,i=process.env.LINKEDIN_PASS;if(r&&i)try{await d.$('input[id="username"]')&&(await d.type('input[id="username"]',r,{delay:100}),await d.type('input[id="password"]',i,{delay:100}),console.log("Auto-filled credentials. Click Sign In or complete verification."))}catch{console.log("Auto-fill failed \u2014 log in manually.")}console.log("Waiting for you to log in..."),console.log("When you see your LinkedIn feed, press Enter here to save cookies.")}await new Promise(r=>{process.stdin.once("data",()=>r())}),process.stdin.pause();let t=await d.cookies(),n=_(t);console.log(`
|
|
4
|
+
\u2713 Cookies saved to ${n} (${t.length} cookies)`),J(j),console.log(`\u2713 Persistent profile ready: ${j}`)}catch(e){console.error("Login failed:",e.message)}finally{await B.close()}process.exit(0);
|