ilml-plugin-linkedin 1.14.4 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/applyQueue.mjs +34 -34
- package/dist/connect.mjs +70 -70
- package/dist/daily.mjs +29 -29
- package/dist/enrichProfile.mjs +1 -1
- package/dist/enrichProfiles.mjs +48 -48
- package/dist/funnelRunner.mjs +58 -58
- package/dist/messageBot.mjs +68 -68
- package/dist/migrationCli.mjs +25 -25
- package/dist/profileHistory.mjs +5 -5
- package/dist/quota.mjs +45 -5
- package/dist/run.mjs +60 -60
- package/dist/scout.mjs +35 -35
- package/dist/syncAll.mjs +103 -103
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +37 -37
- package/dist/visit.mjs +47 -47
- package/dist/warmScan.mjs +2 -2
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.
|
|
1
|
+
import{readFileSync as e}from"fs";import{fileURLToPath as r}from"url";function i(){return"1.15.0";try{let n=new URL("./ilml-plugin.json",import.meta.url);return JSON.parse(e(r(n),"utf-8")).version}catch{return"unknown"}}console.log(`ilml-plugin-linkedin ${i()}`);
|
package/dist/viewers.mjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var
|
|
2
|
-
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let t=
|
|
1
|
+
var qe=Object.defineProperty;var W=(e,o)=>{for(var n in o)qe(e,n,{get:o[n],enumerable:!0})};import"dotenv/config";import*as C from"fs";import*as M from"path";import{fileURLToPath as fo}from"url";import Ge from"puppeteer";import{addExtra as ze}from"puppeteer-extra";import Ke from"puppeteer-extra-plugin-stealth";async function H(e){let o=Math.floor(Math.random()*2001),n=e+o;return new Promise(t=>setTimeout(t,n))}import{getPluginConfig as Ue}from"@ilivemylife/graph-sdk";var Be=await Ue();for(let[e,o]of Object.entries(Be))process.env[e]===void 0&&(process.env[e]=o);var Je=process.env.LINKEDIN_NAME,O=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),bo=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.NEEDS_REVIEW])),Ve=Object.freeze(new Set([O.DRAFT,O.CONFIRMED,O.REJECTED,O.NEEDS_REVIEW]));import le from"fs";import We from"path";var He="cookies.json";function Ye(){let e=process.env.ILML_SCOPE_DIR;return e?We.join(e,"plugins-state","linkedin","cookies.json"):He}function ae(){let e=Ye();if(!le.existsSync(e))throw new Error(`Cookies not found at ${e}. Run: ilml linkedin login`);let o;try{o=le.readFileSync(e,"utf-8")}catch(t){throw new Error(`Failed to read cookies at ${e}: ${t.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(o)}catch{throw new Error(`Cookies file at ${e} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${e} is empty or not an array. Run: ilml linkedin login`);return n}var ue=ze(Ge);ue.use(Ke());async function fe(){let e=await ue.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5}),o=async()=>{console.log(`
|
|
2
|
+
Closing browser...`);try{await e.close()}catch{}process.exit(0)};process.on("SIGINT",o),process.on("SIGTERM",o);let n=await e.newPage();await n.evaluateOnNewDocument(()=>{Object.defineProperty(navigator,"webdriver",{get:()=>{}})});try{let t=ae();await n.setCookie(...t),console.log(" Browser launched, cookies loaded.")}catch(t){console.error(`
|
|
3
3
|
[!] ${t.message}
|
|
4
|
-
`),await e.close(),process.exit(1)}return{browser:e,page:n}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as
|
|
5
|
-
`).map(p=>p.trim()).filter(Boolean),f="";for(let p of u)if(p.length>2&&p.length<60&&!p.includes("View")&&!p.includes("profile")&&!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&!p.startsWith("3rd")){f=p;break}f||(f=
|
|
6
|
-
`)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",
|
|
4
|
+
`),await e.close(),process.exit(1)}return{browser:e,page:n}}import"dotenv/config";import*as h from"fs";import*as g from"path";import{fileURLToPath as Qe}from"url";var Xe=Qe(import.meta.url),Ze=g.dirname(g.dirname(Xe)),D=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(Ze,"collected-profiles"),et=g.join(D,"people.json"),Po=g.join(D,"jobs.json"),qo=g.join(D,"quota.json"),Uo=g.join(D,"conversations.json"),Bo=g.join(D,"sync-state.json"),Jo=g.join(D,"application-questions.json"),Vo=g.join(D,"profile-history"),pe=(e,o)=>{let n=parseInt(e,10);return Number.isInteger(n)&&n>=0?n:o},Wo=pe(process.env.CONNECT_MAX_DAILY,20),Ho=pe(process.env.CONNECT_MAX_WEEKLY,100),B=null,tt=null,ot=null,nt=null,st=null,rt=null;function de(){B=null,tt=null,ot=null,nt=null,st=null,rt=null}function it(){h.existsSync(D)||h.mkdirSync(D,{recursive:!0})}function ct(e,o){if(!h.existsSync(e))return null;try{let n=JSON.parse(h.readFileSync(e,"utf-8"));try{h.copyFileSync(e,e+".backup")}catch{}return n}catch(n){console.error(`[!] ${o} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(e)}`);let t=e+".backup";if(h.existsSync(t))try{let s=JSON.parse(h.readFileSync(t,"utf-8"));console.error(` Restored from ${t}`);try{h.copyFileSync(t,e)}catch{}return s}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${e}.corrupted`);try{h.copyFileSync(e,e+".corrupted")}catch{}return null}}function me(){return B||(it(),B=ct(et,"people.json")||{},B)}import"dotenv/config";import*as j from"fs";import*as S from"path";import{fileURLToPath as lt}from"url";var at=lt(import.meta.url),ut=S.dirname(S.dirname(at)),V=process.env.DATA_DIR?S.resolve(process.env.DATA_DIR,"market-research"):S.join(ut,"market-research"),Ko=S.join(V,"scouted-jobs.json"),ft=S.join(V,"discovered-people.json"),pt=S.join(V,"visit-log.json"),Qo=S.join(V,"companies.json"),Xo=S.join(V,"job-decisions.json");function he(e){try{if(j.existsSync(e))return JSON.parse(j.readFileSync(e,"utf-8"))}catch{}return null}function ge(){dt=null,mt=null,J=null,ht=null,R=null}var dt=null;var mt=null;var J=null;function ye(){return J||(J=he(ft)||{},J)}var ht=null;var R=null;function Se(){return R||(R=he(pt)||{visits:[]},Array.isArray(R.visits)||(R.visits=[]),R)}async function we(e){await e.goto("https://www.linkedin.com/analytics/profile-views/",{waitUntil:"domcontentloaded",timeout:6e4}),await H(5e3);for(let n=0;n<5;n++)await e.evaluate(()=>window.scrollBy(0,600)),await H(1e3);return await e.evaluate(()=>{let n=[],t=document.querySelectorAll('a[href*="/in/"]'),s=new Set;for(let i of t){let r=i.getAttribute("href")?.split("?")[0];if(!r||s.has(r))continue;s.add(r);let c=i;for(let p=0;p<8&&!(!c.parentElement||(c=c.parentElement,c.tagName==="LI"||c.classList?.contains("pvs-list__paged-list-wrapper")));p++);let l=c?.innerText?.trim()||"",u=l.split(`
|
|
5
|
+
`).map(p=>p.trim()).filter(Boolean),f="";for(let p of u)if(p.length>2&&p.length<60&&!p.includes("View")&&!p.includes("profile")&&!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&!p.startsWith("3rd")){f=p;break}f||(f=i.textContent?.trim()?.split(`
|
|
6
|
+
`)[0]?.trim()||""),f=f.replace(/View .+?'s profile$/i,"").trim();let m=l.match(/·\s*(1st|2nd|3rd)/)?.[1]||null,v="",P=u.indexOf(f);if(P>=0&&P+1<u.length){let p=u[P+1];!p.includes("\xB7")&&!p.startsWith("1st")&&!p.startsWith("2nd")&&(v=p)}f&&f.length>1&&n.push({profileUrl:r.startsWith("/")?"https://www.linkedin.com"+r:r,name:f,title:v||null,connectionDegree:m})}return n})}function ve(e){let o=me(),n=Se(),t=ye(),s=new Map;for(let i of n.visits||[]){let r=s.get(i.profileUrl);(!r||i.date>r)&&s.set(i.profileUrl,i.date)}return e.map(i=>{let r=o[i.profileUrl],c=t[i.profileUrl],l=s.get(i.profileUrl);return{...i,isConnected:r?.connectionStatus==="connected",isPending:r?.connectionStatus==="pending"||r?.connectionStatus==="sent_without_note",isInPeopleDb:!!r,isDiscovered:!!c,weVisitedThem:!!l,ourVisitDate:l||null,category:r?.category||c?.role||null}})}import"dotenv/config";import*as b from"fs";import*as _ from"path";import{fileURLToPath as bt}from"url";import"dotenv/config";import{createGraphClient as gt,resolveToken as yt}from"@ilivemylife/graph-sdk";import{config as St}from"dotenv";St();var be=yt()||process.env.TOKEN;be||(console.error(`
|
|
7
7
|
[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.
|
|
8
8
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
9
9
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
10
|
-
`),process.exit(1));var
|
|
10
|
+
`),process.exit(1));var ke=gt({token:be});function wt(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let n=Math.floor(o/60),t=o%60;return t?`${n}m ${t}s`:`${n}m`}function vt({scriptName:e,mode:o,status:n,error:t,duration:s}){let i=n==="error"?"\u2717":n==="quota-reached"?"\u26A0":"\u2713",r=new Date().toISOString().slice(0,16).replace("T"," "),c=s?` ${wt(s)}`:"",l=n==="error"?`error${t?`: ${String(t).slice(0,80)}`:""}`:n==="quota-reached"?"daily quota reached":"done",u=o&&o!=="default"?` (${o})`:"";return`${i} ${e}${u} \u2014 ${l} \u2014 ${r}${c}`}async function Ae({scriptName:e,mode:o,status:n,summaryLines:t,error:s,duration:i}){let r=process.env.NODE_RUN_REPORTS;if(!r||!Array.isArray(t)||t.length===0)return;let l=`**${vt({scriptName:e,mode:o,status:n,error:s,duration:i})}**
|
|
11
11
|
|
|
12
12
|
${t.join(`
|
|
13
|
-
`)}`;try{await ve.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var wt=St(import.meta.url),vt=D.dirname(D.dirname(wt)),G=process.env.DATA_DIR?D.resolve(process.env.DATA_DIR,"collected-profiles"):D.join(vt,"collected-profiles"),z=D.join(G,"run-log.json");function bt(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";b.writeFileSync(t,n);for(let s=0;s<3;s++)try{b.renameSync(t,e);return}catch(r){if(s<2&&(r.code==="EPERM"||r.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw r}}function ke(){try{if(!b.existsSync(z))return{runs:[]};let e=JSON.parse(b.readFileSync(z,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function $e(e){b.existsSync(G)||b.mkdirSync(G,{recursive:!0});try{bt(z,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function Ae(e,o="default"){let n=ke();for(let i of n.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let t=new Date,s={timestamp:t.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(i=>new Date(i.timestamp).getTime()>r),$e(n),{script:e,mode:o,startTime:t.getTime(),runIndex:n.runs.length-1}}function K(e,o,n=null,t=null){if(!e)return;let s=null;try{let i=ke(),c=i.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=n,c.error=t,s=c.duration;else{let l=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=o,l.result=o,l.duration=Date.now()-e.startTime,l.stats=n,l.error=t,s=l.duration)}$e(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=o==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";be({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:t,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as ne from"os";import*as d from"path";import{fileURLToPath as Pt}from"url";var Z={};Y(Z,{NAME:()=>$t,VERSION:()=>kt,up:()=>Tt});import*as k from"fs";import*as W from"path";var kt=1,$t="normalize-jobs-and-questions",At=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Et=50;function Q(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function X(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{k.writeFileSync(t,n)}catch(s){try{k.unlinkSync(t)}catch{}throw s}try{k.renameSync(t,e)}catch(s){try{k.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Tt(e,o){let n=W.join(e,"jobs.json"),t=W.join(o,"scouted-jobs.json"),s=W.join(e,"application-questions.json"),r=Q(n)||{},i=Q(t)||{},c=0,l=[];for(let f of Object.keys(r)){if(!i[f])continue;let w=i[f],m=r[f];for(let v of At)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(X(n,r),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=Q(s);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let M=(m.questions||[]).map(p=>{let P={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=Et?P.options=p.options:(P.optionsOmitted=!0,w++)),p.page&&(P.page=p.page),p.wasPreFilled&&(P.wasPreFilled=!0),p.wasRetry&&(P.wasRetry=!0),P});f[v].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||M.length,questions:M})}X(s,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else u&&!u.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 f of l)delete i[f];X(t,i),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var ee={};Y(ee,{NAME:()=>It,VERSION:()=>Ct,up:()=>Rt});import*as $ from"fs";import*as Ee from"path";var Ct=2,It="reset-unread-flags";function Dt(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function xt(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{$.writeFileSync(t,n)}catch(s){try{$.unlinkSync(t)}catch{}throw s}try{$.renameSync(t,e)}catch(s){try{$.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}async function Rt(e){let o=Ee.join(e,"conversations.json"),n=Dt(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}xt(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var te={};Y(te,{NAME:()=>_t,VERSION:()=>Ot,up:()=>Mt});import*as A from"fs";import*as Te from"path";var Ot=3,_t="recompute-last-message-by",jt=new Set(["draft","confirmed","rejected","needs_review"]);function Nt(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Ft(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{A.writeFileSync(t,n)}catch(s){try{A.unlinkSync(t)}catch{}throw s}try{A.renameSync(t,e)}catch(s){try{A.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let r=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw r.code=s.code,r}throw s}}function Lt(e,o){if(!e||e.length===0)return"them";let n=e.filter(r=>!jt.has(r.status));if(n.length===0)return"them";let t=n.map(r=>({m:r,t:Date.parse(r.time)})).filter(r=>Number.isFinite(r.t)).sort((r,i)=>i.t-r.t).map(r=>r.m),s=t.length>0?t:[...n].reverse();for(let r of s){let i=r.sender;if(i===o)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Mt(e){let o=Te.join(e,"conversations.json"),n=Nt(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,r++);let u=Array.isArray(l.messages)?l.messages:[],f=Lt(u,t),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&i++,l.lastMessageBy=f,l.conversationStatus=w,s++}if(s===0){console.log(" No conversations to recompute.");return}Ft(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),r>0&&console.log(` Cleaned ${r} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var qt=Pt(import.meta.url),Ut=d.dirname(qt),Bt=d.dirname(d.dirname(Ut));function Jt(e){return e&&(e==="~"?ne.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(ne.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?d.resolve(Jt(process.env.DATA_DIR)):Bt,N=d.join(T,"collected-profiles"),F=d.join(T,"market-research"),y=d.join(T,".schema-version"),Ce=[d.join(N,".schema-version"),d.join(F,".schema-version")],x=3,I=[{version:1,module:Z},{version:2,module:ee},{version:3,module:te}];(function(){I.sort((t,s)=>t.version-s.version);let o=new Set;for(let t of I){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let s=t.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=I.length?I[I.length-1].version:0;if(n!==x)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${x}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<I.length;t++){let s=t+1;if(I[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${I[t].version}`)}})();function Re(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
13
|
+
`)}`;try{await ke.addMessage(r,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var kt=bt(import.meta.url),At=_.dirname(_.dirname(kt)),z=process.env.DATA_DIR?_.resolve(process.env.DATA_DIR,"collected-profiles"):_.join(At,"collected-profiles"),K=_.join(z,"run-log.json");function $t(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";b.writeFileSync(t,n);for(let s=0;s<3;s++)try{b.renameSync(t,e);return}catch(i){if(s<2&&(i.code==="EPERM"||i.code==="EBUSY")){let r=Date.now();for(;Date.now()-r<200;);continue}throw i}}function $e(){try{if(!b.existsSync(K))return{runs:[]};let e=JSON.parse(b.readFileSync(K,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function Ee(e){b.existsSync(z)||b.mkdirSync(z,{recursive:!0});try{$t(K,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function Ce(e,o="default"){let n=$e();for(let r of n.runs)r.status==="running"&&(r.status="interrupted",r.result="interrupted",r.timestamp&&(r.duration=Date.now()-new Date(r.timestamp).getTime()));let t=new Date,s={timestamp:t.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};n.runs.push(s);let i=Date.now()-30*24*60*60*1e3;return n.runs=n.runs.filter(r=>new Date(r.timestamp).getTime()>i),Ee(n),{script:e,mode:o,startTime:t.getTime(),runIndex:n.runs.length-1}}function Q(e,o,n=null,t=null){if(!e)return;let s=null;try{let r=$e(),c=r.runs[e.runIndex];if(c&&c.status==="running"&&c.script===e.script)c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=n,c.error=t,s=c.duration;else{let l=r.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());l&&(l.status=o,l.result=o,l.duration=Date.now()-e.startTime,l.stats=n,l.error=t,s=l.duration)}Ee(r)}catch(r){console.error(`[runLog] Failed to end run: ${r.message}`)}let i=n&&Array.isArray(n.summaryLines)?n.summaryLines:null;if(i&&i.length>0&&process.env.NODE_RUN_REPORTS){let r=o==="error"?"error":n&&n.dailyLimitHit?"quota-reached":"done";Ae({scriptName:e.script,mode:e.mode,status:r,summaryLines:i,error:t,duration:s??Date.now()-e.startTime}).catch(c=>console.error(`[runLog] postRunReport failed: ${c.message}`))}}import"dotenv/config";import*as a from"fs";import*as re from"os";import*as d from"path";import{fileURLToPath as Gt}from"url";var ee={};W(ee,{NAME:()=>Ct,VERSION:()=>Et,up:()=>It});import*as k from"fs";import*as Y from"path";var Et=1,Ct="normalize-jobs-and-questions",Tt=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],Dt=50;function X(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function Z(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{k.writeFileSync(t,n)}catch(s){try{k.unlinkSync(t)}catch{}throw s}try{k.renameSync(t,e)}catch(s){try{k.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function It(e,o){let n=Y.join(e,"jobs.json"),t=Y.join(o,"scouted-jobs.json"),s=Y.join(e,"application-questions.json"),i=X(n)||{},r=X(t)||{},c=0,l=[];for(let f of Object.keys(i)){if(!r[f])continue;let w=r[f],m=i[f];for(let v of Tt)w[v]!=null&&m[v]==null&&(m[v]=w[v]);l.push(f),c++}c>0?(Z(n,i),console.log(` Phase 1: Merged ${c} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=X(s);if(u&&Array.isArray(u.applications)){let f={},w=0;for(let m of u.applications){let v=m.jobId||"unknown";f[v]||(f[v]={applications:[]});let P=(m.questions||[]).map(p=>{let q={type:p.type||"input",question:p.question||"",answer:p.answer||""};return p.options&&(p.options.length<=Dt?q.options=p.options:(q.optionsOmitted=!0,w++)),p.page&&(q.page=p.page),p.wasPreFilled&&(q.wasPreFilled=!0),p.wasRetry&&(q.wasRetry=!0),q});f[v].applications.push({applicationId:m.applicationId,date:m.date,result:m.result||"submitted",formPages:m.formPages||null,duration:m.duration||null,retries:m.retries||0,failedField:m.failedField||null,questionCount:m.questionCount||P.length,questions:P})}Z(s,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),w>0&&console.log(` Phase 2: Stripped bloated options from ${w} questions`)}else u&&!u.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 f of l)delete r[f];Z(t,r),console.log(` Phase 3: Removed ${l.length} merged entries from scouted-jobs.json (${Object.keys(r).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var te={};W(te,{NAME:()=>xt,VERSION:()=>_t,up:()=>jt});import*as A from"fs";import*as Te from"path";var _t=2,xt="reset-unread-flags";function Ot(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Rt(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{A.writeFileSync(t,n)}catch(s){try{A.unlinkSync(t)}catch{}throw s}try{A.renameSync(t,e)}catch(s){try{A.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function jt(e){let o=Te.join(e,"conversations.json"),n=Ot(o);if(!n){console.log(" conversations.json not found \u2014 nothing to reset.");return}let t=0;for(let s of Object.keys(n))n[s].unread===!0&&(n[s].unread=!1,t++);if(t===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Rt(o,n),console.log(` Reset unread=false on ${t} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var oe={};W(oe,{NAME:()=>Ft,VERSION:()=>Nt,up:()=>Ut});import*as $ from"fs";import*as De from"path";var Nt=3,Ft="recompute-last-message-by",Lt=new Set(["draft","confirmed","rejected","needs_review"]);function Mt(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function Pt(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{$.writeFileSync(t,n)}catch(s){try{$.unlinkSync(t)}catch{}throw s}try{$.renameSync(t,e)}catch(s){try{$.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}function qt(e,o){if(!e||e.length===0)return"them";let n=e.filter(i=>!Lt.has(i.status));if(n.length===0)return"them";let t=n.map(i=>({m:i,t:Date.parse(i.time)})).filter(i=>Number.isFinite(i.t)).sort((i,r)=>r.t-i.t).map(i=>i.m),s=t.length>0?t:[...n].reverse();for(let i of s){let r=i.sender;if(r===o)return"me";if(r!=="Unknown"&&r!=="")return"them"}return"them"}async function Ut(e){let o=De.join(e,"conversations.json"),n=Mt(o);if(!n){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let t=process.env.LINKEDIN_NAME;if(!t||typeof t!="string"||!t.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,i=0,r=0;for(let c of Object.keys(n)){let l=n[c];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,i++);let u=Array.isArray(l.messages)?l.messages:[],f=qt(u,t),w=f==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==f&&r++,l.lastMessageBy=f,l.conversationStatus=w,s++}if(s===0){console.log(" No conversations to recompute.");return}Pt(o,n),console.log(` Recomputed lastMessageBy + conversationStatus on ${s} conversations.`),console.log(` ${r} 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={};W(ne,{NAME:()=>Jt,VERSION:()=>Bt,up:()=>Yt});import*as E from"fs";import*as Ie from"path";var Bt=4,Jt="split-connection-timestamps",Vt=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Wt(e){if(!E.existsSync(e))return null;let o=E.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Ht(e,o){let n=JSON.stringify(o,null,2),t=e+".tmp";try{E.writeFileSync(t,n)}catch(s){try{E.unlinkSync(t)}catch{}throw s}try{E.renameSync(t,e)}catch(s){try{E.unlinkSync(t)}catch{}if(s.code==="EPERM"||s.code==="EBUSY"){let i=new Error(`File locked: ${e} (${s.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw i.code=s.code,i}throw s}}async function Yt(e){let o=Ie.join(e,"people.json"),n=Wt(o);if(!n||typeof n!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let t=0,s=0;for(let i of Object.keys(n)){let r=n[i];!r||typeof r!="object"||(s++,Vt.has(r.connectionStatus)&&r.connectionDate&&!r.requestedConnectionAt&&(r.requestedConnectionAt=r.connectionDate,r.connectionDate=null,t++))}if(t===0){console.log(` Scanned ${s} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Ht(o,n),console.log(` Moved connectionDate \u2192 requestedConnectionAt on ${t} still-pending people (of ${s} scanned).`),console.log(' connectionDate now means "accepted on" only; requestedConnectionAt means "requested on".')}var zt=Gt(import.meta.url),Kt=d.dirname(zt),Qt=d.dirname(d.dirname(Kt));function Xt(e){return e&&(e==="~"?re.homedir():e.startsWith("~/")||e.startsWith("~\\")?d.join(re.homedir(),e.slice(2)):e)}var T=process.env.DATA_DIR?d.resolve(Xt(process.env.DATA_DIR)):Qt,F=d.join(T,"collected-profiles"),L=d.join(T,"market-research"),y=d.join(T,".schema-version"),_e=[d.join(F,".schema-version"),d.join(L,".schema-version")],x=4,I=[{version:1,module:ee},{version:2,module:te},{version:3,module:oe},{version:4,module:ne}];(function(){I.sort((t,s)=>t.version-s.version);let o=new Set;for(let t of I){if(!Number.isInteger(t.version)||t.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(t.version)} (must be positive integer)`);if(o.has(t.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${t.version}`);o.add(t.version);let s=t.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${t.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==t.version)throw new Error(`MIGRATION_REGISTRY: v${t.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let n=I.length?I[I.length-1].version:0;if(n!==x)throw new Error(`MIGRATION_REGISTRY: highest version v${n} but CURRENT_SCHEMA_VERSION=${x}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let t=0;t<I.length;t++){let s=t+1;if(I[t].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${t} but found v${I[t].version}`)}})();function je(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
14
14
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
15
15
|
`),process.exit(1));try{a.mkdirSync(T,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
|
|
16
16
|
[FATAL] Cannot create DATA_DIR (${T}): ${o.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -18,47 +18,47 @@ ${t.join(`
|
|
|
18
18
|
[FATAL] DATA_DIR (${T}) is not accessible: ${o.message}
|
|
19
19
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
20
20
|
[FATAL] DATA_DIR (${T}) 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.
|
|
21
|
-
`),process.exit(1));for(let o of[
|
|
21
|
+
`),process.exit(1));for(let o of[F,L]){let n;try{n=a.lstatSync(o)}catch(t){if(t.code==="ENOENT")continue;throw t}n.isSymbolicLink()&&(console.error(`
|
|
22
22
|
[FATAL] Data subdirectory is a symbolic link: ${o}`),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.
|
|
23
|
-
`),process.exit(1))}}var
|
|
24
|
-
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${
|
|
23
|
+
`),process.exit(1))}}var N=d.join(T,".migration-lock");function Zt(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return a.writeFileSync(N,e,{flag:"wx"}),!0}catch(t){if(t.code!=="EEXIST")throw t}let o;try{o=JSON.parse(a.readFileSync(N,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let t=!1;try{process.kill(o.pid,0),t=!0}catch(r){r.code==="EPERM"&&(t=!0)}let s=24*60*60*1e3,i=1/0;if(o.startedAt){let r=Date.parse(o.startedAt);Number.isNaN(r)||(i=Date.now()-r)}t&&i<s&&(console.error(`
|
|
24
|
+
[FATAL] Another plugin process is currently running migrations:`),console.error(` PID: ${o.pid}`),console.error(` Started at: ${o.startedAt||"(unknown)"}`),console.error(` Lock file: ${N}
|
|
25
25
|
`),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.
|
|
26
|
-
`),process.exit(1)),t&&
|
|
27
|
-
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let
|
|
26
|
+
`),process.exit(1)),t&&i>=s&&console.log(` Lock holder PID ${o.pid} is alive but lock is older than 24h \u2014 assuming PID reuse, taking over.`)}console.log(` Stale migration lock from PID ${o?.pid??"?"} found \u2014 taking over.`);let n=N+".tmp";try{return a.writeFileSync(n,e),a.renameSync(n,N),!0}catch(t){try{a.unlinkSync(n)}catch{}throw new Error(`Failed to take over stale migration lock: ${t.message}`)}}function ie(){try{if(JSON.parse(a.readFileSync(N,"utf-8")).pid!==process.pid)return;a.unlinkSync(N)}catch{}}var xe=!1;function eo(){if(xe)return;xe=!0;let e=()=>{try{ie()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function to(){if(a.existsSync(y))return;let e=[],o=[];for(let i of _e)if(a.existsSync(i))try{e.push({file:i,schema:G(i)})}catch(r){o.push({file:i,err:r.message})}if(o.length>0){console.error(`
|
|
27
|
+
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let i of o)console.error(` ${i.file}: ${i.err}`);console.error(`
|
|
28
28
|
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.
|
|
29
|
-
`),process.exit(1)}if(e.length===0)return;let n=e.map(
|
|
30
|
-
[FATAL] Legacy .schema-version files disagree:`);for(let
|
|
31
|
-
`),process.exit(1)}let t=e[0].schema,s=y+".tmp";try{a.writeFileSync(s,JSON.stringify(t,null,2)),a.renameSync(s,y)}catch(
|
|
29
|
+
`),process.exit(1)}if(e.length===0)return;let n=e.map(i=>i.schema.version);if(new Set(n).size>1){console.error(`
|
|
30
|
+
[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.
|
|
31
|
+
`),process.exit(1)}let t=e[0].schema,s=y+".tmp";try{a.writeFileSync(s,JSON.stringify(t,null,2)),a.renameSync(s,y)}catch(i){try{a.unlinkSync(s)}catch{}throw i}for(let i of _e)if(a.existsSync(i))try{a.unlinkSync(i)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function oo(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let o=Number(e.version);return!Number.isFinite(o)||o<0||!Number.isInteger(o)?null:(e.version=o,Array.isArray(e.migrations)||(e.migrations=[]),e)}function G(e){let o=a.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Oe(){if(to(),!a.existsSync(y))return{version:0,migrations:[]};let e;try{e=G(y)}catch(n){if(n.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
32
32
|
[FATAL] ${y} is not valid JSON: ${n.message}`),console.error(" Refusing to proceed \u2014 silently treating it as 'fresh install' would re-apply"),console.error(" every migration on top of already-migrated data and corrupt it."),console.error(' Repair the file (set it to {"version":N,"migrations":[...]} matching your real state)'),console.error(` or restore from the *.pre-vNNN.backup files if you have them.
|
|
33
|
-
`),process.exit(1)}let o=
|
|
33
|
+
`),process.exit(1)}let o=oo(e);return o===null&&(console.error(`
|
|
34
34
|
[FATAL] ${y} 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.
|
|
35
|
-
`),process.exit(1)),o}function
|
|
35
|
+
`),process.exit(1)),o}function Ne(e){try{a.chmodSync(e,384)}catch{}}function no(e){if(je(),a.existsSync(y))try{if(a.lstatSync(y).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${y}. Refusing to write through it (potential symlink attack). Remove the link and re-run.`)}catch(n){if(n.message?.includes("symbolic link"))throw n}let o=y+".tmp";try{a.writeFileSync(o,JSON.stringify(e,null,2)),Ne(o),a.renameSync(o,y)}catch(n){try{a.unlinkSync(o)}catch{}throw n}}function Re(e,o){if(!a.existsSync(e))return;let n=`.pre-v${String(o).padStart(3,"0")}.backup`,t=a.readdirSync(e).filter(c=>{let l=c.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return a.statSync(d.join(e,c)).isFile()}catch{return!1}}),s=0,i=0,r=[];for(let c of t){let l=d.join(e,c),u=d.join(e,c+n);if(a.existsSync(u)){i++;continue}try{Le(l,u),s++}catch(f){r.push({file:c,err:f.message})}}if(r.length>0){let c=new Error(`Failed to back up ${r.length} file(s) in ${d.basename(e)}/: `+r.map(l=>`${l.file} (${l.err})`).join(", "));throw c.code="BACKUP_INCOMPLETE",c}if(s>0||i>0){let c=i>0?` (${i} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${d.basename(e)}/ (${n})${c}`)}}var se=!1;async function Fe(){if(se)return;je(),lo();let o=Oe().version;if(o===x){se=!0;return}eo(),Zt(),process.on("exit",ie),o>x&&(console.error(`
|
|
36
36
|
[FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${x}.`),console.error(" This usually means you downgraded the plugin without rolling back data."),console.error(` Operating on the newer-format data with this build would risk corrupting it.
|
|
37
37
|
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${x}.
|
|
38
38
|
`),process.exit(1)),console.log(`
|
|
39
|
-
\u{1F4E6} Schema migration: v${o} \u2192 v${x}`);let n=
|
|
39
|
+
\u{1F4E6} Schema migration: v${o} \u2192 v${x}`);let n=ao();if(!n.ok){console.error(`
|
|
40
40
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of n.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
41
41
|
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'.
|
|
42
42
|
`),process.exit(1)}let t=I.filter(s=>s.version>o);for(let s of t){console.log(`
|
|
43
|
-
Running migration v${String(s.version).padStart(3,"0")}...`);let
|
|
44
|
-
[FATAL] Pre-migration backup failed for ${
|
|
45
|
-
`),process.exit(1)}let c=s.module;try{await c.up(
|
|
46
|
-
[FATAL] Migration ${
|
|
47
|
-
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${
|
|
48
|
-
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${
|
|
49
|
-
`)}process.exit(1)}try{let l=new Date().toISOString(),u={version:s.version,name:c.NAME||
|
|
50
|
-
[FATAL] Migration ${
|
|
51
|
-
`),process.exit(1)}console.log(` \u2713 Migration ${
|
|
43
|
+
Running migration v${String(s.version).padStart(3,"0")}...`);let i=`v${String(s.version).padStart(3,"0")}`,r=`.pre-${i}.backup`;try{Re(F,s.version),Re(L,s.version)}catch(l){console.error(`
|
|
44
|
+
[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.
|
|
45
|
+
`),process.exit(1)}let c=s.module;try{await c.up(F,L)}catch(l){console.error(`
|
|
46
|
+
[FATAL] Migration ${i} failed: ${l.message}`),console.error(` Attempting auto-rollback from ${r} files...`);try{let u=uo(r);u.ok?(console.error(` \u2713 Auto-rollback restored ${u.restored} files. Schema stays at v${o}.`),console.error(` The migration will be retried on next plugin command. Fix the root cause first.
|
|
47
|
+
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${r} files back over the originals.
|
|
48
|
+
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${r} files back over the originals.
|
|
49
|
+
`)}process.exit(1)}try{let l=new Date().toISOString(),u={version:s.version,name:c.NAME||i,appliedAt:l},f=Oe();f.version=s.version,f.migratedAt=l,f.migrations=f.migrations||[],f.migrations.push(u),no(f)}catch(l){console.error(`
|
|
50
|
+
[FATAL] Migration ${i} applied successfully but schema version file could NOT be updated: ${l.message}`),console.error(` Your data is in the v${s.version} state but .schema-version still shows v${o}.`),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.
|
|
51
|
+
`),process.exit(1)}console.log(` \u2713 Migration ${i} complete`)}try{de()}catch{}try{ge()}catch{}se=!0,ie(),console.log(`
|
|
52
52
|
\u2713 Schema is now at v${x}
|
|
53
|
-
`)}var
|
|
53
|
+
`)}var so=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function ro(e){let o=e.toLowerCase();return so.some(n=>n.test(o))}var io=6e4;function co(){let e=Date.now(),o=[];for(let n of[T,F,L]){if(!a.existsSync(n))continue;let t;try{t=a.readdirSync(n)}catch{continue}for(let s of t){if(!ro(s))continue;let i=d.join(n,s);try{let r=a.statSync(i);if(!r.isFile()||e-r.mtimeMs<io)continue;o.push({dir:n,file:s,fullPath:i})}catch{}}}return o}function lo({verbose:e=!1}={}){let o=co();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let n=0;for(let t of o)try{a.unlinkSync(t.fullPath),n++,e&&console.log(` Removed orphan: ${d.basename(t.dir)}/${t.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${t.fullPath}: ${s.message}`)}return!e&&n>0&&console.log(` Cleaned up ${n} orphan .tmp file(s) from previous run.`),n}function ao(){let e=[];for(let o of[F,L]){if(!a.existsSync(o))continue;let n=a.readdirSync(o).filter(t=>{let s=t.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let t of n){let s=d.join(o,t);try{G(s)}catch(i){e.push({dir:d.basename(o),file:t,err:i.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function uo(e){let o=[],n=[];for(let i of[F,L]){if(!a.existsSync(i))continue;let r=a.readdirSync(i).filter(c=>c.endsWith(e));for(let c of r){let l=d.join(i,c),u=c.slice(0,-e.length),f=d.join(i,u);try{u.toLowerCase().endsWith(".json")?G(l):a.accessSync(l,a.constants.R_OK),o.push({backupPath:l,originalPath:f,fileName:c,dir:i})}catch(w){n.push(`${d.basename(i)}/${c}: ${w.message}`)}}}if(n.length>0)return{ok:!1,error:n.join("; "),restored:0};let t=0,s=[];for(let{backupPath:i,originalPath:r,fileName:c,dir:l}of o)try{Le(i,r),t++}catch(u){s.push(`${d.basename(l)}/${c}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:t}:{ok:!0,restored:t}}function Le(e,o){let n=o+".tmp";try{a.copyFileSync(e,n),Ne(n)}catch(t){try{a.unlinkSync(n)}catch{}throw t}try{a.renameSync(n,o)}catch(t){try{a.unlinkSync(n)}catch{}if(t.code==="EPERM"||t.code==="EBUSY"){let s=new Error(`File locked: ${o} (${t.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=t.code,s}throw t}}var po=fo(import.meta.url),mo=M.dirname(po),ce=process.env.DATA_DIR?M.resolve(process.env.DATA_DIR,"market-research"):M.join(mo,"market-research"),U=M.join(ce,"profile-viewers.json");await Fe();var Pe=process.argv.slice(2),Me=Pe.includes("--save"),ho=Pe.includes("--list");function go(){if(!C.existsSync(U)){console.log(`
|
|
54
54
|
No viewer data yet. Run: npm run viewers -- --save
|
|
55
|
-
`);return}let o=JSON.parse(
|
|
56
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE VIEWERS"),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(` Total scans: ${o.length}`),console.log(` Unique viewers: ${t.size}`);let s=[...t.values()].filter(
|
|
57
|
-
Recent viewers:`);let
|
|
58
|
-
`)}async function
|
|
55
|
+
`);return}let o=JSON.parse(C.readFileSync(U,"utf-8")).scans||[],n=o.flatMap(r=>r.viewers||[]),t=new Map;for(let r of n)(!t.has(r.profileUrl)||r.scanDate>t.get(r.profileUrl).scanDate)&&t.set(r.profileUrl,r);console.log(`
|
|
56
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`),console.log(" PROFILE VIEWERS"),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(` Total scans: ${o.length}`),console.log(` Unique viewers: ${t.size}`);let s=[...t.values()].filter(r=>r.isConnected).length,i=[...t.values()].filter(r=>r.weVisitedThem).length;if(console.log(` Already connected: ${s}`),console.log(` We visited first: ${i} (\u2192 they responded by viewing us)`),t.size>0){console.log(`
|
|
57
|
+
Recent viewers:`);let r=[...t.values()].slice(0,10);for(let c of r){let l=[];c.isConnected&&l.push("connected"),c.weVisitedThem&&l.push("we visited"),c.isDiscovered&&l.push("discovered");let u=l.length?` [${l.join(", ")}]`:"";console.log(` ${c.name} (${c.connectionDegree||"?"})${u}`),c.title&&console.log(` ${c.title.slice(0,60)}`)}}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
|
|
58
|
+
`)}async function yo(){if(console.log(`
|
|
59
59
|
LinkedIn Profile Viewers
|
|
60
|
-
`),
|
|
61
|
-
`);let t=await
|
|
62
|
-
Saved ${s.length} viewers to ${
|
|
63
|
-
Summary: ${
|
|
64
|
-
Error:`,t.message),
|
|
60
|
+
`),ho){go();return}let e=Ce("viewers",Me?"save":"view"),{browser:o,page:n}=await fe();try{console.log(` Extracting profile viewers...
|
|
61
|
+
`);let t=await we(n);console.log(` Found ${t.length} viewers`);let s=ve(t);for(let r of s){let c=[];r.isConnected?c.push("\u2713 connected"):r.isPending&&c.push("\u23F3 pending"),r.weVisitedThem&&c.push("\u{1F441} we visited"),r.isDiscovered&&c.push("\u{1F4CB} discovered");let l=c.length?` [${c.join(", ")}]`:"";console.log(` ${r.name} (${r.connectionDegree||"?"})${l}`),r.title&&console.log(` ${r.title.slice(0,70)}`)}if(Me&&s.length>0){C.existsSync(ce)||C.mkdirSync(ce,{recursive:!0});let r={scans:[]};try{C.existsSync(U)&&(r=JSON.parse(C.readFileSync(U,"utf-8")))}catch{}r.scans.push({scanDate:new Date().toISOString(),viewerCount:s.length,viewers:s});let c=Date.now()-90*24*60*60*1e3;r.scans=r.scans.filter(l=>new Date(l.scanDate).getTime()>c),C.writeFileSync(U,JSON.stringify(r,null,2)),console.log(`
|
|
62
|
+
Saved ${s.length} viewers to ${U}`)}let i={viewers:s.length,connected:s.filter(r=>r.isConnected).length,weVisitedFirst:s.filter(r=>r.weVisitedThem).length};console.log(`
|
|
63
|
+
Summary: ${i.viewers} viewers, ${i.connected} connected, ${i.weVisitedFirst} we visited first`),Q(e,"success",i)}catch(t){console.error(`
|
|
64
|
+
Error:`,t.message),Q(e,"error",null,t.message)}finally{await o.close().catch(()=>{})}}yo().catch(e=>{console.error("Viewers failed:",e),process.exit(1)});
|