openrich 0.0.0-stage → 0.1.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.
Files changed (65) hide show
  1. package/.env.example +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +410 -2
  4. package/assets/logo.svg +41 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +144 -0
  7. package/dist/env.d.ts +5 -0
  8. package/dist/env.js +24 -0
  9. package/dist/eval.d.ts +30 -0
  10. package/dist/eval.js +78 -0
  11. package/dist/mcp/client.d.ts +31 -0
  12. package/dist/mcp/client.js +94 -0
  13. package/dist/mcp/oauth.d.ts +13 -0
  14. package/dist/mcp/oauth.js +93 -0
  15. package/dist/mcp/server.d.ts +87 -0
  16. package/dist/mcp/server.js +125 -0
  17. package/dist/merge.d.ts +7 -0
  18. package/dist/merge.js +39 -0
  19. package/dist/providers/devplatforms.d.ts +34 -0
  20. package/dist/providers/devplatforms.js +612 -0
  21. package/dist/providers/finders.d.ts +38 -0
  22. package/dist/providers/finders.js +708 -0
  23. package/dist/providers/freetier.d.ts +9 -0
  24. package/dist/providers/freetier.js +254 -0
  25. package/dist/providers/github.d.ts +8 -0
  26. package/dist/providers/github.js +109 -0
  27. package/dist/providers/identity.d.ts +5 -0
  28. package/dist/providers/identity.js +62 -0
  29. package/dist/providers/index.d.ts +10 -0
  30. package/dist/providers/index.js +68 -0
  31. package/dist/providers/knowledge.d.ts +52 -0
  32. package/dist/providers/knowledge.js +302 -0
  33. package/dist/providers/pattern.d.ts +6 -0
  34. package/dist/providers/pattern.js +99 -0
  35. package/dist/providers/registries.d.ts +36 -0
  36. package/dist/providers/registries.js +396 -0
  37. package/dist/providers/research.d.ts +30 -0
  38. package/dist/providers/research.js +471 -0
  39. package/dist/providers/signals.d.ts +15 -0
  40. package/dist/providers/signals.js +116 -0
  41. package/dist/providers/smtp.d.ts +25 -0
  42. package/dist/providers/smtp.js +97 -0
  43. package/dist/providers/social.d.ts +37 -0
  44. package/dist/providers/social.js +657 -0
  45. package/dist/providers/verifiers.d.ts +47 -0
  46. package/dist/providers/verifiers.js +455 -0
  47. package/dist/providers/websearch.d.ts +32 -0
  48. package/dist/providers/websearch.js +346 -0
  49. package/dist/router.d.ts +31 -0
  50. package/dist/router.js +214 -0
  51. package/dist/server.d.ts +2 -0
  52. package/dist/server.js +52 -0
  53. package/dist/store.d.ts +32 -0
  54. package/dist/store.js +95 -0
  55. package/dist/types.d.ts +82 -0
  56. package/dist/types.js +1 -0
  57. package/dist/util/http.d.ts +19 -0
  58. package/dist/util/http.js +34 -0
  59. package/dist/util/match.d.ts +23 -0
  60. package/dist/util/match.js +72 -0
  61. package/dist/util/names.d.ts +11 -0
  62. package/dist/util/names.js +56 -0
  63. package/dist/util/patterns.d.ts +14 -0
  64. package/dist/util/patterns.js +61 -0
  65. package/package.json +55 -4
@@ -0,0 +1,32 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import type { Finding, Quota } from './types.ts';
3
+ /**
4
+ * Local-only storage: result cache, per-provider quota counters, learned email patterns per domain.
5
+ * Never shared: a shared cache would turn this project into a data broker.
6
+ */
7
+ export declare class Store {
8
+ db: DatabaseSync;
9
+ constructor(path?: string);
10
+ getCache(provider: string, key: string, maxAgeDays?: number): Finding[] | null;
11
+ setCache(provider: string, key: string, findings: Finding[]): void;
12
+ static periodKey(q: Quota, now?: Date): string;
13
+ quotaLeft(provider: string, q: Quota): number;
14
+ useQuota(provider: string, q: Quota, n?: number): void;
15
+ markExhausted(provider: string, q: Quota): void;
16
+ knownPattern(domain: string): string | null;
17
+ learnPattern(domain: string, pattern: string): void;
18
+ getDomainInfo(domain: string): {
19
+ catchAll: boolean | null;
20
+ mx: string[];
21
+ } | null;
22
+ setDomainInfo(domain: string, info: {
23
+ catchAll: boolean | null;
24
+ mx: string[];
25
+ }): void;
26
+ quotaReport(): {
27
+ provider: string;
28
+ period: string;
29
+ used: number;
30
+ exhausted: number;
31
+ }[];
32
+ }
package/dist/store.js ADDED
@@ -0,0 +1,95 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { existsSync, mkdirSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { homedir } from 'node:os';
5
+ /** ~/.openrich/db.sqlite; keeps using ~/.enrich-router/ (the old name) if that is where an existing cache lives. */
6
+ function defaultPath() {
7
+ const old = join(homedir(), '.enrich-router', 'db.sqlite');
8
+ const cur = join(process.env.OPENRICH_HOME ?? join(homedir(), '.openrich'), 'db.sqlite');
9
+ return !existsSync(cur) && existsSync(old) ? old : cur;
10
+ }
11
+ /**
12
+ * Local-only storage: result cache, per-provider quota counters, learned email patterns per domain.
13
+ * Never shared: a shared cache would turn this project into a data broker.
14
+ */
15
+ export class Store {
16
+ db;
17
+ constructor(path = process.env.ENRICH_DB ?? defaultPath()) {
18
+ if (path !== ':memory:')
19
+ mkdirSync(dirname(path), { recursive: true });
20
+ this.db = new DatabaseSync(path);
21
+ this.db.exec(`
22
+ CREATE TABLE IF NOT EXISTS cache (
23
+ provider TEXT NOT NULL, key TEXT NOT NULL, findings TEXT NOT NULL, ts INTEGER NOT NULL,
24
+ PRIMARY KEY (provider, key));
25
+ CREATE TABLE IF NOT EXISTS quota (
26
+ provider TEXT NOT NULL, period TEXT NOT NULL, used INTEGER NOT NULL DEFAULT 0,
27
+ exhausted INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (provider, period));
28
+ CREATE TABLE IF NOT EXISTS patterns (
29
+ domain TEXT NOT NULL, pattern TEXT NOT NULL, hits INTEGER NOT NULL DEFAULT 1,
30
+ PRIMARY KEY (domain, pattern));
31
+ CREATE TABLE IF NOT EXISTS domain_info (
32
+ domain TEXT PRIMARY KEY, catch_all INTEGER, mx TEXT, ts INTEGER NOT NULL);
33
+ `);
34
+ }
35
+ getCache(provider, key, maxAgeDays = 90) {
36
+ const row = this.db.prepare('SELECT findings, ts FROM cache WHERE provider = ? AND key = ?').get(provider, key);
37
+ if (!row || Date.now() - row.ts > maxAgeDays * 86400_000)
38
+ return null;
39
+ return JSON.parse(row.findings);
40
+ }
41
+ setCache(provider, key, findings) {
42
+ this.db
43
+ .prepare('INSERT OR REPLACE INTO cache (provider, key, findings, ts) VALUES (?, ?, ?, ?)')
44
+ .run(provider, key, JSON.stringify(findings), Date.now());
45
+ }
46
+ static periodKey(q, now = new Date()) {
47
+ const ym = now.toISOString().slice(0, 7);
48
+ return q.period === 'month' ? ym : now.toISOString().slice(0, 10);
49
+ }
50
+ quotaLeft(provider, q) {
51
+ const row = this.db
52
+ .prepare('SELECT used, exhausted FROM quota WHERE provider = ? AND period = ?')
53
+ .get(provider, Store.periodKey(q));
54
+ if (!row)
55
+ return q.limit;
56
+ if (row.exhausted)
57
+ return 0;
58
+ return Math.max(0, q.limit - row.used);
59
+ }
60
+ useQuota(provider, q, n = 1) {
61
+ this.db
62
+ .prepare('INSERT INTO quota (provider, period, used) VALUES (?, ?, ?) ON CONFLICT(provider, period) DO UPDATE SET used = used + excluded.used')
63
+ .run(provider, Store.periodKey(q), n);
64
+ }
65
+ markExhausted(provider, q) {
66
+ this.db
67
+ .prepare('INSERT INTO quota (provider, period, used, exhausted) VALUES (?, ?, 0, 1) ON CONFLICT(provider, period) DO UPDATE SET exhausted = 1')
68
+ .run(provider, Store.periodKey(q));
69
+ }
70
+ knownPattern(domain) {
71
+ const row = this.db
72
+ .prepare('SELECT pattern FROM patterns WHERE domain = ? ORDER BY hits DESC LIMIT 1')
73
+ .get(domain);
74
+ return row?.pattern ?? null;
75
+ }
76
+ learnPattern(domain, pattern) {
77
+ this.db
78
+ .prepare('INSERT INTO patterns (domain, pattern) VALUES (?, ?) ON CONFLICT(domain, pattern) DO UPDATE SET hits = hits + 1')
79
+ .run(domain, pattern);
80
+ }
81
+ getDomainInfo(domain) {
82
+ const row = this.db.prepare('SELECT catch_all, mx, ts FROM domain_info WHERE domain = ?').get(domain);
83
+ if (!row || Date.now() - row.ts > 30 * 86400_000)
84
+ return null;
85
+ return { catchAll: row.catch_all === null ? null : row.catch_all === 1, mx: JSON.parse(row.mx) };
86
+ }
87
+ setDomainInfo(domain, info) {
88
+ this.db
89
+ .prepare('INSERT OR REPLACE INTO domain_info (domain, catch_all, mx, ts) VALUES (?, ?, ?, ?)')
90
+ .run(domain, info.catchAll === null ? null : info.catchAll ? 1 : 0, JSON.stringify(info.mx), Date.now());
91
+ }
92
+ quotaReport() {
93
+ return this.db.prepare('SELECT provider, period, used, exhausted FROM quota ORDER BY provider, period').all();
94
+ }
95
+ }
@@ -0,0 +1,82 @@
1
+ export type Field = 'email' | 'personal_email' | 'name' | 'title' | 'company' | 'location' | 'linkedin' | 'github' | 'twitter' | 'website' | 'photo' | 'bio' | 'phone'
2
+ /** ORCID iD as https://orcid.org/0000-.... */
3
+ | 'orcid'
4
+ /** Any other public profile URL (Wikidata, Stack Overflow, Bluesky, Hacker News, ...). Many values are normal. */
5
+ | 'profile';
6
+ /** What the caller knows about the person. Any subset works; providers declare what they need. */
7
+ export interface PersonQuery {
8
+ name?: string;
9
+ firstName?: string;
10
+ lastName?: string;
11
+ domain?: string;
12
+ company?: string;
13
+ email?: string;
14
+ github?: string;
15
+ /**
16
+ * Filled by the router each round, never by the caller.
17
+ * usernames: handles seen so far (GitHub login, X handle, email local part), for username-based sources.
18
+ * emailCandidates: emails found but not yet confirmed (below threshold), best first, for verifiers.
19
+ */
20
+ usernames?: string[];
21
+ emailCandidates?: string[];
22
+ }
23
+ /** One claim about the person from one source. */
24
+ export interface Finding {
25
+ field: Field;
26
+ value: string;
27
+ source: string;
28
+ /** 0..1, how sure this source is. */
29
+ confidence: number;
30
+ evidence?: string;
31
+ }
32
+ export type ProviderKind = 'free' | 'free-tier';
33
+ export interface Quota {
34
+ limit: number;
35
+ period: 'day' | 'month';
36
+ }
37
+ export interface ProviderContext {
38
+ fetch: typeof fetch;
39
+ env: Record<string, string | undefined>;
40
+ log: (msg: string) => void;
41
+ store: import('./store.ts').Store;
42
+ }
43
+ export interface Provider {
44
+ id: string;
45
+ /** free = no key and no metered quota; free-tier = needs the user's own key, has a monthly/daily quota. */
46
+ kind: ProviderKind;
47
+ description: string;
48
+ provides: Field[];
49
+ /** Env var holding the API key, if any. */
50
+ keyEnv?: string;
51
+ /** Overrides the keyEnv check when a provider can be enabled more than one way (API key or MCP sign-in). */
52
+ enabled?(env: Record<string, string | undefined>): boolean;
53
+ quota?: Quota;
54
+ /** Counts quota on every call, not only on hits (verifiers, and finders that bill misses). */
55
+ chargesOnMiss?: boolean;
56
+ /** Verifies q.emailCandidates[0] rather than finding an email; the router then stops offering that candidate. */
57
+ verifies?: boolean;
58
+ /** Free sources that read q.usernames / q.emailCandidates / q.github: run again if they missed and those grew. */
59
+ retryOnNewInputs?: boolean;
60
+ /** True when the query has the inputs this provider needs. */
61
+ needs(q: PersonQuery): boolean;
62
+ run(q: PersonQuery, ctx: ProviderContext): Promise<Finding[]>;
63
+ }
64
+ export interface TraceEntry {
65
+ provider: string;
66
+ status: 'hit' | 'miss' | 'cached' | 'skipped' | 'error';
67
+ ms: number;
68
+ /** When it finished, in ms since the lookup started. */
69
+ at?: number;
70
+ note?: string;
71
+ }
72
+ export interface FieldResult {
73
+ value: string;
74
+ confidence: number;
75
+ sources: string[];
76
+ }
77
+ export interface EnrichResult {
78
+ query: PersonQuery;
79
+ best: Partial<Record<Field, FieldResult>>;
80
+ alternatives: Partial<Record<Field, FieldResult[]>>;
81
+ trace: TraceEntry[];
82
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ export declare class HttpError extends Error {
2
+ status: number;
3
+ body: string;
4
+ constructor(status: number, body: string, url: string);
5
+ }
6
+ /** Raised when a provider says our quota is used up, so the router can stop calling it. */
7
+ export declare class QuotaExceeded extends Error {
8
+ }
9
+ export declare function getJson<T = any>(f: typeof fetch, url: string, init?: RequestInit, timeoutMs?: number): Promise<{
10
+ status: number;
11
+ data: T | null;
12
+ }>;
13
+ /**
14
+ * Sent on every request. Public APIs (Wikimedia, SEC, crates.io) give far higher limits to clients that
15
+ * name a contact: set ENRICH_CONTACT in .env to your email or project URL. Without it Wikimedia allows ~10 req/min.
16
+ */
17
+ export declare const UA: string;
18
+ /** Stable key for per-process caches: the router wraps fetch per lookup (timeouts), the base fetch stays the same. */
19
+ export declare function fetchKey(f: typeof fetch): typeof fetch;
@@ -0,0 +1,34 @@
1
+ export class HttpError extends Error {
2
+ status;
3
+ body;
4
+ constructor(status, body, url) {
5
+ super(`HTTP ${status} from ${new URL(url).host}: ${body.slice(0, 200)}`);
6
+ this.status = status;
7
+ this.body = body;
8
+ }
9
+ }
10
+ /** Raised when a provider says our quota is used up, so the router can stop calling it. */
11
+ export class QuotaExceeded extends Error {
12
+ }
13
+ export async function getJson(f, url, init = {}, timeoutMs = 15000) {
14
+ const res = await f(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
15
+ const text = await res.text();
16
+ if (res.status === 404)
17
+ return { status: 404, data: null };
18
+ if (res.status === 403 && /rate limit/i.test(text))
19
+ throw new QuotaExceeded(`rate limited by ${new URL(url).host}`);
20
+ if (res.status === 429 || res.status === 402)
21
+ throw new QuotaExceeded(`HTTP ${res.status} from ${new URL(url).host}`);
22
+ if (!res.ok)
23
+ throw new HttpError(res.status, text, url);
24
+ return { status: res.status, data: text ? JSON.parse(text) : null };
25
+ }
26
+ /**
27
+ * Sent on every request. Public APIs (Wikimedia, SEC, crates.io) give far higher limits to clients that
28
+ * name a contact: set ENRICH_CONTACT in .env to your email or project URL. Without it Wikimedia allows ~10 req/min.
29
+ */
30
+ export const UA = `openrich/0.1 (${process.env.ENRICH_CONTACT || 'open-source people enrichment; set ENRICH_CONTACT'})`;
31
+ /** Stable key for per-process caches: the router wraps fetch per lookup (timeouts), the base fetch stays the same. */
32
+ export function fetchKey(f) {
33
+ return f.base ?? f;
34
+ }
@@ -0,0 +1,23 @@
1
+ import type { PersonQuery } from '../types.ts';
2
+ /**
3
+ * Same person name? Compares first + last name (accents, case, middle names ignored).
4
+ * "Patrick Collison" matches "Patrick J. Collison" and "COLLISON, Patrick"; first initial "P. Collison" only if allowInitial.
5
+ */
6
+ export declare function sameName(a: string | undefined, b: string | undefined, allowInitial?: boolean): boolean;
7
+ /** Does some text (an affiliation, employer, bio, URL) point at the query's company or domain? */
8
+ export declare function mentionsCompany(text: string | undefined | null, q: PersonQuery): boolean;
9
+ /**
10
+ * How much a profile match is worth, by the kind of evidence (one rule for every source):
11
+ * - LINKED: a page the person controls links to the account (a backlink), or a confirmed account links to it.
12
+ * - CLAIMED: name and company both match, but only as text on the profile. Anyone can type that, and copycat
13
+ * accounts do (e.g. a "Yann LeCun" GitHub account with his bio and website). Kept below the 0.8 "confident"
14
+ * line, so one claimed source never settles a field on its own; two independent ones agreeing do (0.91).
15
+ * - A name-only match is not evidence of anything and is dropped.
16
+ */
17
+ export declare const LINKED = 0.9;
18
+ export declare const CLAIMED = 0.7;
19
+ /**
20
+ * Does the page at pageUrl link to target (a profile URL such as https://github.com/jdoe)?
21
+ * Reads at most 500 KB; any error or non-HTML answer counts as no.
22
+ */
23
+ export declare function linksBack(fetchFn: typeof fetch, pageUrl: string | null | undefined, target: string): Promise<boolean>;
@@ -0,0 +1,72 @@
1
+ import { slug, splitName } from "./names.js";
2
+ /**
3
+ * Same person name? Compares first + last name (accents, case, middle names ignored).
4
+ * "Patrick Collison" matches "Patrick J. Collison" and "COLLISON, Patrick"; first initial "P. Collison" only if allowInitial.
5
+ */
6
+ export function sameName(a, b, allowInitial = false) {
7
+ if (!a || !b)
8
+ return false;
9
+ const norm = (s) => {
10
+ const t = s.includes(',') ? s.split(',').reverse().join(' ') : s;
11
+ const { first, last } = splitName(t);
12
+ const lastTok = last.split(/\s+/).pop() ?? '';
13
+ return { first: slug(first), last: slug(lastTok) };
14
+ };
15
+ const x = norm(a);
16
+ const y = norm(b);
17
+ if (!x.last || !y.last || x.last !== y.last)
18
+ return false;
19
+ if (x.first === y.first)
20
+ return true;
21
+ if (allowInitial && x.first && y.first && x.first[0] === y.first[0] && (x.first.length === 1 || y.first.length === 1))
22
+ return true;
23
+ return false;
24
+ }
25
+ /** Does some text (an affiliation, employer, bio, URL) point at the query's company or domain? */
26
+ export function mentionsCompany(text, q) {
27
+ if (!text)
28
+ return false;
29
+ const t = text.toLowerCase();
30
+ if (q.domain) {
31
+ if (t.includes(q.domain))
32
+ return true;
33
+ const root = q.domain.split('.')[0];
34
+ if (root.length >= 4 && new RegExp(`\\b${root}\\b`).test(t))
35
+ return true;
36
+ }
37
+ if (q.company) {
38
+ const c = q.company.toLowerCase().replace(/\b(inc|llc|ltd|gmbh|corp|corporation|co|company|plc|sa|ag)\b\.?/g, '').trim();
39
+ if (c.length >= 3 && t.includes(c))
40
+ return true;
41
+ }
42
+ return false;
43
+ }
44
+ /**
45
+ * How much a profile match is worth, by the kind of evidence (one rule for every source):
46
+ * - LINKED: a page the person controls links to the account (a backlink), or a confirmed account links to it.
47
+ * - CLAIMED: name and company both match, but only as text on the profile. Anyone can type that, and copycat
48
+ * accounts do (e.g. a "Yann LeCun" GitHub account with his bio and website). Kept below the 0.8 "confident"
49
+ * line, so one claimed source never settles a field on its own; two independent ones agreeing do (0.91).
50
+ * - A name-only match is not evidence of anything and is dropped.
51
+ */
52
+ export const LINKED = 0.9;
53
+ export const CLAIMED = 0.7;
54
+ /**
55
+ * Does the page at pageUrl link to target (a profile URL such as https://github.com/jdoe)?
56
+ * Reads at most 500 KB; any error or non-HTML answer counts as no.
57
+ */
58
+ export async function linksBack(fetchFn, pageUrl, target) {
59
+ if (!pageUrl || !/^https?:\/\//i.test(pageUrl))
60
+ return false;
61
+ try {
62
+ const res = await fetchFn(pageUrl, { headers: { 'user-agent': 'openrich/0.1', accept: 'text/html' }, redirect: 'follow' });
63
+ if (!res.ok || !/html/i.test(res.headers.get('content-type') ?? 'text/html'))
64
+ return false;
65
+ const html = (await res.text()).slice(0, 500_000);
66
+ const t = target.replace(/^https?:\/\/(www\.)?/i, '').replace(/\/$/, '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
67
+ return new RegExp(`(?:https?:)?//(?:www\\.)?${t}(?![\\w-])`, 'i').test(html);
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
@@ -0,0 +1,11 @@
1
+ import type { PersonQuery } from '../types.ts';
2
+ /** Lowercase ASCII letters only: "José-María" -> "josemaria". */
3
+ export declare function slug(s: string): string;
4
+ export declare function splitName(full: string): {
5
+ first: string;
6
+ last: string;
7
+ };
8
+ export declare function cleanDomain(d: string): string;
9
+ /** Fill firstName/lastName from name (and vice versa), normalise domain and email. */
10
+ export declare function normalizeQuery(q: PersonQuery): PersonQuery;
11
+ export declare function hasNameAndDomain(q: PersonQuery): boolean;
@@ -0,0 +1,56 @@
1
+ /** Lowercase ASCII letters only: "José-María" -> "josemaria". */
2
+ export function slug(s) {
3
+ return s
4
+ .normalize('NFD')
5
+ .replace(/[̀-ͯ]/g, '')
6
+ .toLowerCase()
7
+ .replace(/[^a-z]/g, '');
8
+ }
9
+ const SUFFIXES = new Set(['jr', 'sr', 'ii', 'iii', 'iv', 'phd', 'md', 'mba', 'esq']);
10
+ const PREFIXES = new Set(['dr', 'mr', 'mrs', 'ms', 'prof', 'sir']);
11
+ export function splitName(full) {
12
+ const parts = full
13
+ .replace(/[(),]/g, ' ')
14
+ .split(/\s+/)
15
+ .filter(Boolean)
16
+ .filter((p) => !SUFFIXES.has(slug(p)) && !PREFIXES.has(slug(p)));
17
+ if (parts.length === 0)
18
+ return { first: '', last: '' };
19
+ if (parts.length === 1)
20
+ return { first: parts[0], last: '' };
21
+ return { first: parts[0], last: parts.slice(1).join(' ') };
22
+ }
23
+ export function cleanDomain(d) {
24
+ return d
25
+ .trim()
26
+ .toLowerCase()
27
+ .replace(/^[a-z]+:\/\//, '')
28
+ .replace(/^www\./, '')
29
+ .replace(/\/.*$/, '');
30
+ }
31
+ /** Fill firstName/lastName from name (and vice versa), normalise domain and email. */
32
+ export function normalizeQuery(q) {
33
+ const out = { ...q };
34
+ if (out.name && !(out.firstName && out.lastName)) {
35
+ const { first, last } = splitName(out.name);
36
+ out.firstName ??= first || undefined;
37
+ out.lastName ??= last || undefined;
38
+ }
39
+ if (!out.name && out.firstName)
40
+ out.name = [out.firstName, out.lastName].filter(Boolean).join(' ');
41
+ if (out.domain)
42
+ out.domain = cleanDomain(out.domain);
43
+ if (out.email) {
44
+ out.email = out.email.trim().toLowerCase();
45
+ out.domain ??= out.email.split('@')[1];
46
+ }
47
+ if (out.github)
48
+ out.github = out.github.replace(/^https?:\/\/github\.com\//, '').replace(/\/.*$/, '');
49
+ for (const k of Object.keys(out))
50
+ if (!out[k])
51
+ delete out[k];
52
+ return out;
53
+ }
54
+ export function hasNameAndDomain(q) {
55
+ return Boolean(q.firstName && q.lastName && q.domain);
56
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Email local-part templates, most common first (rough order from public B2B studies).
3
+ * Tokens: {first} {last} {f} {l}
4
+ */
5
+ export declare const PATTERNS: readonly ["{first}.{last}", "{first}", "{f}{last}", "{first}{last}", "{first}_{last}", "{f}.{last}", "{first}{l}", "{last}.{first}", "{first}-{last}", "{last}", "{last}{f}", "{first}.{l}", "{last}{first}"];
6
+ export type Pattern = (typeof PATTERNS)[number];
7
+ export declare function applyPattern(p: string, first: string, last: string): string | null;
8
+ /** Candidate addresses, with a known domain pattern (if any) moved to the front. */
9
+ export declare function candidates(first: string, last: string, domain: string, known?: string | null): {
10
+ email: string;
11
+ pattern: string;
12
+ }[];
13
+ /** Which pattern produced this email for this person, if any. Used to learn a domain's pattern. */
14
+ export declare function detectPattern(email: string, first: string, last: string): string | null;
@@ -0,0 +1,61 @@
1
+ import { slug } from "./names.js";
2
+ /**
3
+ * Email local-part templates, most common first (rough order from public B2B studies).
4
+ * Tokens: {first} {last} {f} {l}
5
+ */
6
+ export const PATTERNS = [
7
+ '{first}.{last}',
8
+ '{first}',
9
+ '{f}{last}',
10
+ '{first}{last}',
11
+ '{first}_{last}',
12
+ '{f}.{last}',
13
+ '{first}{l}',
14
+ '{last}.{first}',
15
+ '{first}-{last}',
16
+ '{last}',
17
+ '{last}{f}',
18
+ '{first}.{l}',
19
+ '{last}{first}',
20
+ ];
21
+ function tokens(first, last) {
22
+ const f = slug(first);
23
+ // "van der Berg" -> "vanderberg"; also used for hyphenated names.
24
+ const l = slug(last);
25
+ return { first: f, last: l, f: f.slice(0, 1), l: l.slice(0, 1) };
26
+ }
27
+ export function applyPattern(p, first, last) {
28
+ const t = tokens(first, last);
29
+ if (!t.first)
30
+ return null;
31
+ if (!t.last && /\{(last|l)\}/.test(p))
32
+ return null;
33
+ return p.replace(/\{(first|last|f|l)\}/g, (_, k) => t[k]);
34
+ }
35
+ /** Candidate addresses, with a known domain pattern (if any) moved to the front. */
36
+ export function candidates(first, last, domain, known) {
37
+ const order = known ? [known, ...PATTERNS.filter((p) => p !== known)] : [...PATTERNS];
38
+ const seen = new Set();
39
+ const out = [];
40
+ for (const p of order) {
41
+ const local = applyPattern(p, first, last);
42
+ if (!local)
43
+ continue;
44
+ const email = `${local}@${domain}`;
45
+ if (seen.has(email))
46
+ continue;
47
+ seen.add(email);
48
+ out.push({ email, pattern: p });
49
+ }
50
+ return out;
51
+ }
52
+ /** Which pattern produced this email for this person, if any. Used to learn a domain's pattern. */
53
+ export function detectPattern(email, first, last) {
54
+ const local = email.split('@')[0]?.toLowerCase();
55
+ if (!local)
56
+ return null;
57
+ for (const p of PATTERNS)
58
+ if (applyPattern(p, first, last) === local)
59
+ return p;
60
+ return null;
61
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "openrich",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Open-source, free-first people enrichment: 80 sources, free ones first, one waterfall router. CLI, HTTP API and MCP server.",
5
+ "keywords": [
6
+ "enrichment",
7
+ "people",
8
+ "email-finder",
9
+ "lead-enrichment",
10
+ "clay-alternative",
11
+ "waterfall",
12
+ "mcp",
13
+ "mcp-server",
14
+ "open-source",
15
+ "cli"
16
+ ],
17
+ "homepage": "https://github.com/sk1122/openrich#readme",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/sk1122/openrich.git"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/sk1122/openrich/issues"
24
+ },
25
+ "author": "sk1122",
26
+ "license": "MIT",
27
+ "type": "module",
28
+ "bin": {
29
+ "openrich": "./dist/cli.js"
30
+ },
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/router.d.ts",
34
+ "default": "./dist/router.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "assets/logo.svg",
40
+ ".env.example"
41
+ ],
42
+ "engines": {
43
+ "node": ">=22.13"
44
+ },
45
+ "scripts": {
46
+ "openrich": "node --disable-warning=ExperimentalWarning src/cli.ts",
47
+ "enrich": "node --disable-warning=ExperimentalWarning src/cli.ts",
48
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/cli.js",
49
+ "test": "node --test test/*.test.ts",
50
+ "typecheck": "tsc --noEmit",
51
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^24.0.0",
55
+ "typescript": "^5.9.0"
56
+ }
57
+ }