ilml-plugin-linkedin 1.11.9 → 1.13.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 +41 -1
- package/README.md +7 -1
- package/dist/daily.mjs +4 -4
- package/dist/enrichProfile.mjs +264 -0
- package/dist/enrichProfiles.mjs +302 -47
- package/dist/funnelRunner.mjs +263 -51
- package/dist/help.mjs +15 -0
- package/dist/messageBot.mjs +11 -11
- package/dist/profileHistory.mjs +5 -5
- package/dist/readPost.mjs +70 -0
- package/dist/run.mjs +265 -53
- package/dist/syncAll.mjs +317 -90
- package/dist/verifyAbout.mjs +220 -8
- package/dist/viewers.mjs +9 -9
- package/dist/visit.mjs +259 -47
- package/ilml-plugin.json +210 -24
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,7 +1,47 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.13.0 (in development)
|
|
4
|
+
|
|
5
|
+
**1. Read full LinkedIn profile in one command.**
|
|
6
|
+
```
|
|
7
|
+
ilml linkedin enrich-profile <url> --full
|
|
8
|
+
```
|
|
9
|
+
Pulls Experience, Education, Skills, Recommendations, Certifications, Featured. Use on your own profile to audit, or on a contact before reaching out. For one section only: `--with-experience` / `--with-education` / etc.
|
|
10
|
+
|
|
11
|
+
**2. After sync, deep-read profiles of people who just wrote you.**
|
|
12
|
+
```
|
|
13
|
+
ilml linkedin sync-all --auto-enrich-replies
|
|
14
|
+
```
|
|
15
|
+
Opt-in flag, default OFF. After pulling new messages, visits up to 3 profiles of contacts whose latest message is from them. Skips contacts enriched in the last 30 days. Try `--dry-run` first to see the list.
|
|
16
|
+
|
|
17
|
+
**3. Read & analyse a LinkedIn post with your AI.**
|
|
18
|
+
```
|
|
19
|
+
ilml linkedin read-post <url> --json # AI gets structured data
|
|
20
|
+
ilml linkedin read-post <url> --no-comments # skip 1000+ comments
|
|
21
|
+
ilml linkedin read-post <url> --save-to-graph=<nodeId> # save to your graph (opt-in)
|
|
22
|
+
```
|
|
23
|
+
Default: just print. `--json` for AI consumption. `--save-to-graph` is the only way to save — nothing auto-saves. Saved node holds only stable fields (post text, author, hashtags, mentions, media flags); live counts and comments are NOT saved (they change — re-fetch when needed).
|
|
24
|
+
|
|
25
|
+
**4. Every command now has full docs in the plugin manifest.**
|
|
26
|
+
```
|
|
27
|
+
ilml linkedin help <command>
|
|
28
|
+
```
|
|
29
|
+
AI assistants can read the manifest and know how to use any command without seeing the code.
|
|
30
|
+
|
|
31
|
+
**Schema:** no migration. New profile fields (`featured`, `education`, `skillsFull`, `recommendations`, `certifications`) are additive — appear only on records you explicitly enrich after upgrading.
|
|
32
|
+
|
|
33
|
+
## 1.12.0
|
|
34
|
+
- **`ilml linkedin enrich-profile <profile-url>` — pull the full picture on one person into your local contacts DB.** Visits the profile and saves headline, location, About, company, and other basics. Add `--with-experience` and it also pulls the structured Experience list — every role with company, dates, location, description, and skills. Single-URL, on-demand — no batch mode here. Self-profile is recognised (by URL or by your configured name) and printed to your terminal instead of being added to the contacts DB. Run `ilml linkedin enrich-profile --help` for full usage.
|
|
35
|
+
- **`ilml linkedin enrich-profiles --with-experience` — same Experience extraction, in batch.** When you batch-enrich contacts that have missing info (still capped at 10/session by default), each visit can now also pull the structured Experience. An extra ban-risk warning prints because each profile now costs 2 page loads instead of 1 — keep `--max` low.
|
|
36
|
+
- **`ilml linkedin help` — discover what every command does.** Lists all 20+ commands with short descriptions and risk levels (HIGH ban-risk ones marked ⚠). Run `ilml linkedin help <cmd>` for a detailed view of one command — usage, flags, ban-risk, when to use it.
|
|
37
|
+
- **New config field: `MY_LINKEDIN_URL`** (optional, in LinkedIn account section — visible in `ilml plugin config linkedin`). Set it to your own profile URL so `enrich-profile` can recognise your own profile precisely (more robust than the name-match fallback, especially if someone in your network has the same name).
|
|
38
|
+
- **Safer self-detection.** `enrich-profile` refuses to run if neither `MY_LINKEDIN_URL` nor `LINKEDIN_NAME` is set — without one of those it can't reliably tell own profile from a contact, so it stops rather than risk saving you into your own contacts DB.
|
|
39
|
+
- **Auth-wall awareness in batch enrichment.** If your LinkedIn session expires mid-batch (redirected to login), the script now notices and stops cleanly instead of silently burning through your daily quota writing partial records. You'll see a clear error and can `ilml linkedin login` to refresh.
|
|
40
|
+
- **Existing data is preserved on extraction failures.** If a profile visit hits a hiccup (LinkedIn DOM change, network glitch, partial load), previously-saved info on that profile is kept rather than wiped. New Experience data is additive — only appears on a profile after you explicitly enrich it. No migration needed.
|
|
41
|
+
- **Better discoverability for AI assistants.** Per-command description and ban-risk metadata now lives in the plugin manifest, so a Claude / ChatGPT / Cursor / Codex agent helping you with the plugin can read it and pick the right command without guessing.
|
|
42
|
+
|
|
3
43
|
## 1.11.9
|
|
4
|
-
- **`apply` no longer
|
|
44
|
+
- **`apply` no longer ends with "0 jobs" when the search page loads slowly.** The run scraped the job-results list the moment the page reported `DOMContentLoaded`, but on a slow connection LinkedIn finishes that event well before it paints the job cards — so the scrape came back empty, the run concluded "no jobs", and the browser closed even though jobs were on their way. Apply now waits (up to 30s) for the first job card to render before reading the list; a fast connection waits only as long as the cards actually take to appear. When the list is genuinely empty it now logs why — no cards at all (slow load, empty search, or changed markup) vs. cards present but none Easy Apply — so a "0 jobs" run is debuggable instead of silent.
|
|
5
45
|
- No schema migration; behavior fix only.
|
|
6
46
|
|
|
7
47
|
## 1.11.8
|
package/README.md
CHANGED
|
@@ -175,9 +175,15 @@ Sessions live in your active ilml scope (`<scope>/.ilivemylife/plugins-state/lin
|
|
|
175
175
|
| `ilml linkedin viewers` | Pull the "who viewed your profile" list. |
|
|
176
176
|
| `ilml linkedin warm-scan` | Find 1st-degree connections at target companies (offline, no browser). Reads your already-synced people / conversations and groups them by company so you know who you can message directly versus where you need cold outreach. Override the company list via `--companies="Anthropic,OpenAI"` or pick a named group with `--group=topPaying`. |
|
|
177
177
|
| `ilml linkedin daily` | Full pipeline in one command: `sync-all` → `apply` → `scout` → `funnel` → `visit` → `viewers` → run report. |
|
|
178
|
+
| `ilml linkedin enrich-profile <url> [--with-experience]` | Visit ONE profile by URL, save what we learn to `people.json`. Self-profile (recognised via `MY_LINKEDIN_URL` / `LINKEDIN_NAME`) prints to stdout instead of saving. `--with-experience` adds a structured experience array (2 page loads, normal human pattern). Single-URL only — no batch mode. `--help` for full details. |
|
|
179
|
+
| `ilml linkedin enrich-profiles [--with-experience]` | **⚠ HIGH BAN RISK** — batch-visit contacts with missing About text, fill basic fields. Cap 10/session by default (`--max=N` to change). `--with-experience` doubles per-profile page loads. `--connections` for lower risk (1st-degree only). `--match-title="recruiter\|founder"` to filter by role. `--list` for stats-only. `--help` for full details. |
|
|
178
180
|
| `ilml linkedin login` | Re-save LinkedIn cookies after a session expires. |
|
|
179
181
|
|
|
180
|
-
Run `ilml linkedin` (no subcommand) any time to see the list.
|
|
182
|
+
Run `ilml linkedin` (no subcommand) any time to see the list. Any command above supports `--help` for full usage and flags (the new `enrich-profile` / `enrich-profiles` definitely do; older commands print usage when called with bad arguments).
|
|
183
|
+
|
|
184
|
+
### For AI agents using this plugin
|
|
185
|
+
|
|
186
|
+
If an AI agent is figuring out how to drive this plugin, the canonical machine-readable command surface lives in [`ilml-plugin.json`](./ilml-plugin.json). The `commands` object includes per-command `description`, `usage`, `flags`, `banRisk`, and `useWhen` fields for the higher-stakes commands (`enrich-profile`, `enrich-profiles`) — read that before invoking. The `config.sections[].fields[]` array tells you which env vars are required vs optional and what each does. Per-command `--help` is the fast way to see the flag list interactively.
|
|
181
187
|
|
|
182
188
|
## Common routines
|
|
183
189
|
|
package/dist/daily.mjs
CHANGED
|
@@ -5,7 +5,7 @@ var Ce=Object.defineProperty;var W=(e,n)=>{for(var t in n)Ce(e,t,{get:n[t],enume
|
|
|
5
5
|
`),process.exit(1));var se=_e({token:te});function Le(e){if(!e||e<1e3)return`${e||0}ms`;let n=Math.round(e/1e3);if(n<60)return`${n}s`;let t=Math.floor(n/60),o=n%60;return o?`${t}m ${o}s`:`${t}m`}function Me({scriptName:e,mode:n,status:t,error:o,duration:s}){let r=t==="error"?"\u2717":t==="quota-reached"?"\u26A0":"\u2713",i=new Date().toISOString().slice(0,16).replace("T"," "),a=s?` ${Le(s)}`:"",l=t==="error"?`error${o?`: ${String(o).slice(0,80)}`:""}`:t==="quota-reached"?"daily quota reached":"done",u=n&&n!=="default"?` (${n})`:"";return`${r} ${e}${u} \u2014 ${l} \u2014 ${i}${a}`}async function re({scriptName:e,mode:n,status:t,summaryLines:o,error:s,duration:r}){let i=process.env.NODE_RUN_REPORTS;if(!i||!Array.isArray(o)||o.length===0)return;let l=`**${Me({scriptName:e,mode:n,status:t,error:s,duration:r})}**
|
|
6
6
|
|
|
7
7
|
${o.join(`
|
|
8
|
-
`)}`;try{await se.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Je=Pe(import.meta.url),Ue=R.dirname(R.dirname(Je)),q=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Ue,"collected-profiles"),Y=R.join(q,"run-log.json");function Be(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";S.writeFileSync(o,t);for(let s=0;s<3;s++)try{S.renameSync(o,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 ie(){try{if(!S.existsSync(Y))return{runs:[]};let e=JSON.parse(S.readFileSync(Y,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ce(e){S.existsSync(q)||S.mkdirSync(q,{recursive:!0});try{Be(Y,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function le(e,n="default"){let t=ie();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 o=new Date,s={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>r),ce(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function ae(e,n,t=null,o=null){if(!e)return;let s=null;try{let i=ie(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=n,a.result=n,a.duration=Date.now()-e.startTime,a.stats=t,a.error=o,s=a.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=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,s=l.duration)}ce(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";re({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as Ve}from"@ilivemylife/graph-sdk";var We=await Ve();for(let[e,n]of Object.entries(We))process.env[e]===void 0&&(process.env[e]=n);var cn=process.env.LINKEDIN_NAME,N=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ln=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.NEEDS_REVIEW])),an=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.REJECTED,N.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as qe}from"url";var Ye=qe(import.meta.url),Ge=m.dirname(m.dirname(Ye)),E=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(Ge,"collected-profiles"),mn=m.join(E,"people.json"),hn=m.join(E,"jobs.json"),He=m.join(E,"quota.json"),gn=m.join(E,"conversations.json"),yn=m.join(E,"sync-state.json"),Sn=m.join(E,"application-questions.json"),bn=m.join(E,"profile-history"),M=20,P=100,Ke=null,Qe=null,I=null,ze=null,Xe=null,Ze=null;function ue(){Ke=null,Qe=null,I=null,ze=null,Xe=null,Ze=null}function eo(){d.existsSync(E)||d.mkdirSync(E,{recursive:!0})}function oo(e,n){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(`[!] ${n} is corrupted: ${t.message}`),console.error(` File: ${m.resolve(e)}`);let o=e+".backup";if(d.existsSync(o))try{let s=JSON.parse(d.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{d.copyFileSync(o,e)}catch{}return s}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 fe(){return new Date().toISOString().split("T")[0]}function no(){return I||(eo(),I=oo(He,"quota.json"),(!I||!I.connections)&&(I={connections:[]}),I)}function pe(){let e=no(),n=new Date;n.setDate(n.getDate()-7);let t=n.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=t)}function de(){let e=pe(),n=fe(),t=e.filter(l=>l.date===n).length,o=e.length,s=t>=M,r=o>=P,i=!s&&!r,a={allowed:i,daily:{sent:t,max:M},weekly:{sent:o,max:P}};return i||(a.reason=s?`Daily limit reached (${t}/${M})`:`Weekly limit reached (${o}/${P})`),a}function me(){let e=pe(),n=fe(),t=e.filter(s=>s.date===n).length,o=e.length;return{daily:{sent:t,max:M,remaining:M-t},weekly:{sent:o,max:P,remaining:P-o}}}import"dotenv/config";import*as c from"fs";import*as Z from"os";import*as f from"path";import{fileURLToPath as Io}from"url";var K={};W(K,{NAME:()=>so,VERSION:()=>to,up:()=>co});import*as b from"fs";import*as B from"path";var to=1,so="normalize-jobs-and-questions",ro=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],io=50;function G(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function H(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{b.writeFileSync(o,t)}catch(s){try{b.unlinkSync(o)}catch{}throw s}try{b.renameSync(o,e)}catch(s){try{b.unlinkSync(o)}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 co(e,n){let t=B.join(e,"jobs.json"),o=B.join(n,"scouted-jobs.json"),s=B.join(e,"application-questions.json"),r=G(t)||{},i=G(o)||{},a=0,l=[];for(let p of Object.keys(r)){if(!i[p])continue;let w=i[p],h=r[p];for(let O of ro)w[O]!=null&&h[O]==null&&(h[O]=w[O]);l.push(p),a++}a>0?(H(t,r),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=G(s);if(u&&Array.isArray(u.applications)){let p={},w=0;for(let h of u.applications){let O=h.jobId||"unknown";p[O]||(p[O]={applications:[]});let ne=(h.questions||[]).map(k=>{let F={type:k.type||"input",question:k.question||"",answer:k.answer||""};return k.options&&(k.options.length<=io?F.options=k.options:(F.optionsOmitted=!0,w++)),k.page&&(F.page=k.page),k.wasPreFilled&&(F.wasPreFilled=!0),k.wasRetry&&(F.wasRetry=!0),F});p[O].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||ne.length,questions:ne})}H(s,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).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 p of l)delete i[p];H(o,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 Q={};W(Q,{NAME:()=>ao,VERSION:()=>lo,up:()=>po});import*as v from"fs";import*as he from"path";var lo=2,ao="reset-unread-flags";function uo(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function fo(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{v.writeFileSync(o,t)}catch(s){try{v.unlinkSync(o)}catch{}throw s}try{v.renameSync(o,e)}catch(s){try{v.unlinkSync(o)}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 po(e){let n=he.join(e,"conversations.json"),t=uo(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(t))t[s].unread===!0&&(t[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}fo(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var z={};W(z,{NAME:()=>ho,VERSION:()=>mo,up:()=>vo});import*as $ from"fs";import*as ge from"path";var mo=3,ho="recompute-last-message-by",go=new Set(["draft","confirmed","rejected","needs_review"]);function yo(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function So(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(s){try{$.unlinkSync(o)}catch{}throw s}try{$.renameSync(o,e)}catch(s){try{$.unlinkSync(o)}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 bo(e,n){if(!e||e.length===0)return"them";let t=e.filter(r=>!go.has(r.status));if(t.length===0)return"them";let o=t.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=o.length>0?o:[...t].reverse();for(let r of s){let i=r.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function vo(e){let n=ge.join(e,"conversations.json"),t=yo(n);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let a of Object.keys(t)){let l=t[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,r++);let u=Array.isArray(l.messages)?l.messages:[],p=bo(u,o),w=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&i++,l.lastMessageBy=p,l.conversationStatus=w,s++}if(s===0){console.log(" No conversations to recompute.");return}So(n,t),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.")}import"dotenv/config";import*as y from"path";import{fileURLToPath as $o}from"url";var wo=$o(import.meta.url),ko=y.dirname(y.dirname(wo)),J=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(ko,"market-research"),kn=y.join(J,"scouted-jobs.json"),jn=y.join(J,"discovered-people.json"),En=y.join(J,"visit-log.json"),An=y.join(J,"companies.json"),On=y.join(J,"job-decisions.json");function ye(){jo=null,Eo=null,Ao=null,Oo=null,Ro=null}var jo=null;var Eo=null;var Ao=null;var Oo=null;var Ro=null;var To=Io(import.meta.url),Do=f.dirname(To),No=f.dirname(f.dirname(Do));function Co(e){return e&&(e==="~"?Z.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(Z.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?f.resolve(Co(process.env.DATA_DIR)):No,_=f.join(j,"collected-profiles"),x=f.join(j,"market-research"),g=f.join(j,".schema-version"),Se=[f.join(_,".schema-version"),f.join(x,".schema-version")],T=3,A=[{version:1,module:K},{version:2,module:Q},{version:3,module:z}];(function(){A.sort((o,s)=>o.version-s.version);let n=new Set;for(let o of A){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(n.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);n.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=A.length?A[A.length-1].version:0;if(t!==T)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${T}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<A.length;o++){let s=o+1;if(A[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${A[o].version}`)}})();function we(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
8
|
+
`)}`;try{await se.addMessage(i,l)}catch(u){console.error(`[runReport] Failed to post end-of-session message: ${u.message}`)}}var Je=Pe(import.meta.url),Ue=R.dirname(R.dirname(Je)),q=process.env.DATA_DIR?R.resolve(process.env.DATA_DIR,"collected-profiles"):R.join(Ue,"collected-profiles"),Y=R.join(q,"run-log.json");function Be(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";S.writeFileSync(o,t);for(let s=0;s<3;s++)try{S.renameSync(o,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 ie(){try{if(!S.existsSync(Y))return{runs:[]};let e=JSON.parse(S.readFileSync(Y,"utf-8"));return!e.runs||!Array.isArray(e.runs)?{runs:[]}:e}catch{return{runs:[]}}}function ce(e){S.existsSync(q)||S.mkdirSync(q,{recursive:!0});try{Be(Y,e)}catch(n){console.error(`[!] Failed to save run-log.json: ${n.message}`)}}function le(e,n="default"){let t=ie();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 o=new Date,s={timestamp:o.toISOString(),script:e,mode:n,status:"running",result:null,duration:null,stats:null,error:null};t.runs.push(s);let r=Date.now()-30*24*60*60*1e3;return t.runs=t.runs.filter(i=>new Date(i.timestamp).getTime()>r),ce(t),{script:e,mode:n,startTime:o.getTime(),runIndex:t.runs.length-1}}function ae(e,n,t=null,o=null){if(!e)return;let s=null;try{let i=ie(),a=i.runs[e.runIndex];if(a&&a.status==="running"&&a.script===e.script)a.status=n,a.result=n,a.duration=Date.now()-e.startTime,a.stats=t,a.error=o,s=a.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=n,l.result=n,l.duration=Date.now()-e.startTime,l.stats=t,l.error=o,s=l.duration)}ce(i)}catch(i){console.error(`[runLog] Failed to end run: ${i.message}`)}let r=t&&Array.isArray(t.summaryLines)?t.summaryLines:null;if(r&&r.length>0&&process.env.NODE_RUN_REPORTS){let i=n==="error"?"error":t&&t.dailyLimitHit?"quota-reached":"done";re({scriptName:e.script,mode:e.mode,status:i,summaryLines:r,error:o,duration:s??Date.now()-e.startTime}).catch(a=>console.error(`[runLog] postRunReport failed: ${a.message}`))}}import{getPluginConfig as Ve}from"@ilivemylife/graph-sdk";var We=await Ve();for(let[e,n]of Object.entries(We))process.env[e]===void 0&&(process.env[e]=n);var cn=process.env.LINKEDIN_NAME,N=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),ln=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.NEEDS_REVIEW])),an=Object.freeze(new Set([N.DRAFT,N.CONFIRMED,N.REJECTED,N.NEEDS_REVIEW]));import"dotenv/config";import*as d from"fs";import*as m from"path";import{fileURLToPath as qe}from"url";var Ye=qe(import.meta.url),Ge=m.dirname(m.dirname(Ye)),A=process.env.DATA_DIR?m.resolve(process.env.DATA_DIR,"collected-profiles"):m.join(Ge,"collected-profiles"),mn=m.join(A,"people.json"),hn=m.join(A,"jobs.json"),He=m.join(A,"quota.json"),gn=m.join(A,"conversations.json"),yn=m.join(A,"sync-state.json"),Sn=m.join(A,"application-questions.json"),bn=m.join(A,"profile-history"),M=20,P=100,Ke=null,Qe=null,I=null,ze=null,Xe=null,Ze=null;function ue(){Ke=null,Qe=null,I=null,ze=null,Xe=null,Ze=null}function eo(){d.existsSync(A)||d.mkdirSync(A,{recursive:!0})}function oo(e,n){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(`[!] ${n} is corrupted: ${t.message}`),console.error(` File: ${m.resolve(e)}`);let o=e+".backup";if(d.existsSync(o))try{let s=JSON.parse(d.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{d.copyFileSync(o,e)}catch{}return s}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 fe(){return new Date().toISOString().split("T")[0]}function no(){return I||(eo(),I=oo(He,"quota.json"),(!I||!I.connections)&&(I={connections:[]}),I)}function pe(){let e=no(),n=new Date;n.setDate(n.getDate()-7);let t=n.toISOString().split("T")[0];return e.connections.filter(o=>o.date>=t)}function de(){let e=pe(),n=fe(),t=e.filter(l=>l.date===n).length,o=e.length,s=t>=M,r=o>=P,i=!s&&!r,a={allowed:i,daily:{sent:t,max:M},weekly:{sent:o,max:P}};return i||(a.reason=s?`Daily limit reached (${t}/${M})`:`Weekly limit reached (${o}/${P})`),a}function me(){let e=pe(),n=fe(),t=e.filter(s=>s.date===n).length,o=e.length;return{daily:{sent:t,max:M,remaining:M-t},weekly:{sent:o,max:P,remaining:P-o}}}import"dotenv/config";import*as c from"fs";import*as Z from"os";import*as f from"path";import{fileURLToPath as Io}from"url";var K={};W(K,{NAME:()=>so,VERSION:()=>to,up:()=>co});import*as b from"fs";import*as B from"path";var to=1,so="normalize-jobs-and-questions",ro=["description","techStack","jobTags","seniority","employmentType","industries","jobFunction","postedTime","applicantCount","companySize","workplaceType","contractType","isEasyApply","applyType","companyUrl","scoutedAt","lastSeen"],io=50;function G(e){return b.existsSync(e)?JSON.parse(b.readFileSync(e,"utf-8")):null}function H(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{b.writeFileSync(o,t)}catch(s){try{b.unlinkSync(o)}catch{}throw s}try{b.renameSync(o,e)}catch(s){try{b.unlinkSync(o)}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 co(e,n){let t=B.join(e,"jobs.json"),o=B.join(n,"scouted-jobs.json"),s=B.join(e,"application-questions.json"),r=G(t)||{},i=G(o)||{},a=0,l=[];for(let p of Object.keys(r)){if(!i[p])continue;let w=i[p],h=r[p];for(let O of ro)w[O]!=null&&h[O]==null&&(h[O]=w[O]);l.push(p),a++}a>0?(H(t,r),console.log(` Phase 1: Merged ${a} scouted jobs into jobs.json`)):console.log(" Phase 1: No overlapping jobs to merge");let u=G(s);if(u&&Array.isArray(u.applications)){let p={},w=0;for(let h of u.applications){let O=h.jobId||"unknown";p[O]||(p[O]={applications:[]});let ne=(h.questions||[]).map(k=>{let F={type:k.type||"input",question:k.question||"",answer:k.answer||""};return k.options&&(k.options.length<=io?F.options=k.options:(F.optionsOmitted=!0,w++)),k.page&&(F.page=k.page),k.wasPreFilled&&(F.wasPreFilled=!0),k.wasRetry&&(F.wasRetry=!0),F});p[O].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||ne.length,questions:ne})}H(s,p),console.log(` Phase 2: Rekeyed ${u.applications.length} applications by jobId (${Object.keys(p).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 p of l)delete i[p];H(o,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 Q={};W(Q,{NAME:()=>ao,VERSION:()=>lo,up:()=>po});import*as v from"fs";import*as he from"path";var lo=2,ao="reset-unread-flags";function uo(e){return v.existsSync(e)?JSON.parse(v.readFileSync(e,"utf-8")):null}function fo(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{v.writeFileSync(o,t)}catch(s){try{v.unlinkSync(o)}catch{}throw s}try{v.renameSync(o,e)}catch(s){try{v.unlinkSync(o)}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 po(e){let n=he.join(e,"conversations.json"),t=uo(n);if(!t){console.log(" conversations.json not found \u2014 nothing to reset.");return}let o=0;for(let s of Object.keys(t))t[s].unread===!0&&(t[s].unread=!1,o++);if(o===0){console.log(" No stale unread flags found \u2014 nothing to do.");return}fo(n,t),console.log(` Reset unread=false on ${o} conversations. Run 'ilml linkedin sync-all' to re-establish real unread state from LinkedIn.`)}var z={};W(z,{NAME:()=>ho,VERSION:()=>mo,up:()=>vo});import*as $ from"fs";import*as ge from"path";var mo=3,ho="recompute-last-message-by",go=new Set(["draft","confirmed","rejected","needs_review"]);function yo(e){return $.existsSync(e)?JSON.parse($.readFileSync(e,"utf-8")):null}function So(e,n){let t=JSON.stringify(n,null,2),o=e+".tmp";try{$.writeFileSync(o,t)}catch(s){try{$.unlinkSync(o)}catch{}throw s}try{$.renameSync(o,e)}catch(s){try{$.unlinkSync(o)}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 bo(e,n){if(!e||e.length===0)return"them";let t=e.filter(r=>!go.has(r.status));if(t.length===0)return"them";let o=t.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=o.length>0?o:[...t].reverse();for(let r of s){let i=r.sender;if(i===n)return"me";if(i!=="Unknown"&&i!=="")return"them"}return"them"}async function vo(e){let n=ge.join(e,"conversations.json"),t=yo(n);if(!t){console.log(" conversations.json not found \u2014 nothing to recompute.");return}let o=process.env.LINKEDIN_NAME;if(!o||typeof o!="string"||!o.trim())throw new Error(`LINKEDIN_NAME env var is not set. Migration v003 needs your display name to determine which messages are yours vs theirs. Set LINKEDIN_NAME in your .env (or run "ilml plugin config linkedin set LINKEDIN_NAME 'Your Name'") and retry.`);let s=0,r=0,i=0;for(let a of Object.keys(t)){let l=t[a];if(!l||typeof l!="object")continue;Object.prototype.hasOwnProperty.call(l,"_cardSynced")&&(delete l._cardSynced,r++);let u=Array.isArray(l.messages)?l.messages:[],p=bo(u,o),w=p==="me"?"awaiting_reply":"unanswered_by_us";l.lastMessageBy!==p&&i++,l.lastMessageBy=p,l.conversationStatus=w,s++}if(s===0){console.log(" No conversations to recompute.");return}So(n,t),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.")}import"dotenv/config";import*as y from"path";import{fileURLToPath as $o}from"url";var wo=$o(import.meta.url),ko=y.dirname(y.dirname(wo)),J=process.env.DATA_DIR?y.resolve(process.env.DATA_DIR,"market-research"):y.join(ko,"market-research"),kn=y.join(J,"scouted-jobs.json"),jn=y.join(J,"discovered-people.json"),An=y.join(J,"visit-log.json"),En=y.join(J,"companies.json"),On=y.join(J,"job-decisions.json");function ye(){jo=null,Ao=null,Eo=null,Oo=null,Ro=null}var jo=null;var Ao=null;var Eo=null;var Oo=null;var Ro=null;var To=Io(import.meta.url),Do=f.dirname(To),No=f.dirname(f.dirname(Do));function Co(e){return e&&(e==="~"?Z.homedir():e.startsWith("~/")||e.startsWith("~\\")?f.join(Z.homedir(),e.slice(2)):e)}var j=process.env.DATA_DIR?f.resolve(Co(process.env.DATA_DIR)):No,_=f.join(j,"collected-profiles"),x=f.join(j,"market-research"),g=f.join(j,".schema-version"),Se=[f.join(_,".schema-version"),f.join(x,".schema-version")],T=3,E=[{version:1,module:K},{version:2,module:Q},{version:3,module:z}];(function(){E.sort((o,s)=>o.version-s.version);let n=new Set;for(let o of E){if(!Number.isInteger(o.version)||o.version<1)throw new Error(`MIGRATION_REGISTRY: invalid version ${JSON.stringify(o.version)} (must be positive integer)`);if(n.has(o.version))throw new Error(`MIGRATION_REGISTRY: duplicate version v${o.version}`);n.add(o.version);let s=o.module;if(!s||typeof s.up!="function")throw new Error(`MIGRATION_REGISTRY: v${o.version} module is missing up()`);if(s.VERSION!==void 0&&s.VERSION!==o.version)throw new Error(`MIGRATION_REGISTRY: v${o.version} entry does not match module VERSION (${s.VERSION}). Drift between registry and module \u2014 pick one source of truth.`)}let t=E.length?E[E.length-1].version:0;if(t!==T)throw new Error(`MIGRATION_REGISTRY: highest version v${t} but CURRENT_SCHEMA_VERSION=${T}. Forgot to bump CURRENT_SCHEMA_VERSION when adding the new migration?`);for(let o=0;o<E.length;o++){let s=o+1;if(E[o].version!==s)throw new Error(`MIGRATION_REGISTRY: gap detected \u2014 expected v${s} at position ${o} but found v${E[o].version}`)}})();function we(){process.env.DATA_DIR!==void 0&&process.env.DATA_DIR.trim()===""&&process.env.DATA_DIR.length>0&&(console.error(`
|
|
9
9
|
[FATAL] DATA_DIR is set to whitespace ("${process.env.DATA_DIR}"). Either unset it or set a real path.
|
|
10
10
|
`),process.exit(1));try{c.mkdirSync(j,{recursive:!0})}catch(n){n.code!=="EEXIST"&&(console.error(`
|
|
11
11
|
[FATAL] Cannot create DATA_DIR (${j}): ${n.message}`),console.error(` Fix the path or permissions and try again.
|
|
@@ -27,14 +27,14 @@ ${o.join(`
|
|
|
27
27
|
[FATAL] ${g} 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.
|
|
28
28
|
`),process.exit(1)}let n=Lo(e);return n===null&&(console.error(`
|
|
29
29
|
[FATAL] ${g} 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.
|
|
30
|
-
`),process.exit(1)),n}function ke(e){try{c.chmodSync(e,384)}catch{}}function Mo(e){if(we(),c.existsSync(g))try{if(c.lstatSync(g).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${g}. 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 n=g+".tmp";try{c.writeFileSync(n,JSON.stringify(e,null,2)),ke(n),c.renameSync(n,g)}catch(t){try{c.unlinkSync(n)}catch{}throw t}}function $e(e,n){if(!c.existsSync(e))return;let t=`.pre-v${String(n).padStart(3,"0")}.backup`,o=c.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return c.statSync(f.join(e,a)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let a of o){let l=f.join(e,a),u=f.join(e,a+t);if(c.existsSync(u)){r++;continue}try{
|
|
30
|
+
`),process.exit(1)),n}function ke(e){try{c.chmodSync(e,384)}catch{}}function Mo(e){if(we(),c.existsSync(g))try{if(c.lstatSync(g).isSymbolicLink())throw new Error(`SCHEMA_FILE is a symbolic link: ${g}. 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 n=g+".tmp";try{c.writeFileSync(n,JSON.stringify(e,null,2)),ke(n),c.renameSync(n,g)}catch(t){try{c.unlinkSync(n)}catch{}throw t}}function $e(e,n){if(!c.existsSync(e))return;let t=`.pre-v${String(n).padStart(3,"0")}.backup`,o=c.readdirSync(e).filter(a=>{let l=a.toLowerCase();if(l.includes(".backup")||l===".schema-version"||l.endsWith(".tmp"))return!1;try{return c.statSync(f.join(e,a)).isFile()}catch{return!1}}),s=0,r=0,i=[];for(let a of o){let l=f.join(e,a),u=f.join(e,a+t);if(c.existsSync(u)){r++;continue}try{Ae(l,u),s++}catch(p){i.push({file:a,err:p.message})}}if(i.length>0){let a=new Error(`Failed to back up ${i.length} file(s) in ${f.basename(e)}/: `+i.map(l=>`${l.file} (${l.err})`).join(", "));throw a.code="BACKUP_INCOMPLETE",a}if(s>0||r>0){let a=r>0?` (${r} pre-existing backup(s) preserved)`:"";console.log(` Backed up ${s} files in ${f.basename(e)}/ (${t})${a}`)}}var X=!1;async function je(){if(X)return;we(),Vo();let n=ve().version;if(n===T){X=!0;return}xo(),_o(),process.on("exit",ee),n>T&&(console.error(`
|
|
31
31
|
[FATAL] Your data schema is at v${n}, but this plugin build only understands up to v${T}.`),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.
|
|
32
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${T}.
|
|
33
33
|
`),process.exit(1)),console.log(`
|
|
34
34
|
\u{1F4E6} Schema migration: v${n} \u2192 v${T}`);let t=Wo();if(!t.ok){console.error(`
|
|
35
35
|
[FATAL] Cannot migrate \u2014 current data is corrupted:`);for(let s of t.broken)console.error(` ${s.dir}/${s.file}: ${s.err}`);console.error(`
|
|
36
36
|
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
|
-
`),process.exit(1)}let o=
|
|
37
|
+
`),process.exit(1)}let o=E.filter(s=>s.version>n);for(let s of o){console.log(`
|
|
38
38
|
Running migration v${String(s.version).padStart(3,"0")}...`);let r=`v${String(s.version).padStart(3,"0")}`,i=`.pre-${r}.backup`;try{$e(_,s.version),$e(x,s.version)}catch(l){console.error(`
|
|
39
39
|
[FATAL] Pre-migration backup failed for ${r}: ${l.message}`),console.error(" Migration NOT applied. Repair the underlying issue (disk space, permissions, locked files)"),console.error(` and re-run the plugin command.
|
|
40
40
|
`),process.exit(1)}let a=s.module;try{await a.up(_,x)}catch(l){console.error(`
|
|
@@ -45,7 +45,7 @@ ${o.join(`
|
|
|
45
45
|
[FATAL] Migration ${r} 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${n}.`),console.error(` On next plugin command the runner will try to re-apply ${r}. If that migration is`),console.error(` idempotent (most are), it will succeed harmlessly. If you're unsure, run 'data-cleanup' and contact support.
|
|
46
46
|
`),process.exit(1)}console.log(` \u2713 Migration ${r} complete`)}try{ue()}catch{}try{ye()}catch{}X=!0,ee(),console.log(`
|
|
47
47
|
\u2713 Schema is now at v${T}
|
|
48
|
-
`)}var Po=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Jo(e){let n=e.toLowerCase();return Po.some(t=>t.test(n))}var Uo=6e4;function Bo(){let e=Date.now(),n=[];for(let t of[j,_,x]){if(!c.existsSync(t))continue;let o;try{o=c.readdirSync(t)}catch{continue}for(let s of o){if(!Jo(s))continue;let r=f.join(t,s);try{let i=c.statSync(r);if(!i.isFile()||e-i.mtimeMs<Uo)continue;n.push({dir:t,file:s,fullPath:r})}catch{}}}return n}function Vo({verbose:e=!1}={}){let n=Bo();if(n.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let o of n)try{c.unlinkSync(o.fullPath),t++,e&&console.log(` Removed orphan: ${f.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function Wo(){let e=[];for(let n of[_,x]){if(!c.existsSync(n))continue;let t=c.readdirSync(n).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of t){let s=f.join(n,o);try{V(s)}catch(r){e.push({dir:f.basename(n),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function qo(e){let n=[],t=[];for(let r of[_,x]){if(!c.existsSync(r))continue;let i=c.readdirSync(r).filter(a=>a.endsWith(e));for(let a of i){let l=f.join(r,a),u=a.slice(0,-e.length),p=f.join(r,u);try{u.toLowerCase().endsWith(".json")?V(l):c.accessSync(l,c.constants.R_OK),n.push({backupPath:l,originalPath:p,fileName:a,dir:r})}catch(w){t.push(`${f.basename(r)}/${a}: ${w.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let o=0,s=[];for(let{backupPath:r,originalPath:i,fileName:a,dir:l}of n)try{
|
|
48
|
+
`)}var Po=[/\.json\.tmp$/,/\.schema-version\.tmp$/,/\.backup\.tmp$/];function Jo(e){let n=e.toLowerCase();return Po.some(t=>t.test(n))}var Uo=6e4;function Bo(){let e=Date.now(),n=[];for(let t of[j,_,x]){if(!c.existsSync(t))continue;let o;try{o=c.readdirSync(t)}catch{continue}for(let s of o){if(!Jo(s))continue;let r=f.join(t,s);try{let i=c.statSync(r);if(!i.isFile()||e-i.mtimeMs<Uo)continue;n.push({dir:t,file:s,fullPath:r})}catch{}}}return n}function Vo({verbose:e=!1}={}){let n=Bo();if(n.length===0)return e&&console.log(" No orphan .tmp files found."),0;let t=0;for(let o of n)try{c.unlinkSync(o.fullPath),t++,e&&console.log(` Removed orphan: ${f.basename(o.dir)}/${o.file}`)}catch(s){console.warn(` [!] Could not remove orphan ${o.fullPath}: ${s.message}`)}return!e&&t>0&&console.log(` Cleaned up ${t} orphan .tmp file(s) from previous run.`),t}function Wo(){let e=[];for(let n of[_,x]){if(!c.existsSync(n))continue;let t=c.readdirSync(n).filter(o=>{let s=o.toLowerCase();return s.endsWith(".json")&&!s.includes(".backup")});for(let o of t){let s=f.join(n,o);try{V(s)}catch(r){e.push({dir:f.basename(n),file:o,err:r.message})}}}return e.length===0?{ok:!0}:{ok:!1,broken:e}}function qo(e){let n=[],t=[];for(let r of[_,x]){if(!c.existsSync(r))continue;let i=c.readdirSync(r).filter(a=>a.endsWith(e));for(let a of i){let l=f.join(r,a),u=a.slice(0,-e.length),p=f.join(r,u);try{u.toLowerCase().endsWith(".json")?V(l):c.accessSync(l,c.constants.R_OK),n.push({backupPath:l,originalPath:p,fileName:a,dir:r})}catch(w){t.push(`${f.basename(r)}/${a}: ${w.message}`)}}}if(t.length>0)return{ok:!1,error:t.join("; "),restored:0};let o=0,s=[];for(let{backupPath:r,originalPath:i,fileName:a,dir:l}of n)try{Ae(r,i),o++}catch(u){s.push(`${f.basename(l)}/${a}: ${u.message}`)}return s.length>0?{ok:!1,error:s.join("; "),restored:o}:{ok:!0,restored:o}}function Ae(e,n){let t=n+".tmp";try{c.copyFileSync(e,t),ke(t)}catch(o){try{c.unlinkSync(t)}catch{}throw o}try{c.renameSync(t,n)}catch(o){try{c.unlinkSync(t)}catch{}if(o.code==="EPERM"||o.code==="EBUSY"){let s=new Error(`File locked: ${n} (${o.code}). On Windows this is usually antivirus / Search Indexer / the file open in another app. Close anything that might be holding it and re-run.`);throw s.code=o.code,s}throw o}}await je();var U=process.argv.slice(2),oe=new Set((U.find(e=>e.startsWith("--skip="))?.split("=")[1]||"").split(",").filter(Boolean)),Ee=new Set((U.find(e=>e.startsWith("--only="))?.split("=")[1]||"").split(",").filter(Boolean)),Ie=U.includes("--dry-run"),Te=U.includes("--jobs"),De=U.includes("--comms"),Oe=["apply-queue","apply","funnel","scout","visit"],Re=["sync","today"],Ne=Te?Oe:De?Re:[...Oe,...Re];function D(e){return Ee.size>0?Ee.has(e):!oe.has(e)&&Ne.includes(e)}function L(e,n,t=[],{optional:o=!1}={}){if(console.log(`
|
|
49
49
|
${"\u2550".repeat(50)}`),console.log(` STEP: ${e}`),console.log("\u2550".repeat(50)),Ie)return console.log(` [DRY RUN] Would run: node ${n} ${t.join(" ")}`),!0;try{return Yo("node",[n,...t],{stdio:"inherit",timeout:18e6}),console.log(` \u2713 ${e} completed`),!0}catch(s){return o?(console.log(` \u26A0 ${e} failed (optional): ${s.message?.slice(0,80)}`),!1):(console.error(` \u2717 ${e} failed: ${s.message?.slice(0,80)}`),!1)}}async function Go(){let e=Te?"jobs":De?"comms":"full";console.log(`
|
|
50
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 n=Ne.filter(D);console.log(` Steps: ${n.join(" \u2192 ")}`),oe.size>0&&console.log(` Skipping: ${[...oe].join(", ")}`),Ie&&console.log(" [DRY RUN MODE]");let t=le("daily",e),o={};if(D("apply-queue")&&(o["apply-queue"]=L("Apply Queue (scored jobs)","applyQueue.mjs",["--max=50","--min-score=50"],{optional:!0})),D("apply")){let r=me();o.apply=L("Apply from Search","run.mjs",[],{optional:!0})}if(D("funnel")&&!D("apply")){let r=de();r.allowed?o.funnel=L("Connection Funnel","funnelRunner.mjs",["--max=20"],{optional:!0}):(console.log(`
|
|
51
51
|
\u26A0 Funnel skipped: ${r.reason}`),o.funnel="skipped_quota")}D("scout")&&(o.scout=L("Scout Jobs for Tomorrow","scout.mjs",["--max=300","--verbose"],{optional:!0})),D("sync")&&(o.sync=L("Sync Inbox","syncAll.mjs")),D("today")&&(o.today=L("Daily Report","syncAll.mjs",["--today"])),console.log(`
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
var Xe=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var et=(t,e)=>{for(var n in e)Xe(t,n,{get:e[n],enumerable:!0})};async function w(t){let e=Math.floor(Math.random()*2001),n=t+e;return new Promise(o=>setTimeout(o,n))}async function $e(t){return await t.evaluate(()=>{let e=document.querySelectorAll("div.artdeco-modal--is-open");for(let o of e){let i=o.innerText||"",s=i.includes("Premium")||i.includes("premium")||i.includes("Upgrade")||i.includes("upgrade"),f=i.includes("Try for")||i.includes("free trial")||i.includes("/month")||i.includes("per month")||i.includes("Start my")||i.includes("Subscribe"),d=i.includes("Get hired faster")||i.includes("Get hired 2x");if(s||f||d){let D=o.querySelector('button[aria-label="Dismiss"]')||o.querySelector("button.artdeco-modal__dismiss")||o.querySelector("button[data-test-modal-close-btn]");if(D)return D.click(),{dismissed:!0,matched:i.substring(0,80)};let $=o.querySelectorAll("button");for(let a of $){let S=a.innerText?.trim().toLowerCase()||"",p=a.getAttribute("aria-label")?.toLowerCase()||"";if(S==="not now"||S==="no thanks"||S==="dismiss"||p.includes("dismiss"))return a.click(),{dismissed:!0,matched:i.substring(0,80)}}}}let n=document.querySelector(".premium-upsell-link")||document.querySelector("[data-test-premium-upsell]")||document.querySelector(".premium-hub-upsell");if(n){let o=n.closest('[class*="modal"]')?.querySelector('button[aria-label="Dismiss"]')||n.closest('[class*="banner"]')?.querySelector('button[aria-label="Close"]');if(o)return o.click(),{dismissed:!0,matched:"premium-banner"}}return!1})}var re=Ae(()=>{});var Re={};et(Re,{extractCertificationsFromDetails:()=>bt,extractEducationFromDetails:()=>gt,extractExperienceFromDetails:()=>ht,extractFeaturedFromDetails:()=>wt,extractRecommendationsFromDetails:()=>St,extractSkillsFromDetails:()=>yt});async function ht(t,e){let n=e.replace(/\/+$/,"")+"/details/experience/";try{await t.goto(n,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();if(/\/(login|authwall|checkpoint)/i.test(o))throw new Error(`Session expired \u2014 bounced to ${o} when fetching /details/experience/`);for(let s=0;s<5;s++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(900);await w(1e3);let i=0;for(;i<5&&await t.evaluate(()=>{for(let f of document.querySelectorAll("button"))if(/^Load more$/i.test((f.textContent||"").trim()))return f.click(),!0;return!1});)i++,await w(1500),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);return await t.evaluate(()=>{let s=document.querySelector("main");if(!s)return[];function f(a){let S=[];for(let p of a.querySelectorAll("div")){let h=Array.from(p.children).filter(v=>v.tagName==="DIV");if(h.length<3)continue;let y=h.filter(v=>(v.textContent||"").trim().length>50);y.length<3||(p.textContent||"").length<500||S.push({el:p,count:y.length,totalText:(p.textContent||"").length})}return S.sort((p,h)=>h.count-p.count||p.totalText-h.totalText),S[0]?.el}let d=f(s);if(!d)return[];let D=Array.from(d.children).filter(a=>a.tagName==="DIV").filter(a=>(a.textContent||"").trim().length>50);function $(a){let S=a[0]||null,p=null,h=null;if(a[1]){let c=a[1].split("\xB7").map(k=>k.trim());p=c[0]||null,c[1]&&(h=c[1])}let y=a.findIndex(c=>/(\d{4}|present)/i.test(c)&&/(-|–|—)/i.test(c)&&c.length<80),v=null,M=null;if(y>=0){let c=a[y].split("\xB7").map(k=>k.trim());v=c[0]||null,c[1]&&(M=c[1])}let F=null,ne=-1;if(y>=0&&a[y+1]){let c=a[y+1],k=/^[>*\-•]|^>/.test(c),j=/https?:\/\//.test(c),x=/\d{4}/.test(c),V=/,/.test(c)||/\bArea\b|\bRegion\b|\bProvince\b|\bCountry\b|, [A-Z]{2}\b/.test(c);!k&&!j&&!x&&c.length<100&&V&&(F=c,ne=y+1)}let b=null,P=-1,I=a[a.length-1];if(I&&/and\s+\+\d+\s+skills?$/i.test(I)){P=a.length-1;let c=I.match(/^(.+?)\s+and\s+\+(\d+)\s+skills?$/i);c&&(b={listed:c[1].split(",").map(k=>k.trim()),additional:parseInt(c[2],10)})}let L=new Set([0,1,y,ne,P].filter(c=>c>=0)),C=a.filter((c,k)=>!L.has(k)),oe=C.length>0?C.join(`
|
|
2
|
+
|
|
3
|
+
`):null;return{title:S,company:p,employmentType:h,dates:v,duration:M,location:F,description:oe,skills:b,_raw:a}}return D.map(a=>{let p=(a.innerText||"").trim().split(`
|
|
4
|
+
`).map(h=>h.trim()).filter(h=>h&&h.length<5e3);return $(p)}).filter(a=>a.title)})}catch(o){if(/session expired|bounced to|authwall|checkpoint/i.test(o.message||""))throw o;return console.error(`extractExperienceFromDetails failed for ${e}: ${o.message?.slice(0,120)}`),[]}}async function B(t,e,n){let o=e.replace(/\/+$/,"")+`/details/${n}/`;await t.goto(o,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let i=t.url();if(/\/(login|authwall|checkpoint)/i.test(i))throw new Error(`Session expired \u2014 bounced to ${i} when fetching /details/${n}/`);if(!i.toLowerCase().includes(`/details/${n.toLowerCase()}/`))throw new Error(`Section /details/${n}/ not available on profile (landed on ${i})`);for(let f=0;f<4;f++)await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(700);await w(800);let s=0;for(;s<5&&await t.evaluate(()=>{for(let d of document.querySelectorAll("button"))if(/^Load more$/i.test((d.textContent||"").trim()))return d.click(),!0;return!1});)s++,await w(1300),await t.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await w(600)}async function U(t,e,n,o){try{return await o()}catch(i){let s=i.message||"";if(/session expired|bounced to|authwall|checkpoint/i.test(s))throw i;return/not available on profile/i.test(s)?(console.log(` (${e}: section not on profile \u2014 skipped)`),[]):(console.error(`${n} failed for ${t}: ${s.slice(0,120)}`),[])}}async function wt(t,e){return U(e,"featured","extractFeaturedFromDetails",async()=>(await B(t,e,"featured"),await t.evaluate(`(() => {
|
|
5
|
+
${H}
|
|
6
|
+
|
|
7
|
+
const main = document.querySelector('main');
|
|
8
|
+
if (!main) return [];
|
|
9
|
+
const container = findEntryContainer(main);
|
|
10
|
+
if (!container) return [];
|
|
11
|
+
|
|
12
|
+
const entries = Array.from(container.children)
|
|
13
|
+
.filter(c => c.tagName === 'DIV')
|
|
14
|
+
.filter(c => (c.textContent || '').trim().length > 30);
|
|
15
|
+
|
|
16
|
+
return entries.map(entry => {
|
|
17
|
+
const raw = (entry.innerText || '').trim();
|
|
18
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
|
|
19
|
+
|
|
20
|
+
// External link from any anchor inside the card (filter LinkedIn-internal)
|
|
21
|
+
const anchors = Array.from(entry.querySelectorAll('a[href]'));
|
|
22
|
+
const externalAnchor = anchors.find(a => {
|
|
23
|
+
const h = a.href || '';
|
|
24
|
+
return h.startsWith('http') &&
|
|
25
|
+
!h.includes('linkedin.com/in/') &&
|
|
26
|
+
!h.includes('linkedin.com/posts/') &&
|
|
27
|
+
!h.includes('#');
|
|
28
|
+
});
|
|
29
|
+
const url = externalAnchor?.href || anchors[0]?.href || null;
|
|
30
|
+
|
|
31
|
+
const title = lines[0] || null;
|
|
32
|
+
const caption = lines[1] && lines[1] !== title ? lines[1] : null;
|
|
33
|
+
|
|
34
|
+
return { title, caption, url, _raw: lines };
|
|
35
|
+
}).filter(e => {
|
|
36
|
+
if (!e.title) return false;
|
|
37
|
+
// Reject "People You May Know" sidebar cards: signature is
|
|
38
|
+
// exactly [title, "View"] with no url/caption beyond "View".
|
|
39
|
+
if (e._raw.length === 2 && e._raw[1] === 'View') return false;
|
|
40
|
+
return true;
|
|
41
|
+
});
|
|
42
|
+
})()`)))}async function gt(t,e){return U(e,"education","extractEducationFromDetails",async()=>(await B(t,e,"education"),await t.evaluate(`(() => {
|
|
43
|
+
${H}
|
|
44
|
+
|
|
45
|
+
const main = document.querySelector('main');
|
|
46
|
+
if (!main) return [];
|
|
47
|
+
const container = findEntryContainer(main);
|
|
48
|
+
if (!container) return [];
|
|
49
|
+
|
|
50
|
+
const entries = Array.from(container.children)
|
|
51
|
+
.filter(c => c.tagName === 'DIV')
|
|
52
|
+
.filter(c => (c.textContent || '').trim().length > 30);
|
|
53
|
+
|
|
54
|
+
return entries.map(entry => {
|
|
55
|
+
const raw = (entry.innerText || '').trim();
|
|
56
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
|
|
57
|
+
|
|
58
|
+
const school = lines[0] || null;
|
|
59
|
+
const degree = lines[1] || null;
|
|
60
|
+
const dates = lines.find(l =>
|
|
61
|
+
/(\\d{4})/.test(l) &&
|
|
62
|
+
/(-|\u2013|\u2014)/i.test(l) &&
|
|
63
|
+
l.length < 80
|
|
64
|
+
) || null;
|
|
65
|
+
const used = new Set([0, 1, dates ? lines.indexOf(dates) : -1].filter(i => i >= 0));
|
|
66
|
+
const descLines = lines.filter((_, i) => !used.has(i));
|
|
67
|
+
const description = descLines.length > 0 ? descLines.join(' / ') : null;
|
|
68
|
+
|
|
69
|
+
return { school, degree, dates, description, _raw: lines };
|
|
70
|
+
}).filter(e => {
|
|
71
|
+
if (!e.school) return false;
|
|
72
|
+
// Reject "People You May Know" sidebar cards: [title, "View"].
|
|
73
|
+
if (e._raw.length === 2 && e._raw[1] === 'View') return false;
|
|
74
|
+
return true;
|
|
75
|
+
});
|
|
76
|
+
})()`)))}async function yt(t,e){return U(e,"skills","extractSkillsFromDetails",async()=>(await B(t,e,"skills"),await t.evaluate(`(() => {
|
|
77
|
+
${H}
|
|
78
|
+
|
|
79
|
+
const main = document.querySelector('main');
|
|
80
|
+
if (!main) return [];
|
|
81
|
+
const container = findEntryContainer(main);
|
|
82
|
+
if (!container) return [];
|
|
83
|
+
|
|
84
|
+
const entries = Array.from(container.children)
|
|
85
|
+
.filter(c => c.tagName === 'DIV')
|
|
86
|
+
.filter(c => (c.textContent || '').trim().length > 1);
|
|
87
|
+
|
|
88
|
+
const seen = new Set();
|
|
89
|
+
const skills = [];
|
|
90
|
+
for (const entry of entries) {
|
|
91
|
+
const raw = (entry.innerText || '').trim();
|
|
92
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(Boolean);
|
|
93
|
+
if (lines.length === 0) continue;
|
|
94
|
+
|
|
95
|
+
const name = lines[0];
|
|
96
|
+
if (!name || name.length > 100 || seen.has(name.toLowerCase())) continue;
|
|
97
|
+
seen.add(name.toLowerCase());
|
|
98
|
+
|
|
99
|
+
let endorsements = null;
|
|
100
|
+
for (const l of lines.slice(1)) {
|
|
101
|
+
const m = l.match(/(\\d+)\\s+endorsement/i);
|
|
102
|
+
if (m) { endorsements = parseInt(m[1], 10); break; }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
skills.push({ name, endorsements, _raw: lines });
|
|
106
|
+
}
|
|
107
|
+
return skills;
|
|
108
|
+
})()`)))}async function bt(t,e){return U(e,"certifications","extractCertificationsFromDetails",async()=>(await B(t,e,"certifications"),await t.evaluate(`(() => {
|
|
109
|
+
${H}
|
|
110
|
+
|
|
111
|
+
const main = document.querySelector('main');
|
|
112
|
+
if (!main) return [];
|
|
113
|
+
const container = findEntryContainer(main);
|
|
114
|
+
if (!container) return [];
|
|
115
|
+
|
|
116
|
+
const entries = Array.from(container.children)
|
|
117
|
+
.filter(c => c.tagName === 'DIV')
|
|
118
|
+
.filter(c => (c.textContent || '').trim().length > 20);
|
|
119
|
+
|
|
120
|
+
return entries.map(entry => {
|
|
121
|
+
const raw = (entry.innerText || '').trim();
|
|
122
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 2000);
|
|
123
|
+
|
|
124
|
+
const name = lines[0] || null;
|
|
125
|
+
const issuer = lines[1] || null;
|
|
126
|
+
const issueDate = lines.find(l => /^Issued\\b/i.test(l)) || null;
|
|
127
|
+
const expiryDate = lines.find(l => /Expir(es|ed)\\b/i.test(l)) || null;
|
|
128
|
+
const credentialId = (lines.find(l => /credential id/i.test(l)) || '')
|
|
129
|
+
.replace(/^.*credential id[:\\s]*/i, '').trim() || null;
|
|
130
|
+
|
|
131
|
+
return { name, issuer, issueDate, expiryDate, credentialId, _raw: lines };
|
|
132
|
+
}).filter(e => e.name);
|
|
133
|
+
})()`)))}async function St(t,e){return U(e,"recommendations","extractRecommendationsFromDetails",async()=>(await B(t,e,"recommendations"),await t.evaluate(`(() => {
|
|
134
|
+
${H}
|
|
135
|
+
|
|
136
|
+
const main = document.querySelector('main');
|
|
137
|
+
if (!main) return [];
|
|
138
|
+
const container = findEntryContainer(main);
|
|
139
|
+
if (!container) return [];
|
|
140
|
+
|
|
141
|
+
const entries = Array.from(container.children)
|
|
142
|
+
.filter(c => c.tagName === 'DIV')
|
|
143
|
+
.filter(c => (c.textContent || '').trim().length > 50);
|
|
144
|
+
|
|
145
|
+
return entries.map(entry => {
|
|
146
|
+
const raw = (entry.innerText || '').trim();
|
|
147
|
+
const lines = raw.split('\\n').map(l => l.trim()).filter(l => l && l.length < 5000);
|
|
148
|
+
|
|
149
|
+
const recommender = lines[0] || null;
|
|
150
|
+
const recommenderTitle = lines[1] || null;
|
|
151
|
+
const relationship = lines.find(l =>
|
|
152
|
+
/\\b(was |worked |reported |managed |taught |studied )\\b/i.test(l) &&
|
|
153
|
+
l.length < 200
|
|
154
|
+
) || null;
|
|
155
|
+
const date = lines.find(l => /(January|February|March|April|May|June|July|August|September|October|November|December)\\s+\\d{1,2}.*\\d{4}/i.test(l)) || null;
|
|
156
|
+
// Recommendation text is the longest non-meta line
|
|
157
|
+
const text = [...lines].sort((a, b) => b.length - a.length)[0] || '';
|
|
158
|
+
|
|
159
|
+
return { recommender, recommenderTitle, relationship, date, text, _raw: lines };
|
|
160
|
+
}).filter(e => {
|
|
161
|
+
if (!e.recommender || !e.text) return false;
|
|
162
|
+
// Reject "People You May Know" sidebar cards: [title, "View"].
|
|
163
|
+
if (e._raw.length === 2 && e._raw[1] === 'View') return false;
|
|
164
|
+
return true;
|
|
165
|
+
});
|
|
166
|
+
})()`)))}var H,Pe=Ae(()=>{re();H=`
|
|
167
|
+
function findEntryContainer(root) {
|
|
168
|
+
const candidates = [];
|
|
169
|
+
for (const div of root.querySelectorAll('div')) {
|
|
170
|
+
const directDivs = Array.from(div.children).filter(c => c.tagName === 'DIV');
|
|
171
|
+
if (directDivs.length < 2) continue;
|
|
172
|
+
const substantial = directDivs.filter(c => (c.textContent || '').trim().length > 30);
|
|
173
|
+
if (substantial.length < 2) continue;
|
|
174
|
+
if ((div.textContent || '').length < 200) continue;
|
|
175
|
+
|
|
176
|
+
// Reject "People You May Know" suggestion containers: every substantial
|
|
177
|
+
// child is exactly [title, "View"] (a tiny suggestion card with a single
|
|
178
|
+
// "View" CTA). Real section entries always have richer per-child content
|
|
179
|
+
// (multiple text lines per entry).
|
|
180
|
+
const allLookLikePYMK = substantial.every(c => {
|
|
181
|
+
const lines = (c.innerText || '').trim().split('\\n').map(l => l.trim()).filter(Boolean);
|
|
182
|
+
return lines.length === 2 && lines[1] === 'View';
|
|
183
|
+
});
|
|
184
|
+
if (allLookLikePYMK) continue;
|
|
185
|
+
|
|
186
|
+
// Reject LinkedIn footer/legal blocks: when a /details/<section>/ page
|
|
187
|
+
// renders empty, LinkedIn falls back to "Questions? Visit our Help
|
|
188
|
+
// Center", "Select language" (35+ languages), "Recommendation
|
|
189
|
+
// transparency" and similar nav cards inside <main>. These are unique
|
|
190
|
+
// marker strings that never appear inside real section entries.
|
|
191
|
+
const containerText = div.textContent || '';
|
|
192
|
+
const FOOTER_MARKERS = [
|
|
193
|
+
'Visit our Help Center',
|
|
194
|
+
'Select language',
|
|
195
|
+
'Recommendation transparency',
|
|
196
|
+
'Manage your account and privacy',
|
|
197
|
+
'Go to your Settings',
|
|
198
|
+
'Who your viewers also viewed', // "Private to you" PYMK block on empty pages
|
|
199
|
+
'People also viewed',
|
|
200
|
+
'People you may know',
|
|
201
|
+
];
|
|
202
|
+
if (FOOTER_MARKERS.some(m => containerText.includes(m))) continue;
|
|
203
|
+
|
|
204
|
+
candidates.push({ el: div, count: substantial.length, totalText: (div.textContent || '').length });
|
|
205
|
+
}
|
|
206
|
+
// Sort: most children first, then RICHER children (larger totalText) \u2014 real
|
|
207
|
+
// section entries dominate via content density, not just child count. The
|
|
208
|
+
// previous "smaller totalText wins" tie-break gave PYMK sidebars priority
|
|
209
|
+
// over the real Education / Recommendations lists.
|
|
210
|
+
candidates.sort((a, b) => b.count - a.count || b.totalText - a.totalText);
|
|
211
|
+
return candidates[0]?.el;
|
|
212
|
+
}
|
|
213
|
+
`});import"dotenv/config";import Et from"puppeteer";re();import{getPluginConfig as tt}from"@ilivemylife/graph-sdk";var nt=await tt();for(let[t,e]of Object.entries(nt))process.env[t]===void 0&&(process.env[t]=e);var Dt=process.env.LINKEDIN_NAME,T=Object.freeze({DRAFT:"draft",CONFIRMED:"confirmed",REJECTED:"rejected",NEEDS_REVIEW:"needs_review",SENT:"sent"}),Mt=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.NEEDS_REVIEW])),Ft=Object.freeze(new Set([T.DRAFT,T.CONFIRMED,T.REJECTED,T.NEEDS_REVIEW]));import"dotenv/config";import*as m from"fs";import*as g from"path";import{fileURLToPath as ot}from"url";var it=ot(import.meta.url),st=g.dirname(g.dirname(it)),A=process.env.DATA_DIR?g.resolve(process.env.DATA_DIR,"collected-profiles"):g.join(st,"collected-profiles"),le=g.join(A,"people.json"),Pt=g.join(A,"jobs.json"),jt=g.join(A,"quota.json"),Ot=g.join(A,"conversations.json"),qt=g.join(A,"sync-state.json"),Bt=g.join(A,"application-questions.json"),ae=g.join(A,"profile-history");var q=null;function Me(){m.existsSync(A)||m.mkdirSync(A,{recursive:!0})}function Fe(t,e){let n=JSON.stringify(e,null,2),o=t+".tmp";m.writeFileSync(o,n);for(let i=0;i<3;i++)try{m.renameSync(o,t);return}catch(s){if(i<2&&(s.code==="EPERM"||s.code==="EBUSY")){let f=Date.now();for(;Date.now()-f<200;);continue}throw s}}function Le(t,e){if(!m.existsSync(t))return null;try{let n=JSON.parse(m.readFileSync(t,"utf-8"));try{m.copyFileSync(t,t+".backup")}catch{}return n}catch(n){console.error(`[!] ${e} is corrupted: ${n.message}`),console.error(` File: ${g.resolve(t)}`);let o=t+".backup";if(m.existsSync(o))try{let i=JSON.parse(m.readFileSync(o,"utf-8"));console.error(` Restored from ${o}`);try{m.copyFileSync(o,t)}catch{}return i}catch{console.error(" Backup also corrupted!")}console.error(` Starting with empty data. Old file preserved as ${t}.corrupted`);try{m.copyFileSync(t,t+".corrupted")}catch{}return null}}function rt(){return new Date().toISOString().split("T")[0]}var lt=["name","title","location","company","connectionDegree","connectionsCount","mutualConnections","photoUrl","hasVerifiedBadge","about","currentCompany","currentSchool","connectionsLevel","mutualConnectionsCount","followers","openToWork","hiring","topSkills","availableSections","experience","featuredLinks","_lastEnrichedAt","featured","education","skillsFull","recommendations","certifications"],at=["name","title","location","currentCompany","currentSchool","connectionDegree","hasVerifiedBadge","openToWork","hiring","about","topSkills"];function ce(t){if(!t)return null;let e=t.match(/\/in\/([^/?#]+)/);return e?e[1].toLowerCase():null}function ct(){m.existsSync(ae)||m.mkdirSync(ae,{recursive:!0})}function Te(t){let e=ce(t);return e?g.join(ae,`${e}.json`):null}function ut(t){let e=Te(t);return e?Le(e,`profile-history/${ce(t)}.json`)||[]:[]}function dt(t,e){let n=Te(t);if(!n)return;ct();let o=ut(t);o.unshift(e);try{Fe(n,o)}catch(i){console.error(`[!] Failed to append profile-history for ${ce(t)}: ${i.message}`)}}function _e(t){return!!(t==null||Array.isArray(t)&&t.length===0||typeof t=="string"&&!t.trim())}function De(t){return Array.isArray(t)?[...t].map(e=>String(e).trim()).sort().join("||"):typeof t=="string"?t.replace(/\s+/g," ").trim():t}function ft(t,e){if(!t)return[];let n=[];for(let o of at){let i=t[o],s=e[o];_e(i)||_e(s)||De(i)!==De(s)&&n.push(o)}return n}function mt(t){let e=new Set(["seenCount","sources","firstSeen","lastSeen","lastUpdated","encounters","jobIds","lastFullVisitAt","lastSnapshotAt","messageSent","connectionStatus","connectionDate","connectionMethod"]),n={};for(let[o,i]of Object.entries(t))e.has(o)||(n[o]=i);return n}function Ne(){return q||(Me(),q=Le(le,"people.json")||{},q)}function pt(t){Me(),q=t;try{Fe(le,t)}catch(e){console.error(`[!] Failed to save people.json: ${e.message}`),console.error(` Path: ${g.resolve(le)}`)}}function ue(t,e={}){if(!t)return null;let n=Ne(),o=rt(),i=new Date().toISOString(),s=n[t];if(s){let f=ft(s,e);f.length>0&&(dt(t,{capturedAt:i,previousLastUpdated:s.lastUpdated||null,changedFields:f,snapshot:mt(s)}),s.lastSnapshotAt=i),s.seenCount=(s.seenCount||1)+1,s.lastSeen=o,s.lastUpdated=i,e.source&&!s.sources?.includes(e.source)&&(s.sources=s.sources||[],s.sources.push(e.source));for(let d of lt)if(e[d]!=null){if(Array.isArray(e[d])&&e[d].length===0&&Array.isArray(s[d])&&s[d].length>0)continue;s[d]=e[d]}Array.isArray(e.availableSections)&&(s.lastFullVisitAt=i)}else n[t]={name:e.name||null,title:e.title||null,location:e.location||null,company:e.company||null,about:e.about||null,connectionDegree:e.connectionDegree||null,connectionsCount:e.connectionsCount||null,mutualConnections:e.mutualConnections||null,photoUrl:e.photoUrl||null,hasVerifiedBadge:e.hasVerifiedBadge||!1,currentCompany:e.currentCompany||null,currentSchool:e.currentSchool||null,connectionsLevel:e.connectionsLevel||null,mutualConnectionsCount:e.mutualConnectionsCount||null,followers:e.followers||null,openToWork:e.openToWork||!1,hiring:e.hiring||!1,topSkills:e.topSkills||null,availableSections:e.availableSections||null,experience:e.experience||null,featuredLinks:e.featuredLinks||null,_lastEnrichedAt:e._lastEnrichedAt||null,featured:e.featured||null,education:e.education||null,skillsFull:e.skillsFull||null,recommendations:e.recommendations||null,certifications:e.certifications||null,firstSeen:o,lastSeen:o,seenCount:1,sources:e.source?[e.source]:[],connectionStatus:null,connectionDate:null,connectionMethod:null,messageSent:null,jobIds:[],lastUpdated:i,lastSnapshotAt:null,lastFullVisitAt:Array.isArray(e.availableSections)?i:null};return pt(n),n[t]}async function kt(t,e){let n=t.url();if(n.includes("/in/"))return!1;if(n.includes("/login")||n.includes("/authwall")||n.includes("/checkpoint"))throw new Error("Session expired \u2014 redirected to login. Run: npm run login");console.log(` Off-track: ${n.slice(0,80)}`),console.log(" Navigating back to profile..."),await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3);let o=t.url();return o.includes("/in/")||console.log(` Recovery failed \u2014 still on: ${o.slice(0,80)}`),!0}async function je(t,e,n={}){let{extractExperience:o=!1,extractFeatured:i=!1,extractEducation:s=!1,extractSkills:f=!1,extractRecommendations:d=!1,extractCertifications:D=!1}=n;try{await t.goto(e,{waitUntil:"domcontentloaded",timeout:6e4}),await w(3e3),await $e(t)&&(console.log(" Dismissed Premium overlay"),await w(1500),await kt(t,e));let a=0;for(let b=0;b<2;b++){let P=await t.evaluate(()=>document.body.scrollHeight);for(let L=1;L<=6;L++)await t.evaluate(C=>window.scrollTo(0,C),P*L/6),await w(900);let I=await t.evaluate(()=>document.body.scrollHeight);if(I===a)break;a=I}await w(800);let S=await t.evaluate(()=>{let b=new Set(["Highlights","About","Activity","Experience","Education","Skills","Recommendations","Languages","Interests","Volunteer experience","Featured","Honors & awards","Honors and awards","Projects","Publications","Patents","Certifications","Licenses & certifications","Courses","Test scores","Organizations"]),P=new Set(["Ad Options","Don\u2019t want to see this","0 notifications","Explore Premium profiles","You might like","People you may know","Suggested for you","More profiles for you","Promoted"]),I=r=>{let l=(r||"").trim().replace(/^[·•]\s*/,"");return/^(1st|2nd|3rd|she\/her|he\/him|they\/them|their\/them)$/i.test(l)},L={name:null,title:null,location:null,currentCompany:null,currentSchool:null,connectionDegree:null,hasVerifiedBadge:!1,photoUrl:null,connectionsLevel:null,mutualConnectionsCount:null,followers:null,openToWork:!1,hiring:!1,about:null,topSkills:null,availableSections:[]},C=document.querySelector("main");if(!C)return L;let oe=[...Array.from(C.querySelectorAll("h1")),...Array.from(C.querySelectorAll("h2"))],c=Array.from(C.querySelectorAll("h2")),k=oe.find(r=>{let l=r.textContent&&r.textContent.trim(),u=(l||"").replace(/\s*\(\d+\)$/,"").trim();return l&&l.length>1&&l.length<100&&!b.has(u)&&!P.has(u)}),j=k?k.textContent.trim():null,x=k?k.parentElement:null;for(;x&&x!==C&&!Array.from(x.children).filter(l=>l.tagName==="P").some(l=>{let u=l.textContent&&l.textContent.trim();return u&&u.length>5&&!I(u)});)x=x.parentElement;let V=null,pe=null,he=null,ie=null;if(x&&x!==C){let r=Array.from(x.children).filter(u=>u.tagName==="P").filter(u=>{let _=u.textContent&&u.textContent.trim();return _&&_.length>5&&!I(_)});if(r[0]&&(V=r[0].textContent.trim()),r[1]){let u=r[1].textContent.trim().split(/\s*[·•]\s*/);pe=u[0]||null,u.length>1&&(he=u.slice(1).join(" \xB7 "))}let l=Array.from(x.children).filter(u=>u.tagName==="DIV");for(let u=l.length-1;u>=0;u--){let _=l[u].textContent&&l[u].textContent.trim();if(_&&!(j&&_.startsWith(j))&&(ie=_.split(/[·•]/)[0].trim(),ie))break}}let we=null;if(x){let r=x.querySelectorAll("p, span, div");for(let l of r){let u=(l.textContent||"").trim().replace(/^[·•]\s*/,"");if(u==="1st"||u==="2nd"||u==="3rd"){we=u;break}}}let Je=!!C.querySelector('svg[data-test-icon="verified"], [aria-label*="Verified" i]'),ge=document.querySelector('main img[width="200"], button img[alt*="photo" i]'),Ke=ge&&ge.src||null,W=C.textContent||"",ye=null,be=W.match(/(\d+\+?)\s+connections\b/i);be&&(ye=be[1]+" connections");let J=null,Se=W.match(/(\d+)\s+mutual connection/i),ke=W.match(/and\s+(\d+)\s+other mutual/i),Ye=W.match(/([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+and\s+([A-Z][\w'-]+(?:\s+[A-Z][\w'-]+)?)\s+are\s+mutual/);Se?J=parseInt(Se[1],10):ke?J=2+parseInt(ke[1],10):Ye&&(J=2);let Ce=null,xe=null,ve=c.find(r=>r.textContent&&r.textContent.trim()==="About");if(ve){let r=ve.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").trim();l=l.replace(/^About\s*/,"").trim();let u=l.match(/Top skills\s*(.+?)$/i);if(u){let se=u[1].split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim().split(/\s*[·•]\s*/).map(Ze=>Ze.trim()).filter(Boolean);se.length>0&&se.length<10&&(xe=se)}l=l.split(/\n?…\s*more/i)[0].trim(),l=l.split(/\n?\.\.\.\s*more/i)[0].trim(),l=l.split(/\bTop skills\b/i)[0].trim(),l=l.split(/\b(?:see (?:more|less)|show (?:more|less))\b/i)[0].trim(),Ce=l||null}}let Ee=null,Ie=c.find(r=>r.textContent&&r.textContent.trim()==="Activity");if(Ie){let r=Ie.parentElement;for(;r&&r.tagName!=="SECTION";)r=r.parentElement;if(r){let l=(r.textContent||"").slice(0,200).match(/([\d,]+)\s+followers/i);l&&(Ee=parseInt(l[1].replace(/,/g,""),10))}}let Qe=[...new Set(c.map(r=>(r.textContent||"").trim().replace(/\s*\(\d+\)$/,"").trim()).filter(r=>r&&r.length>1&&r.length<60&&r!==j).filter(r=>b.has(r)))],O=document.body.textContent||"",ze=/#OpenToWork\b/i.test(O)||/\bOpen to work\b/.test(O),Ge=/#Hiring\b/i.test(O)||/\bI'?m hiring\b/i.test(O)||/\bWe are hiring\b/i.test(O);return{name:j,title:V,location:ie,currentCompany:pe,currentSchool:he,connectionDegree:we,hasVerifiedBadge:Je,photoUrl:Ke,connectionsLevel:ye,mutualConnectionsCount:J,followers:Ee,openToWork:ze,hiring:Ge,about:Ce,topSkills:xe,availableSections:Qe}});console.log(`Viewed: ${S.name} - ${S.title}`);let p=null,h=null,y=null,v=null,M=null,F=null;if(o||i||s||f||d||D){let b=await Promise.resolve().then(()=>(Pe(),Re));o&&(p=await b.extractExperienceFromDetails(t,e),console.log(` + Experience: ${p.length} entries`)),i&&(h=await b.extractFeaturedFromDetails(t,e),console.log(` + Featured: ${h.length} entries`)),s&&(y=await b.extractEducationFromDetails(t,e),console.log(` + Education: ${y.length} entries`)),f&&(v=await b.extractSkillsFromDetails(t,e),console.log(` + Skills: ${v.length} entries`)),d&&(M=await b.extractRecommendationsFromDetails(t,e),console.log(` + Recommendations: ${M.length} entries`)),D&&(F=await b.extractCertificationsFromDetails(t,e),console.log(` + Certifications: ${F.length} entries`))}return{...S,profileUrl:e,...p!==null&&{experience:p},...h!==null&&{featured:h},...y!==null&&{education:y},...v!==null&&{skillsFull:v},...M!==null&&{recommendations:M},...F!==null&&{certifications:F}}}catch($){console.error(`Error viewing profile ${e}:`,$.message);try{await t.goto("about:blank",{timeout:1e4}),await w(1e3)}catch{}if(/session expired|bounced to|authwall|checkpoint|redirected to login/i.test($.message||""))throw $;return null}}import Oe from"fs";import Ct from"path";var xt="cookies.json";function vt(){let t=process.env.ILML_SCOPE_DIR;return t?Ct.join(t,"plugins-state","linkedin","cookies.json"):xt}function qe(){let t=vt();if(!Oe.existsSync(t))throw new Error(`Cookies not found at ${t}. Run: ilml linkedin login`);let e;try{e=Oe.readFileSync(t,"utf-8")}catch(o){throw new Error(`Failed to read cookies at ${t}: ${o.message}. Run: ilml linkedin login`)}let n;try{n=JSON.parse(e)}catch{throw new Error(`Cookies file at ${t} is corrupted (invalid JSON). Run: ilml linkedin login`)}if(!Array.isArray(n)||n.length===0)throw new Error(`Cookies file at ${t} is empty or not an array. Run: ilml linkedin login`);return n}function Be(t){return t?t.replace(/^https?:\/\/(www\.|m\.)?linkedin\.com/i,"https://linkedin.com").split("?")[0].split("#")[0].replace(/\/+$/,"").toLowerCase():""}function He(t){return(t||"").replace(/ /g," ").replace(/\s+/g," ").trim().toLowerCase()}var E=process.argv.slice(2),It=E.includes("--help")||E.includes("-h"),N=E.find(t=>t.startsWith("http")),R=E.includes("--full"),Y=R||E.includes("--with-experience"),Q=R||E.includes("--with-featured"),z=R||E.includes("--with-education"),G=R||E.includes("--with-skills"),Z=R||E.includes("--with-recommendations"),X=R||E.includes("--with-certifications"),Ue=[["experience",Y],["featured",Q],["education",z],["skills",G],["recommendations",Z],["certifications",X]],Ve=Ue.filter(([,t])=>t).length,fe=1+Ve;function We(){console.log(`
|
|
214
|
+
enrich-profile \u2014 visit ONE LinkedIn profile and save what we learn
|
|
215
|
+
|
|
216
|
+
USAGE
|
|
217
|
+
ilml linkedin enrich-profile <profile-url> [--full | --with-...]
|
|
218
|
+
node enrichProfile.mjs <profile-url> [--full | --with-...] # dev
|
|
219
|
+
|
|
220
|
+
ARGUMENTS
|
|
221
|
+
<profile-url> Required. Full LinkedIn profile URL.
|
|
222
|
+
Example: https://www.linkedin.com/in/<slug>/
|
|
223
|
+
|
|
224
|
+
FLAGS
|
|
225
|
+
--full Shortcut: enables all --with-* flags. Up to 7 page
|
|
226
|
+
loads (main + Experience + Featured + Education +
|
|
227
|
+
Skills + Recommendations + Certifications). Missing
|
|
228
|
+
sections are skipped automatically (smart-skip), so
|
|
229
|
+
most real profiles cost 3\u20136 loads in practice.
|
|
230
|
+
Recommended for own-profile audit and on-demand
|
|
231
|
+
deep-dive on one contact.
|
|
232
|
+
|
|
233
|
+
--with-experience Adds /details/experience/ \u2192 structured experience[]
|
|
234
|
+
(title, company, dates, location, description, skills).
|
|
235
|
+
--with-featured Adds /details/featured/ \u2192 pinned items (title, caption, url).
|
|
236
|
+
--with-education Adds /details/education/ \u2192 schools, degrees, dates.
|
|
237
|
+
--with-skills Adds /details/skills/ \u2192 full skill list with endorsements.
|
|
238
|
+
--with-recommendations Adds /details/recommendations/ \u2192 received recommendations.
|
|
239
|
+
--with-certifications Adds /details/certifications/ \u2192 licenses & certifications.
|
|
240
|
+
|
|
241
|
+
Each --with-* adds ONE extra navigation = ONE extra page load. Mix and
|
|
242
|
+
match for cheaper partial enrichment.
|
|
243
|
+
|
|
244
|
+
--help, -h Print this help and exit.
|
|
245
|
+
|
|
246
|
+
BEHAVIOUR
|
|
247
|
+
- Saves to people.json via upsertPerson() \u2014 additive merge, never deletes data.
|
|
248
|
+
- Self-profile detected via MY_LINKEDIN_URL or LINKEDIN_NAME \u2192 printed to
|
|
249
|
+
stdout instead of saved (keeps own profile out of the contacts DB).
|
|
250
|
+
- Refuses to run if NEITHER MY_LINKEDIN_URL nor LINKEDIN_NAME is set.
|
|
251
|
+
- Any --with-* section that returns 0 entries (DOM change / auth blip)
|
|
252
|
+
preserves the existing stored value \u2014 never wiped.
|
|
253
|
+
- _lastEnrichedAt is set only when at least one rich section returned data.
|
|
254
|
+
|
|
255
|
+
BAN RISK
|
|
256
|
+
Low. One profile = 1 to 7 page loads depending on flags, all targeting the
|
|
257
|
+
same profile = normal "deep read" human behavior. Intentionally no batch
|
|
258
|
+
mode here. For gated batch enrichment use 'enrich-profiles --with-experience'.
|
|
259
|
+
|
|
260
|
+
WHEN TO USE
|
|
261
|
+
- Audit your own LinkedIn profile (--full prints everything to stdout)
|
|
262
|
+
- Deep-dive on one specific contact before reaching out
|
|
263
|
+
- Verify what we know about a recruiter / lead
|
|
264
|
+
`)}It&&(We(),process.exit(0));N||(We(),process.exit(1));/linkedin\.com\/in\//i.test(N)||(console.error(`URL doesn't look like a LinkedIn profile: ${N}`),console.error("Expected format: https://www.linkedin.com/in/<slug>/"),process.exit(1));var me=Be(process.env.MY_LINKEDIN_URL||""),te=He(process.env.LINKEDIN_NAME||"");!me&&!te&&(console.error(""),console.error(" \u26D4 Refusing to run: cannot self-detect without configuration."),console.error(""),console.error(" Set EITHER (preferably both) of:"),console.error(" MY_LINKEDIN_URL=https://www.linkedin.com/in/<your-slug>"),console.error(' LINKEDIN_NAME="Your Full Name"'),console.error(""),console.error(" in .env (dev) or via `ilml plugin config linkedin set <KEY> <VALUE>` (prod)."),console.error(" This prevents your own profile from accidentally landing in people.json."),console.error(""),process.exit(1));var ee=me&&Be(N)===me,de=Ue.filter(([,t])=>t).map(([t])=>t);console.log("");console.log(` enrichProfile \u2014 ${N}`);R?console.log(` Mode: --full (${fe} page loads: main + ${de.join(" + ")})`):de.length>0?console.log(` Mode: rich (${fe} loads: main + ${de.join(" + ")})`):console.log(" Mode: basic (1 load \u2014 main page only)");console.log(ee?" Target: SELF (URL match) \u2014 will print to stdout, not saved to people.json":te?` Target: TBD \u2014 name-match against "${process.env.LINKEDIN_NAME}" after fetch`:" Target: will save to people.json (no MY_LINKEDIN_URL or LINKEDIN_NAME set for self-check)");Ve>0&&(console.log(""),console.log(` \u26A0 ${fe} page loads on the SAME profile = normal "deep read" pattern.`),console.log(" This is intentionally single-URL \u2014 DO NOT batch. For batch enrichment"),console.log(" use `enrichProfiles.mjs --with-experience` (gated, capped)."));console.log("");var K=null;try{K=await Et.launch({headless:!1,defaultViewport:null,protocolTimeout:3e5});let t=await K.newPage();await t.setCookie(...qe());let e=await je(t,N,{extractExperience:Y,extractFeatured:Q,extractEducation:z,extractSkills:G,extractRecommendations:Z,extractCertifications:X});if((!e||!e.name)&&(console.error(" viewProfile returned no name \u2014 profile not loaded or DOM changed"),process.exit(1)),!ee&&te&&e.name&&He(e.name)===te&&(ee=!0,console.log(" \u2191 Detected self via LINKEDIN_NAME match \u2014 will NOT save to people.json")),console.log(""),console.log(" \u2500\u2500\u2500 extracted \u2500\u2500\u2500"),console.log(` name: ${e.name}`),console.log(` title: ${e.title||"(none)"}`),console.log(` location: ${e.location||"(none)"}`),console.log(` about: ${e.about?`${e.about.length} chars`:"(none)"}`),console.log(` topSkills: ${e.topSkills?e.topSkills.join(", "):"(none)"}`),Y&&console.log(` experience: ${(e.experience||[]).length} entries`),Q&&console.log(` featured: ${(e.featured||[]).length} entries`),z&&console.log(` education: ${(e.education||[]).length} entries`),G&&console.log(` skillsFull: ${(e.skillsFull||[]).length} entries`),Z&&console.log(` recommendations: ${(e.recommendations||[]).length} entries`),X&&console.log(` certifications: ${(e.certifications||[]).length} entries`),console.log(""),ee)console.log(" \u2500\u2500\u2500 full data (self \u2014 not persisted) \u2500\u2500\u2500"),console.log(JSON.stringify(e,null,2));else{let n={name:e.name,title:e.title,location:e.location,about:e.about,currentCompany:e.currentCompany,currentSchool:e.currentSchool,topSkills:e.topSkills,availableSections:e.availableSections,connectionsLevel:e.connectionsLevel,mutualConnectionsCount:e.mutualConnectionsCount,followers:e.followers,openToWork:e.openToWork,hiring:e.hiring,hasVerifiedBadge:e.hasVerifiedBadge,photoUrl:e.photoUrl,source:"enrich-profile-single"},o=[["experience",Y,e.experience],["featured",Q,e.featured],["education",z,e.education],["skillsFull",G,e.skillsFull],["recommendations",Z,e.recommendations],["certifications",X,e.certifications]],i=!1;for(let[s,f,d]of o)f&&(Array.isArray(d)&&d.length>0?(n[s]=d,i=!0):console.log(` \u26A0 --with-${s==="skillsFull"?"skills":s} returned 0 entries \u2014 NOT writing ${s} (existing data preserved)`));i&&(n._lastEnrichedAt=new Date().toISOString()),ue(N,n),console.log(" \u2713 Saved to people.json")}}catch(t){console.error(" Error:",t.message),process.exit(1)}finally{K&&await K.close().catch(()=>{})}
|