ilml-plugin-linkedin 1.20.18 → 1.20.19
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 -1
- package/dist/applyQueue.mjs +18 -20
- package/dist/connect.mjs +72 -74
- package/dist/daily.mjs +27 -29
- package/dist/enrichProfiles.mjs +26 -28
- package/dist/funnelRunner.mjs +41 -42
- package/dist/messageBot.mjs +56 -58
- package/dist/run.mjs +28 -30
- package/dist/scout.mjs +42 -44
- package/dist/syncAll.mjs +74 -76
- package/dist/syncConnections.mjs +30 -32
- package/dist/version.mjs +1 -1
- package/dist/viewers.mjs +36 -38
- package/dist/visit.mjs +33 -35
- package/ilml-plugin.json +1 -1
- package/package.json +1 -1
package/dist/daily.mjs
CHANGED
|
@@ -1,53 +1,51 @@
|
|
|
1
|
-
var Ue=Object.defineProperty;var q=(e,o)=>{for(var t in o)Ue(e,t,{get:o[t],enumerable:!0})};import{execFileSync as
|
|
1
|
+
var Ue=Object.defineProperty;var q=(e,o)=>{for(var t in o)Ue(e,t,{get:o[t],enumerable:!0})};import{execFileSync as un}from"child_process";import"dotenv/config";import*as w from"fs";import*as I from"path";import{fileURLToPath as He}from"url";import"dotenv/config";import{createGraphClient as Je,resolveToken as Be}from"@ilivemylife/graph-sdk";import{config as qe}from"dotenv";qe();var se=Be()||process.env.TOKEN;se||(console.error(`
|
|
2
2
|
[FATAL] No iLiveMyLife token found.`),console.error(" The bot uses Lifebot AI to decide which jobs to apply for"),console.error(` and how to fill application forms. It cannot work without it.
|
|
3
3
|
`),console.error(" Easiest way:"),console.error(" 1. npm install -g @ilivemylife/graph-sdk"),console.error(` 2. ilml login your@email.com yourpassword
|
|
4
4
|
`),console.error(` Or add ILML_TOKEN=... to .env
|
|
5
|
-
`),process.exit(1));var ie=Je({token:se});function Ve(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return n?`${t}m ${n}s`:`${t}m`}
|
|
6
|
-
|
|
7
|
-
${n.join(`
|
|
8
|
-
`)}`;try{await ie.addMessage(i,c)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Ge=Ye(import.meta.url),He=I.dirname(I.dirname(Ge)),Y=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(He,"collected-profiles"),G=I.join(Y,"run-log.json");function Ke(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";S.writeFileSync(n,t);for(let r=0;r<3;r++)try{S.renameSync(n,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ce(){try{if(!S.existsSync(G))return{runs:[]};let e=JSON.parse(S.readFileSync(G,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ae(e){S.existsSync(Y)||S.mkdirSync(Y,{recursive:!0});try{Ke(G,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function ue(e,o="default"){let t=ce();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,r={timestamp:n.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),ae(t),{script:e,mode:o,startTime:n.getTime(),runIndex:t.runs.length-1}}function fe(e,o,t=null,n=null){if(!e)return;let r=null;try{let i=ce(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=o,a.result=o,a.duration=Date.now()-e.startTime,a.stats=t,a.error=n,r=a.duration;else{let c=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());c&&(c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=t,c.error=n,r=c.duration)}ae(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=o==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";le({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:n,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as Xe}from"@ilivemylife/graph-sdk";var ze={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},pe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Qe(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function de(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 s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&t.set("distance",String(s)),pe(e.JOB_SEARCH_EASY_APPLY)&&t.set("f_AL","true"),pe(e.JOB_SEARCH_IN_NETWORK)&&t.set("f_JIYN","true");let i=Qe(e.JOB_SEARCH_COMPANY_IDS);i.length&&t.set("f_C",i.join(","));let a=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();a&&t.set("f_TPR",ze[a]||a),t.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let c="https://www.linkedin.com/jobs/search/?"+t.toString(),u=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return u&&(c+="&"+u),c}var Ze=await Xe();for(let[e,o]of Object.entries(Ze))process.env[e]===void 0&&(process.env[e]=o);var me=de(process.env);me&&(process.env.LINKEDIN_SEARCH_URL=me);var $n=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),En=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),jn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as eo}from"url";var oo=eo(import.meta.url),no=m.dirname(m.dirname(oo)),j=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(no,"collected-profiles"),Dn=m.join(j,"people.json"),_n=m.join(j,"jobs.json"),to=m.join(j,"quota.json"),Cn=m.join(j,"conversations.json"),Nn=m.join(j,"sync-state.json"),xn=m.join(j,"application-questions.json"),Fn=m.join(j,"profile-history"),he=(e,o)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:o},P=he(process.env.CONNECT_MAX_DAILY,20),U=he(process.env.CONNECT_MAX_WEEKLY,100),ro=null,so=null,T=null,io=null,lo=null,co=null;function ge(){ro=null,so=null,T=null,io=null,lo=null,co=null}function ao(){d.existsSync(j)||d.mkdirSync(j,{recursive:!0})}function uo(e,o){if(!d.existsSync(e))return null;try{let t=JSON.parse(d.readFileSync(e,"utf-8"));try{d.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${m.resolve(e)}`);let n=e+".backup";if(d.existsSync(n))try{let r=JSON.parse(d.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{d.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{d.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function fo(){return T||(ao(),T=uo(to,"quota.json"),(!T||!T.connections)&&(T={connections:[]}),T)}function Se(){let e=fo(),o=new Date;o.setDate(o.getDate()-7);let t=o.toISOString().split("T")[0];return e.connections.filter(n=>n.date>=t)}function be(){let e=Se(),o=ye(),t=e.filter(c=>c.date===o).length,n=e.length,r=t>=P,s=n>=U,i=!r&&!s,a={allowed:i,daily:{sent:t,max:P},weekly:{sent:n,max:U}};return i||(a.reason=r?`Daily limit reached (${t}/${P})`:`Weekly limit reached (${n}/${U})`),a}function we(){let e=Se(),o=ye(),t=e.filter(r=>r.date===o).length,n=e.length;return{daily:{sent:t,max:P,remaining:P-t},weekly:{sent:n,max:U,remaining:U-n}}}import"dotenv/config";import*as l from"fs";import*as oe from"os";import*as f from"path";import{fileURLToPath as Vo}from"url";var z={};q(z,{NAME:()=>mo,VERSION:()=>po,up:()=>yo});import*as b from"fs";import*as V from"path";var po=1,mo="normalize-jobs-and-questions",ho=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],go=50;function H(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function K(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{b.writeFileSync(n,t)}catch(r){try{b.unlinkSync(n)}catch{}throw r}try{b.renameSync(n,e)}catch(r){try{b.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function yo(e,o){let t=V.join(e,"jobs.json"),n=V.join(o,"scouted-jobs.json"),r=V.join(e,"application-questions.json"),s=H(t)||{},i=H(n)||{},a=0,c=[];for(let p of Object.keys(s)){if(!i[p])continue;let A=i[p],h=s[p];for(let R of ho)A[R]!=null&&h[R]==null&&(h[R]=A[R]);c.push(p),a++}a>0?(K(t,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=H(r);if(u&&Array.isArray(u.applications)){let p={},A=0;for(let h of u.applications){let R=h.jobId||"unknown";p[R]||(p[R]={applications:[]});let re=(h.questions||[]).map($=>{let L={type:$.type||"input",question:$.question||"",answer:$.answer||""};return $.options&&($.options.length<=go?L.options=$.options:(L.optionsOmitted=!0,A++)),$.page&&(L.page=$.page),$.wasPreFilled&&(L.wasPreFilled=!0),$.wasRetry&&(L.wasRetry=!0),L});p[R].applications.push({applicationId:h.applicationId,date:h.date,result:h.result||"submitted",formPages:h.formPages||null,duration:h.duration||null,retries:h.retries||0,failedField:h.failedField||null,questionCount:h.questionCount||re.length,questions:re})}K(r,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).length} unique jobs)`),A>0&&console.log(` Phase 2: Stripped bloated options from ${A} 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(c.length>0){for(let p of c)delete i[p];K(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Q={};q(Q,{NAME:()=>bo,VERSION:()=>So,up:()=>ko});import*as w from"fs";import*as ve from"path";var So=2,bo="reset-unread-flags";function wo(e){return w.existsSync(e)?JSON.parse(w.readFileSync(e,"utf-8")):null}function vo(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{w.writeFileSync(n,t)}catch(r){try{w.unlinkSync(n)}catch{}throw r}try{w.renameSync(n,e)}catch(r){try{w.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function ko(e){let o=ve.join(e,"conversations.json"),t=wo(o);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}vo(o,t),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var X={};q(X,{NAME:()=>$o,VERSION:()=>Ao,up:()=>Io});import*as v from"fs";import*as ke from"path";var Ao=3,$o="recompute-last-message-by",Eo=new Set(["draft","confirmed","rejected","needs_review"]);function jo(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function Oo(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{v.writeFileSync(n,t)}catch(r){try{v.unlinkSync(n)}catch{}throw r}try{v.renameSync(n,e)}catch(r){try{v.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function Ro(e,o){if(!e||e.length===0)return"them";let t=e.filter(s=>!Eo.has(s.status));if(t.length===0)return"them";let n=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=n.length>0?n:[...t].reverse();for(let s of r){let i=s.sender;if(i===o)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function Io(e){let o=ke.join(e,"conversations.json"),t=jo(o);if(!t){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,s=0,i=0;for(let a of Object.keys(t)){let c=t[a];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let u=Array.isArray(c.messages)?c.messages:[],p=Ro(u,n),A=p==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==p&&i++,c.lastMessageBy=p,c.conversationStatus=A,r++}if(r===0){console.log(" No conversations to recompute.");return}Oo(o,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Z={};q(Z,{NAME:()=>Do,VERSION:()=>To,up:()=>xo});import*as k from"fs";import*as Ae from"path";var To=4,Do="split-connection-timestamps",_o=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function Co(e){if(!k.existsSync(e))return null;let o=k.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function No(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{k.writeFileSync(n,t)}catch(r){try{k.unlinkSync(n)}catch{}throw r}try{k.renameSync(n,e)}catch(r){try{k.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function xo(e){let o=Ae.join(e,"people.json"),t=Co(o);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,_o.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}No(o,t),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".')}import"dotenv/config";import*as y from"path";import{fileURLToPath as Fo}from"url";var Lo=Fo(import.meta.url),Mo=y.dirname(y.dirname(Lo)),J=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(Mo,"market-research"),Vn=y.join(J,"scouted-jobs.json"),Wn=y.join(J,"discovered-people.json"),Yn=y.join(J,"visit-log.json"),Gn=y.join(J,"companies.json"),Hn=y.join(J,"job-decisions.json");function $e(){Po=null,Uo=null,Jo=null,Bo=null,qo=null}var Po=null;var Uo=null;var Jo=null;var Bo=null;var qo=null;var Wo=Vo(import.meta.url),Yo=f.dirname(Wo),Go=f.dirname(f.dirname(Yo));function Ho(e){return e&&(e==="~"?oe.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(oe.homedir(),e.slice(2)):e)}var E=process.env.DATA_DIR?f.resolve(Ho(process.env.DATA_DIR)):Go,x=f.join(E,"collected-profiles"),F=f.join(E,"market-research"),g=f.join(E,".schema-version"),Ee=[f.join(x,".schema-version"),f.join(F,".schema-version")],D=4,O=[{version:1,module:z},{version:2,module:Q},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((n,r)=>n.version-r.version);let o=new Set;for(let n of O){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(o.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);o.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 t=O.length?O[O.length-1].version:0;if(t!==D)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${D}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<O.length;n++){let r=n+1;if(O[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${O[n].version}`)}})();function Ie(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
5
|
+
`),process.exit(1));var ie=Je({token:se});function Ve(e){if(!e||e<1e3)return`${e||0}ms`;let o=Math.round(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return n?`${t}m ${n}s`:`${t}m`}var We={apply:"Job apply","apply-queue":"Job apply (queue)",scout:"Job scout",connect:"Connect run",funnel:"Recruiter funnel",messages:"Messages",sync:"Connections sync","sync-all":"Inbox sync",visit:"Profile visits",viewers:"Profile viewers",daily:"Daily run"};function Ye(e){let o=String(e||"").toLowerCase();return/authwall|session expired|not logged in|re-?auth|logged out|sign ?in/.test(o)?"LinkedIn asked to sign in again. Run `ilml linkedin login`, then run this again.":/protocoltimeout|callfunctionon|target closed|session closed|detached|execution context|browser.*disconnected|connection closed/.test(o)?"The browser stopped responding partway through. This is usually temporary \u2014 just run it again.":/err_aborted|err_network|err_connection|err_name_not_resolved|net::/.test(o)?"A page failed to load (network hiccup). Try running it again in a moment.":/navigation timeout|timeout.*exceeded|waiting for selector|waiting for/.test(o)?"A page took too long to load. Try again in a moment.":/invite limit|weekly.*limit|too many|rate.?limit|quota/.test(o)?"You've reached a LinkedIn sending limit for now. Wait a while, then try again.":"Something went wrong partway through. It is safe to run the command again."}function Ge({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s}){let i=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",a=t==="error"?"stopped early":t==="quota-reached"?"daily limit reached":"done",c=We[e]||e,u=o&&o!=="default"?` \xB7 ${o}`:"",f=new Date().toISOString().slice(0,16).replace("T"," "),S=s?` \xB7 ${Ve(s)}`:"",d=[];d.push(`## ${i} ${c} \u2014 ${a}`),d.push(`_${f}${u}${S}_`),d.push("");for(let g of n)d.push(`- ${g}`);if(t==="error"){d.push(""),d.push(`**What happened:** ${Ye(r)}`);let g=String(r||"").replace(/\s+/g," ").trim();g&&d.push(`_Technical detail: ${g.slice(0,140)}_`)}return d.join(`
|
|
6
|
+
`)}async function le({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(n)||n.length===0)return;let a=Ge({scriptName:e,mode:o,status:t,summaryLines:n,error:r,duration:s});try{await ie.addMessage(i,a)}catch(c){console.error(`[runReport] Failed to post end-of-session message: ${c.message}`)}}var Ke=He(import.meta.url),ze=I.dirname(I.dirname(Ke)),Y=process.env.DATA_DIR?I.resolve(process.env.DATA_DIR,"collected-profiles"):I.join(ze,"collected-profiles"),G=I.join(Y,"run-log.json");function Qe(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";w.writeFileSync(n,t);for(let r=0;r<3;r++)try{w.renameSync(n,e);return}catch(s){if(r<2&&(s.code==="EPERM"||s.code==="EBUSY")){let i=Date.now();for(;Date.now()-i<200;);continue}throw s}}function ce(){try{if(!w.existsSync(G))return{runs:[]};let e=JSON.parse(w.readFileSync(G,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ae(e){w.existsSync(Y)||w.mkdirSync(Y,{recursive:!0});try{Qe(G,e)}catch(o){console.error(`[!] Failed to save run-log.json: ${o.message}`)}}function ue(e,o="default"){let t=ce();for(let i of t.runs)i.status==="running"&&(i.status="interrupted",i.result="interrupted",i.timestamp&&(i.duration=Date.now()-new Date(i.timestamp).getTime()));let n=new Date,r={timestamp:n.toISOString(),script:e,mode:o,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(r);let s=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>s),ae(t),{script:e,mode:o,startTime:n.getTime(),runIndex:t.runs.length-1}}function fe(e,o,t=null,n=null){if(!e)return;let r=null;try{let i=ce(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=o,a.result=o,a.duration=Date.now()-e.startTime,a.stats=t,a.error=n,r=a.duration;else{let c=i.runs.find(u=>u.script===e.script&&u.status==="running"&&u.timestamp===new Date(e.startTime).toISOString());c&&(c.status=o,c.result=o,c.duration=Date.now()-e.startTime,c.stats=t,c.error=n,r=c.duration)}ae(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let s=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(s&&s.length>0&&process.env.NODE_RUN_REPORTS){let i=o==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";le({scriptName:e.script,mode:e.mode,status:i,summaryLines:s,error:n,duration:r??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as eo}from"@ilivemylife/graph-sdk";var Xe={day:"r86400","24h":"r86400",today:"r86400",week:"r604800","7d":"r604800",month:"r2592000","30d":"r2592000"},pe=e=>/^(1|true|yes|on)$/i.test(String(e??"").trim());function Ze(e){return String(e??"").split(/[,\s|]+/).map(o=>o.trim()).filter(Boolean)}function de(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 s=parseInt(e.JOB_SEARCH_RADIUS_MILES,10);Number.isFinite(s)&&s>0&&t.set("distance",String(s)),pe(e.JOB_SEARCH_EASY_APPLY)&&t.set("f_AL","true"),pe(e.JOB_SEARCH_IN_NETWORK)&&t.set("f_JIYN","true");let i=Ze(e.JOB_SEARCH_COMPANY_IDS);i.length&&t.set("f_C",i.join(","));let a=(e.JOB_SEARCH_DATE_POSTED||"").trim().toLowerCase();a&&t.set("f_TPR",Xe[a]||a),t.set("origin","JOB_SEARCH_PAGE_JOB_FILTER");let c="https://www.linkedin.com/jobs/search/?"+t.toString(),u=(e.JOB_SEARCH_EXTRA_PARAMS||"").trim().replace(/^[?&]+/,"");return u&&(c+="&"+u),c}var oo=await eo();for(let[e,o]of Object.entries(oo))process.env[e]===void 0&&(process.env[e]=o);var me=de(process.env);me&&(process.env.LINKEDIN_SEARCH_URL=me);var jn=process.env.LINKEDIN_NAME,C=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Rn=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.NEEDS_REVIEW])),On=Object.freeze(new Set([C.DRAFT,C.CONFIRMED,C.REJECTED,C.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as h from"path";import{fileURLToPath as no}from"url";var to=no(import.meta.url),ro=h.dirname(h.dirname(to)),R=process.env.DATA_DIR?h.resolve(process.env.DATA_DIR,"collected-profiles"):h.join(ro,"collected-profiles"),Cn=h.join(R,"people.json"),Nn=h.join(R,"jobs.json"),so=h.join(R,"quota.json"),xn=h.join(R,"conversations.json"),Fn=h.join(R,"sync-state.json"),Ln=h.join(R,"application-questions.json"),Mn=h.join(R,"profile-history"),he=(e,o)=>{let t=parseInt(e,10);return Number.isInteger(t)&&t>=0?t:o},P=he(process.env.CONNECT_MAX_DAILY,20),U=he(process.env.CONNECT_MAX_WEEKLY,100),io=null,lo=null,T=null,co=null,ao=null,uo=null;function ge(){io=null,lo=null,T=null,co=null,ao=null,uo=null}function fo(){m.existsSync(R)||m.mkdirSync(R,{recursive:!0})}function po(e,o){if(!m.existsSync(e))return null;try{let t=JSON.parse(m.readFileSync(e,"utf-8"));try{m.copyFileSync(e,e+".backup")}catch{}return t}catch(t){console.error(`[!] ${o} is corrupted: ${t.message}`),console.error(` File: ${h.resolve(e)}`);let n=e+".backup";if(m.existsSync(n))try{let r=JSON.parse(m.readFileSync(n,"utf-8"));console.error(` Restored from ${n}`);try{m.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{m.copyFileSync(e,e+".corrupted")}catch{}return null}}function ye(){return new Date().toISOString().split("T")[0]}function mo(){return T||(fo(),T=po(so,"quota.json"),(!T||!T.connections)&&(T={connections:[]}),T)}function Se(){let e=mo(),o=new Date;o.setDate(o.getDate()-7);let t=o.toISOString().split("T")[0];return e.connections.filter(n=>n.date>=t)}function be(){let e=Se(),o=ye(),t=e.filter(c=>c.date===o).length,n=e.length,r=t>=P,s=n>=U,i=!r&&!s,a={allowed:i,daily:{sent:t,max:P},weekly:{sent:n,max:U}};return i||(a.reason=r?`Daily limit reached (${t}/${P})`:`Weekly limit reached (${n}/${U})`),a}function we(){let e=Se(),o=ye(),t=e.filter(r=>r.date===o).length,n=e.length;return{daily:{sent:t,max:P,remaining:P-t},weekly:{sent:n,max:U,remaining:U-n}}}import"dotenv/config";import*as l from"fs";import*as oe from"os";import*as p from"path";import{fileURLToPath as Yo}from"url";var z={};q(z,{NAME:()=>go,VERSION:()=>ho,up:()=>bo});import*as v from"fs";import*as V from"path";var ho=1,go="normalize-jobs-and-questions",yo=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],So=50;function H(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function K(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{v.writeFileSync(n,t)}catch(r){try{v.unlinkSync(n)}catch{}throw r}try{v.renameSync(n,e)}catch(r){try{v.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function bo(e,o){let t=V.join(e,"jobs.json"),n=V.join(o,"scouted-jobs.json"),r=V.join(e,"application-questions.json"),s=H(t)||{},i=H(n)||{},a=0,c=[];for(let f of Object.keys(s)){if(!i[f])continue;let S=i[f],d=s[f];for(let g of yo)S[g]!=null&&d[g]==null&&(d[g]=S[g]);c.push(f),a++}a>0?(K(t,s),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=H(r);if(u&&Array.isArray(u.applications)){let f={},S=0;for(let d of u.applications){let g=d.jobId||"unknown";f[g]||(f[g]={applications:[]});let re=(d.questions||[]).map(E=>{let L={type:E.type||"input",question:E.question||"",answer:E.answer||""};return E.options&&(E.options.length<=So?L.options=E.options:(L.optionsOmitted=!0,S++)),E.page&&(L.page=E.page),E.wasPreFilled&&(L.wasPreFilled=!0),E.wasRetry&&(L.wasRetry=!0),L});f[g].applications.push({applicationId:d.applicationId,date:d.date,result:d.result||"submitted",formPages:d.formPages||null,duration:d.duration||null,retries:d.retries||0,failedField:d.failedField||null,questionCount:d.questionCount||re.length,questions:re})}K(r,f),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(f).length} unique jobs)`),S>0&&console.log(` Phase 2: Stripped bloated options from ${S} 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(c.length>0){for(let f of c)delete i[f];K(n,i),console.log(` Phase 3: Removed ${c.length} merged entries from scouted-jobs.json (${Object.keys(i).length} remaining)`)}else console.log(" Phase 3: No entries to remove from scouted-jobs.json")}var Q={};q(Q,{NAME:()=>vo,VERSION:()=>wo,up:()=>$o});import*as k from"fs";import*as ve from"path";var wo=2,vo="reset-unread-flags";function ko(e){return k.existsSync(e)?JSON.parse(k.readFileSync(e,"utf-8")):null}function Ao(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{k.writeFileSync(n,t)}catch(r){try{k.unlinkSync(n)}catch{}throw r}try{k.renameSync(n,e)}catch(r){try{k.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function $o(e){let o=ve.join(e,"conversations.json"),t=ko(o);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let n=0;for(let r of Object.keys(t))t[r].unread===!0&&(t[r].unread=!1,n++);if(n===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}Ao(o,t),console.log(` Reset unread=false on ${n} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var X={};q(X,{NAME:()=>jo,VERSION:()=>Eo,up:()=>_o});import*as A from"fs";import*as ke from"path";var Eo=3,jo="recompute-last-message-by",Ro=new Set(["draft","confirmed","rejected","needs_review"]);function Oo(e){return A.existsSync(e)?JSON.parse(A.readFileSync(e,"utf-8")):null}function Io(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{A.writeFileSync(n,t)}catch(r){try{A.unlinkSync(n)}catch{}throw r}try{A.renameSync(n,e)}catch(r){try{A.unlinkSync(n)}catch{}if(r.code==="EPERM"||r.code==="EBUSY"){let s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}function To(e,o){if(!e||e.length===0)return"them";let t=e.filter(s=>!Ro.has(s.status));if(t.length===0)return"them";let n=t.map(s=>({m:s,t:Date.parse(s.time)})).filter(s=>Number.isFinite(s.t)).sort((s,i)=>i.t-s.t).map(s=>s.m),r=n.length>0?n:[...t].reverse();for(let s of r){let i=s.sender;if(i===o)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function _o(e){let o=ke.join(e,"conversations.json"),t=Oo(o);if(!t){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,s=0,i=0;for(let a of Object.keys(t)){let c=t[a];if(!c||typeof c!="object")continue;Object.prototype.hasOwnProperty.call(c,"_cardSynced")&&(delete c._cardSynced,s++);let u=Array.isArray(c.messages)?c.messages:[],f=To(u,n),S=f==="me"?"awaiting_reply":"unanswered_by_us";c.lastMessageBy!==f&&i++,c.lastMessageBy=f,c.conversationStatus=S,r++}if(r===0){console.log(" No conversations to recompute.");return}Io(o,t),console.log(` Recomputed lastMessageBy + conversationStatus on ${r} conversations.`),console.log(` ${i} had stale lastMessageBy (now corrected).`),s>0&&console.log(` Cleaned ${s} leftover _cardSynced flags.`),console.log(" Re-run 'ilml linkedin enrich' if you want actionNeeded / summary / autoTags to also update.")}var Z={};q(Z,{NAME:()=>Co,VERSION:()=>Do,up:()=>Lo});import*as $ from"fs";import*as Ae from"path";var Do=4,Co="split-connection-timestamps",No=new Set(["pending","sent_without_note","sent_with_note","sent_without_note_upsell"]);function xo(e){if(!$.existsSync(e))return null;let o=$.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Fo(e,o){let t=JSON.stringify(o,null,2),n=e+".tmp";try{$.writeFileSync(n,t)}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 s=new Error(`File locked: ${e} (${r.code}). On Windows usually antivirus / file explorer / open editor. Close it and re-run.`);throw s.code=r.code,s}throw r}}async function Lo(e){let o=Ae.join(e,"people.json"),t=xo(o);if(!t||typeof t!="object"){console.log(" people.json not found \u2014 nothing to migrate.");return}let n=0,r=0;for(let s of Object.keys(t)){let i=t[s];!i||typeof i!="object"||(r++,No.has(i.connectionStatus)&&i.connectionDate&&!i.requestedConnectionAt&&(i.requestedConnectionAt=i.connectionDate,i.connectionDate=null,n++))}if(n===0){console.log(` Scanned ${r} people \u2014 none needed the connectionDate\u2192requestedConnectionAt move.`);return}Fo(o,t),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".')}import"dotenv/config";import*as b from"path";import{fileURLToPath as Mo}from"url";var Po=Mo(import.meta.url),Uo=b.dirname(b.dirname(Po)),J=process.env.DATA_DIR?b.resolve(process.env.DATA_DIR,"market-research"):b.join(Uo,"market-research"),Yn=b.join(J,"scouted-jobs.json"),Gn=b.join(J,"discovered-people.json"),Hn=b.join(J,"visit-log.json"),Kn=b.join(J,"companies.json"),zn=b.join(J,"job-decisions.json");function $e(){Jo=null,Bo=null,qo=null,Vo=null,Wo=null}var Jo=null;var Bo=null;var qo=null;var Vo=null;var Wo=null;var Go=Yo(import.meta.url),Ho=p.dirname(Go),Ko=p.dirname(p.dirname(Ho));function zo(e){return e&&(e==="~"?oe.homedir():e.startsWith("~/")||e.startsWith("~\\")?p.join(oe.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?p.resolve(zo(process.env.DATA_DIR)):Ko,x=p.join(j,"collected-profiles"),F=p.join(j,"market-research"),y=p.join(j,".schema-version"),Ee=[p.join(x,".schema-version"),p.join(F,".schema-version")],_=4,O=[{version:1,module:z},{version:2,module:Q},{version:3,module:X},{version:4,module:Z}];(function(){O.sort((n,r)=>n.version-r.version);let o=new Set;for(let n of O){if(!Number.isInteger(n.version)||n.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(n.version)} (must be positive integer)`);if(o.has(n.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${n.version}`);o.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 t=O.length?O[O.length-1].version:0;if(t!==_)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${_}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let n=0;n<O.length;n++){let r=n+1;if(O[n].version!==r)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${r} at position ${n} but found v${O[n].version}`)}})();function Ie(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
9
7
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
10
|
-
`),process.exit(1));try{l.mkdirSync(
|
|
11
|
-
[FATAL] Cannot create DATA_DIR (${
|
|
12
|
-
`),process.exit(1))}let e;try{e=l.statSync(
|
|
13
|
-
[FATAL] DATA_DIR (${
|
|
8
|
+
`),process.exit(1));try{l.mkdirSync(j,{recursive:!0})}catch(o){o.code!=="EEXIST"&&(console.error(`
|
|
9
|
+
[FATAL] Cannot create DATA_DIR (${j}): ${o.message}`),console.error(` Fix the path or permissions and try again.
|
|
10
|
+
`),process.exit(1))}let e;try{e=l.statSync(j)}catch(o){console.error(`
|
|
11
|
+
[FATAL] DATA_DIR (${j}) is not accessible: ${o.message}
|
|
14
12
|
`),process.exit(1)}e.isDirectory()||(console.error(`
|
|
15
|
-
[FATAL] DATA_DIR (${
|
|
13
|
+
[FATAL] DATA_DIR (${j}) exists but is NOT a directory.`),console.error(` Looks like a typo \u2014 your DATA_DIR points at a file. Fix the path and try again.
|
|
16
14
|
`),process.exit(1));for(let o of[x,F]){let t;try{t=l.lstatSync(o)}catch(n){if(n.code==="ENOENT")continue;throw n}t.isSymbolicLink()&&(console.error(`
|
|
17
15
|
[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.
|
|
18
|
-
`),process.exit(1))}}var N=
|
|
16
|
+
`),process.exit(1))}}var N=p.join(j,".migration-lock");function Qo(){let e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()},null,2);try{return l.writeFileSync(N,e,{flag:"wx"}),!0}catch(n){if(n.code!=="EEXIST")throw n}let o;try{o=JSON.parse(l.readFileSync(N,"utf-8"))}catch{o=null}if(o&&Number.isInteger(o.pid)){let n=!1;try{process.kill(o.pid,0),n=!0}catch(i){i.code==="EPERM"&&(n=!0)}let r=24*60*60*1e3,s=1/0;if(o.startedAt){let i=Date.parse(o.startedAt);Number.isNaN(i)||(s=Date.now()-i)}n&&s<r&&(console.error(`
|
|
19
17
|
[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}
|
|
20
18
|
`),console.error(" Wait for it to finish, or if you're sure it's not actually running,"),console.error(` delete the lock file manually and re-run.
|
|
21
|
-
`),process.exit(1)),n&&s>=r&&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 t=N+".tmp";try{return l.writeFileSync(t,e),l.renameSync(t,N),!0}catch(n){try{l.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function ne(){try{if(JSON.parse(l.readFileSync(N,"utf-8")).pid!==process.pid)return;l.unlinkSync(N)}catch{}}var je=!1;function
|
|
19
|
+
`),process.exit(1)),n&&s>=r&&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 t=N+".tmp";try{return l.writeFileSync(t,e),l.renameSync(t,N),!0}catch(n){try{l.unlinkSync(t)}catch{}throw new Error(`Failed to take over stale migration lock: ${n.message}`)}}function ne(){try{if(JSON.parse(l.readFileSync(N,"utf-8")).pid!==process.pid)return;l.unlinkSync(N)}catch{}}var je=!1;function Xo(){if(je)return;je=!0;let e=()=>{try{ne()}catch{}process.exit(1)};for(let o of["SIGINT","SIGTERM","SIGHUP"])try{process.on(o,e)}catch{}}function Zo(){if(l.existsSync(y))return;let e=[],o=[];for(let s of Ee)if(l.existsSync(s))try{e.push({file:s,schema:W(s)})}catch(i){o.push({file:s,err:i.message})}if(o.length>0){console.error(`
|
|
22
20
|
[FATAL] Legacy .schema-version file(s) corrupted \u2014 cannot determine current schema version:`);for(let s of o)console.error(` ${s.file}: ${s.err}`);console.error(`
|
|
23
21
|
Repair the file(s) (likely just an integer 'version' field \u2014 see another working DATA_DIR`),console.error(` or default to {"version":1,"migrations":[]} if you're sure you're on schema v1) and try again.
|
|
24
22
|
`),process.exit(1)}if(e.length===0)return;let t=e.map(s=>s.schema.version);if(new Set(t).size>1){console.error(`
|
|
25
23
|
[FATAL] Legacy .schema-version files disagree:`);for(let s of e)console.error(` ${s.file}: v${s.schema.version}`);console.error(" This means a previous migration crashed between writing the two files."),console.error(` Reconcile manually (delete the wrong one, keep the right one), then re-run.
|
|
26
|
-
`),process.exit(1)}let n=e[0].schema,r=
|
|
27
|
-
[FATAL] ${
|
|
28
|
-
`),process.exit(1)}let o=
|
|
29
|
-
[FATAL] ${
|
|
30
|
-
`),process.exit(1)),o}function Te(e){try{l.chmodSync(e,384)}catch{}}function
|
|
31
|
-
[FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${
|
|
32
|
-
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${
|
|
24
|
+
`),process.exit(1)}let n=e[0].schema,r=y+".tmp";try{l.writeFileSync(r,JSON.stringify(n,null,2)),l.renameSync(r,y)}catch(s){try{l.unlinkSync(r)}catch{}throw s}for(let s of Ee)if(l.existsSync(s))try{l.unlinkSync(s)}catch{}console.log(` Consolidated legacy .schema-version files \u2192 ${y}`)}function en(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 W(e){let o=l.readFileSync(e,"utf-8");return o.charCodeAt(0)===65279&&(o=o.slice(1)),JSON.parse(o)}function Re(){if(Zo(),!l.existsSync(y))return{version:0,migrations:[]};let e;try{e=W(y)}catch(t){if(t.code==="ENOENT")return{version:0,migrations:[]};console.error(`
|
|
25
|
+
[FATAL] ${y} is not valid JSON: ${t.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.
|
|
26
|
+
`),process.exit(1)}let o=en(e);return o===null&&(console.error(`
|
|
27
|
+
[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.
|
|
28
|
+
`),process.exit(1)),o}function Te(e){try{l.chmodSync(e,384)}catch{}}function on(e){if(Ie(),l.existsSync(y))try{if(l.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(t){if(t.message?.includes("symbolic link"))throw t}let o=y+".tmp";try{l.writeFileSync(o,JSON.stringify(e,null,2)),Te(o),l.renameSync(o,y)}catch(t){try{l.unlinkSync(o)}catch{}throw t}}function Oe(e,o){if(!l.existsSync(e))return;let t=`.pre-v${String(o).padStart(3,"0")}.backup`,n=l.readdirSync(e).filter(a=>{let c=a.toLowerCase();if(c.includes(".backup")||c===".schema-version"||c.endsWith(".tmp"))return!1;try{return l.statSync(p.join(e,a)).isFile()}catch{return!1}}),r=0,s=0,i=[];for(let a of n){let c=p.join(e,a),u=p.join(e,a+t);if(l.existsSync(u)){s++;continue}try{De(c,u),r++}catch(f){i.push({file:a,err:f.message})}}if(i.length>0){let a=new Error(`Failed to back up ${i.length} file(s) in ${p.basename(e)}/: `+i.map(c=>`${c.file} (${c.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(r>0||s>0){let a=s>0?` (${s} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${r} files in ${p.basename(e)}/ (${t})${a}`)}}var ee=!1;async function _e(){if(ee)return;Ie(),ln();let o=Re().version;if(o===_){ee=!0;return}Xo(),Qo(),process.on("exit",ne),o>_&&(console.error(`
|
|
29
|
+
[FATAL] Your data schema is at v${o}, but this plugin build only understands up to v${_}.`),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.
|
|
30
|
+
`),console.error(" Options:"),console.error(" A) Re-install the newer plugin version that produced this schema, then"),console.error(" (if you really want to downgrade) run 'rollback-data --confirm' first,"),console.error(" then re-install the older plugin version."),console.error(` B) Manually restore your data from the *.pre-vNNN.backup files matching v${_}.
|
|
33
31
|
`),process.exit(1)),console.log(`
|
|
34
|
-
\u{1F4E6} Schema migration: v${o} \u2192 v${
|
|
32
|
+
\u{1F4E6} Schema migration: v${o} \u2192 v${_}`);let t=cn();if(!t.ok){console.error(`
|
|
35
33
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let r of t.broken)console.error(` ${r.dir}/${r.file}: ${r.err}`);console.error(`
|
|
36
34
|
Migration ABORTED. No backups taken, no files modified.`),console.error(" Repair the file(s) above (restore from your own backup, or fix manually)"),console.error(` and try again. To inspect: 'ilml linkedin migrate-status'.
|
|
37
35
|
`),process.exit(1)}let n=O.filter(r=>r.version>o);for(let r of n){console.log(`
|
|
38
|
-
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{
|
|
36
|
+
Running migration v${String(r.version).padStart(3,"0")}...`);let s=`v${String(r.version).padStart(3,"0")}`,i=`.pre-${s}.backup`;try{Oe(x,r.version),Oe(F,r.version)}catch(c){console.error(`
|
|
39
37
|
[FATAL] Pre-migration backup failed for ${s}: ${c.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
40
38
|
`),process.exit(1)}let a=r.module;try{await a.up(x,F)}catch(c){console.error(`
|
|
41
|
-
[FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=
|
|
39
|
+
[FATAL] Migration ${s} failed: ${c.message}`),console.error(` Attempting auto-rollback from ${i} files...`);try{let u=an(i);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.
|
|
42
40
|
`)):(console.error(` [!] Auto-rollback INCOMPLETE: ${u.error}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
43
41
|
`))}catch(u){console.error(` [!] Auto-rollback CRASHED while restoring: ${u.message}`),console.error(` Manual recovery: copy *${i} files back over the originals.
|
|
44
|
-
`)}process.exit(1)}try{let c=new Date().toISOString(),u={version:r.version,name:a.NAME||s,appliedAt:c},
|
|
42
|
+
`)}process.exit(1)}try{let c=new Date().toISOString(),u={version:r.version,name:a.NAME||s,appliedAt:c},f=Re();f.version=r.version,f.migratedAt=c,f.migrations=f.migrations||[],f.migrations.push(u),on(f)}catch(c){console.error(`
|
|
45
43
|
[FATAL] Migration ${s} applied successfully but schema version file could NOT be updated: ${c.message}`),console.error(` Your data is in the v${r.version} state but .schema-version still shows v${o}.`),console.error(` On next plugin command the runner will try to re-apply ${s}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
46
44
|
`),process.exit(1)}console.log(` \u2713 Migration ${s} complete`)}try{ge()}catch{}try{$e()}catch{}ee=!0,ne(),console.log(`
|
|
47
|
-
\u2713 Schema is now at v${
|
|
48
|
-
`)}var
|
|
49
|
-
${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Fe)return console.log(` [DRY RUN] Would run: node ${o} ${t.join(" ")}`),!0;try{return
|
|
50
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` DAILY PIPELINE (${e})`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let o=Pe.filter(
|
|
51
|
-
\u26A0 Funnel skipped: ${s.reason}`),n.funnel="skipped_quota")}
|
|
45
|
+
\u2713 Schema is now at v${_}
|
|
46
|
+
`)}var nn=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function tn(e){let o=e.toLowerCase();return nn.some(t=>t.test(o))}var rn=6e4;function sn(){let e=Date.now(),o=[];for(let t of[j,x,F]){if(!l.existsSync(t))continue;let n;try{n=l.readdirSync(t)}catch{continue}for(let r of n){if(!tn(r))continue;let s=p.join(t,r);try{let i=l.statSync(s);if(!i.isFile()||e-i.mtimeMs<rn)continue;o.push({dir:t,file:r,fullPath:s})}catch{}}}return o}function ln({verbose:e=!1}={}){let o=sn();if(o.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let n of o)try{l.unlinkSync(n.fullPath),t++,e&&console.log(` Removed orphan: ${p.basename(n.dir)}/${n.file}`)}catch(r){console.warn(` [!] Could not remove orphan ${n.fullPath}: ${r.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function cn(){let e=[];for(let o of[x,F]){if(!l.existsSync(o))continue;let t=l.readdirSync(o).filter(n=>{let r=n.toLowerCase();return r.endsWith(".json")&&!r.includes(".backup")});for(let n of t){let r=p.join(o,n);try{W(r)}catch(s){e.push({dir:p.basename(o),file:n,err:s.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function an(e){let o=[],t=[];for(let s of[x,F]){if(!l.existsSync(s))continue;let i=l.readdirSync(s).filter(a=>a.endsWith(e));for(let a of i){let c=p.join(s,a),u=a.slice(0,-e.length),f=p.join(s,u);try{u.toLowerCase().endsWith(".json")?W(c):l.accessSync(c,l.constants.R_OK),o.push({backupPath:c,originalPath:f,fileName:a,dir:s})}catch(S){t.push(`${p.basename(s)}/${a}: ${S.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let n=0,r=[];for(let{backupPath:s,originalPath:i,fileName:a,dir:c}of o)try{De(s,i),n++}catch(u){r.push(`${p.basename(c)}/${a}: ${u.message}`)}return r.length>0?{ok:!1,error:r.join("; "),restored:n}:{ok:!0,restored:n}}function De(e,o){let t=o+".tmp";try{l.copyFileSync(e,t),Te(t)}catch(n){try{l.unlinkSync(t)}catch{}throw n}try{l.renameSync(t,o)}catch(n){try{l.unlinkSync(t)}catch{}if(n.code==="EPERM"||n.code==="EBUSY"){let r=new Error(`File locked: ${o} (${n.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw r.code=n.code,r}throw n}}await _e();var B=process.argv.slice(2),te=new Set((B.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Ce=new Set((B.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Fe=B.includes("--dry-run"),Le=B.includes("--jobs"),Me=B.includes("--comms"),Ne=["apply-queue","apply","funnel","scout","visit"],xe=["sync","today"],Pe=Le?Ne:Me?xe:[...Ne,...xe];function D(e){return Ce.size>0?Ce.has(e):!te.has(e)&&Pe.includes(e)}function M(e,o,t=[],{optional:n=!1}={}){if(console.log(`
|
|
47
|
+
${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Fe)return console.log(` [DRY RUN] Would run: node ${o} ${t.join(" ")}`),!0;try{return un("node",[o,...t],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${e} completed`),!0}catch(r){return n?(console.log(` \u26A0 ${e} failed (optional): ${r.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${e} failed: ${r.message?.slice(0,80)}`),!1)}}async function fn(){let e=Le?"jobs":Me?"comms":"full";console.log(`
|
|
48
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(` DAILY PIPELINE (${e})`),console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");let o=Pe.filter(D);console.log(` Steps: ${o.join(" \u2192 ")}`),te.size>0&&console.log(` Skipping: ${[...te].join(", ")}`),Fe&&console.log(" [DRY RUN MODE]");let t=ue("daily",e),n={};if(D("apply-queue")&&(n["apply-queue"]=M("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),D("apply")){let s=we();n.apply=M("Apply from Search","run.mjs",[],{optional:!0})}if(D("funnel")&&!D("apply")){let s=be();s.allowed?n.funnel=M("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
|
|
49
|
+
\u26A0 Funnel skipped: ${s.reason}`),n.funnel="skipped_quota")}D("scout")&&(n.scout=M("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),D("sync")&&(n.sync=M("Sync Inbox","syncAll.mjs")),D("today")&&(n.today=M("Daily Report","syncAll.mjs",["--today"])),console.log(`
|
|
52
50
|
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\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(" PIPELINE 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");for(let[s,i]of Object.entries(n))console.log(` ${i===!0?"\u2713":i===!1?"\u2717":"\u26A0"} ${s}: ${i===!0?"success":i===!1?"failed":i}`);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
|
|
53
|
-
`);let r=Object.values(n).some(s=>s===!1);fe(t,r?"partial":"success",n)}
|
|
51
|
+
`);let r=Object.values(n).some(s=>s===!1);fe(t,r?"partial":"success",n)}fn().catch(e=>{console.error("Daily pipeline failed:",e),process.exit(1)});
|