-
-
Notifications
You must be signed in to change notification settings - Fork 7.2k
Expand file tree
/
Copy pathscan.mjs
More file actions
367 lines (306 loc) · 12 KB
/
scan.mjs
File metadata and controls
367 lines (306 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#!/usr/bin/env node
/**
* scan.mjs — Zero-token portal scanner
*
* Fetches Greenhouse, Ashby, and Lever APIs directly, applies title
* filters from portals.yml, deduplicates against existing history,
* and appends new offers to pipeline.md + scan-history.tsv.
*
* Zero Claude API tokens — pure HTTP + JSON.
*
* Usage:
* node scan.mjs # scan all enabled companies
* node scan.mjs --dry-run # preview without writing files
* node scan.mjs --company Cohere # scan a single company
*/
import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync } from 'fs';
import yaml from 'js-yaml';
const parseYaml = yaml.load;
// ── Config ──────────────────────────────────────────────────────────
const PORTALS_PATH = 'portals.yml';
const SCAN_HISTORY_PATH = 'data/scan-history.tsv';
const PIPELINE_PATH = 'data/pipeline.md';
const APPLICATIONS_PATH = 'data/applications.md';
// Ensure required directories exist (fresh setup)
mkdirSync('data', { recursive: true });
const CONCURRENCY = 10;
const FETCH_TIMEOUT_MS = 10_000;
// ── API detection ───────────────────────────────────────────────────
function detectApi(company) {
// Greenhouse: explicit api field
if (company.api && company.api.includes('greenhouse')) {
return { type: 'greenhouse', url: company.api };
}
const url = company.careers_url || '';
// Ashby
const ashbyMatch = url.match(/jobs\.ashbyhq\.com\/([^/?#]+)/);
if (ashbyMatch) {
return {
type: 'ashby',
url: `https://api.ashbyhq.com/posting-api/job-board/${ashbyMatch[1]}?includeCompensation=true`,
};
}
// Lever
const leverMatch = url.match(/jobs\.lever\.co\/([^/?#]+)/);
if (leverMatch) {
return {
type: 'lever',
url: `https://api.lever.co/v0/postings/${leverMatch[1]}`,
};
}
// Greenhouse EU boards
const ghEuMatch = url.match(/job-boards(?:\.eu)?\.greenhouse\.io\/([^/?#]+)/);
if (ghEuMatch && !company.api) {
return {
type: 'greenhouse',
url: `https://boards-api.greenhouse.io/v1/boards/${ghEuMatch[1]}/jobs`,
};
}
return null;
}
// ── API parsers ─────────────────────────────────────────────────────
function parseGreenhouse(json, companyName) {
const jobs = json.jobs || [];
return jobs.map(j => ({
title: j.title || '',
url: j.absolute_url || '',
company: companyName,
location: j.location?.name || '',
}));
}
function parseAshby(json, companyName) {
const jobs = json.jobs || [];
return jobs.map(j => ({
title: j.title || '',
url: j.jobUrl || '',
company: companyName,
location: j.location || '',
}));
}
function parseLever(json, companyName) {
if (!Array.isArray(json)) return [];
return json.map(j => ({
title: j.text || '',
url: j.hostedUrl || '',
company: companyName,
location: j.categories?.location || '',
}));
}
const PARSERS = { greenhouse: parseGreenhouse, ashby: parseAshby, lever: parseLever };
// ── Fetch with timeout ──────────────────────────────────────────────
async function fetchJson(url) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} finally {
clearTimeout(timer);
}
}
// ── Title filter ────────────────────────────────────────────────────
function buildTitleFilter(titleFilter) {
const positive = (titleFilter?.positive || []).map(k => k.toLowerCase());
const negative = (titleFilter?.negative || []).map(k => k.toLowerCase());
return (title) => {
const lower = title.toLowerCase();
const hasPositive = positive.length === 0 || positive.some(k => lower.includes(k));
const hasNegative = negative.some(k => lower.includes(k));
return hasPositive && !hasNegative;
};
}
// ── Dedup ───────────────────────────────────────────────────────────
function loadSeenUrls() {
const seen = new Set();
// scan-history.tsv
if (existsSync(SCAN_HISTORY_PATH)) {
const lines = readFileSync(SCAN_HISTORY_PATH, 'utf-8').split('\n');
for (const line of lines.slice(1)) { // skip header
const url = line.split('\t')[0];
if (url) seen.add(url);
}
}
// pipeline.md — extract URLs from checkbox lines
if (existsSync(PIPELINE_PATH)) {
const text = readFileSync(PIPELINE_PATH, 'utf-8');
for (const match of text.matchAll(/- \[[ x]\] (https?:\/\/\S+)/g)) {
seen.add(match[1]);
}
}
// applications.md — extract URLs from report links and any inline URLs
if (existsSync(APPLICATIONS_PATH)) {
const text = readFileSync(APPLICATIONS_PATH, 'utf-8');
for (const match of text.matchAll(/https?:\/\/[^\s|)]+/g)) {
seen.add(match[0]);
}
}
return seen;
}
function loadSeenCompanyRoles() {
const seen = new Set();
if (existsSync(APPLICATIONS_PATH)) {
const text = readFileSync(APPLICATIONS_PATH, 'utf-8');
// Parse markdown table rows: | # | Date | Company | Role | ...
for (const match of text.matchAll(/\|[^|]+\|[^|]+\|\s*([^|]+)\s*\|\s*([^|]+)\s*\|/g)) {
const company = match[1].trim().toLowerCase();
const role = match[2].trim().toLowerCase();
if (company && role && company !== 'company') {
seen.add(`${company}::${role}`);
}
}
}
return seen;
}
// ── Pipeline writer ─────────────────────────────────────────────────
function appendToPipeline(offers) {
if (offers.length === 0) return;
let text = readFileSync(PIPELINE_PATH, 'utf-8');
// Find "## Pendientes" section and append after it
const marker = '## Pendientes';
const idx = text.indexOf(marker);
if (idx === -1) {
// No Pendientes section — append at end before Procesadas
const procIdx = text.indexOf('## Procesadas');
const insertAt = procIdx === -1 ? text.length : procIdx;
const block = `\n${marker}\n\n` + offers.map(o =>
`- [ ] ${o.url} | ${o.company} | ${o.title}`
).join('\n') + '\n\n';
text = text.slice(0, insertAt) + block + text.slice(insertAt);
} else {
// Find the end of existing Pendientes content (next ## or end)
const afterMarker = idx + marker.length;
const nextSection = text.indexOf('\n## ', afterMarker);
const insertAt = nextSection === -1 ? text.length : nextSection;
const block = '\n' + offers.map(o =>
`- [ ] ${o.url} | ${o.company} | ${o.title}`
).join('\n') + '\n';
text = text.slice(0, insertAt) + block + text.slice(insertAt);
}
writeFileSync(PIPELINE_PATH, text, 'utf-8');
}
function appendToScanHistory(offers, date) {
// Ensure file + header exist
if (!existsSync(SCAN_HISTORY_PATH)) {
writeFileSync(SCAN_HISTORY_PATH, 'url\tfirst_seen\tportal\ttitle\tcompany\tstatus\n', 'utf-8');
}
const lines = offers.map(o =>
`${o.url}\t${date}\t${o.source}\t${o.title}\t${o.company}\tadded`
).join('\n') + '\n';
appendFileSync(SCAN_HISTORY_PATH, lines, 'utf-8');
}
// ── Parallel fetch with concurrency limit ───────────────────────────
async function parallelFetch(tasks, limit) {
const results = [];
let i = 0;
async function next() {
while (i < tasks.length) {
const task = tasks[i++];
results.push(await task());
}
}
const workers = Array.from({ length: Math.min(limit, tasks.length) }, () => next());
await Promise.all(workers);
return results;
}
// ── Main ────────────────────────────────────────────────────────────
async function main() {
const args = process.argv.slice(2);
const dryRun = args.includes('--dry-run');
const companyFlag = args.indexOf('--company');
const filterCompany = companyFlag !== -1 ? args[companyFlag + 1]?.toLowerCase() : null;
// 1. Read portals.yml
if (!existsSync(PORTALS_PATH)) {
console.error('Error: portals.yml not found. Run onboarding first.');
process.exit(1);
}
const config = parseYaml(readFileSync(PORTALS_PATH, 'utf-8'));
const companies = config.tracked_companies || [];
const titleFilter = buildTitleFilter(config.title_filter);
// 2. Filter to enabled companies with detectable APIs
const targets = companies
.filter(c => c.enabled !== false)
.filter(c => !filterCompany || c.name.toLowerCase().includes(filterCompany))
.map(c => ({ ...c, _api: detectApi(c) }))
.filter(c => c._api !== null);
const skippedCount = companies.filter(c => c.enabled !== false).length - targets.length;
console.log(`Scanning ${targets.length} companies via API (${skippedCount} skipped — no API detected)`);
if (dryRun) console.log('(dry run — no files will be written)\n');
// 3. Load dedup sets
const seenUrls = loadSeenUrls();
const seenCompanyRoles = loadSeenCompanyRoles();
// 4. Fetch all APIs
const date = new Date().toISOString().slice(0, 10);
let totalFound = 0;
let totalFiltered = 0;
let totalDupes = 0;
const newOffers = [];
const errors = [];
const tasks = targets.map(company => async () => {
const { type, url } = company._api;
try {
const json = await fetchJson(url);
const jobs = PARSERS[type](json, company.name);
totalFound += jobs.length;
for (const job of jobs) {
if (!titleFilter(job.title)) {
totalFiltered++;
continue;
}
if (seenUrls.has(job.url)) {
totalDupes++;
continue;
}
const key = `${job.company.toLowerCase()}::${job.title.toLowerCase()}`;
if (seenCompanyRoles.has(key)) {
totalDupes++;
continue;
}
// Mark as seen to avoid intra-scan dupes
seenUrls.add(job.url);
seenCompanyRoles.add(key);
newOffers.push({ ...job, source: `${type}-api` });
}
} catch (err) {
errors.push({ company: company.name, error: err.message });
}
});
await parallelFetch(tasks, CONCURRENCY);
// 5. Write results
if (!dryRun && newOffers.length > 0) {
appendToPipeline(newOffers);
appendToScanHistory(newOffers, date);
}
// 6. Print summary
console.log(`\n${'━'.repeat(45)}`);
console.log(`Portal Scan — ${date}`);
console.log(`${'━'.repeat(45)}`);
console.log(`Companies scanned: ${targets.length}`);
console.log(`Total jobs found: ${totalFound}`);
console.log(`Filtered by title: ${totalFiltered} removed`);
console.log(`Duplicates: ${totalDupes} skipped`);
console.log(`New offers added: ${newOffers.length}`);
if (errors.length > 0) {
console.log(`\nErrors (${errors.length}):`);
for (const e of errors) {
console.log(` ✗ ${e.company}: ${e.error}`);
}
}
if (newOffers.length > 0) {
console.log('\nNew offers:');
for (const o of newOffers) {
console.log(` + ${o.company} | ${o.title} | ${o.location || 'N/A'}`);
}
if (dryRun) {
console.log('\n(dry run — run without --dry-run to save results)');
} else {
console.log(`\nResults saved to ${PIPELINE_PATH} and ${SCAN_HISTORY_PATH}`);
}
}
console.log(`\n→ Run /career-ops pipeline to evaluate new offers.`);
console.log('→ Share results and get help: https://discord.gg/8pRpHETxa4');
}
main().catch(err => {
console.error('Fatal:', err.message);
process.exit(1);
});