@kantadev/cli 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.
- package/README.md +223 -0
- package/bin/kanta-mcp.js +8 -0
- package/bin/kanta.js +7 -0
- package/package.json +58 -0
- package/server.json +43 -0
- package/src/cli/commands/account.js +22 -0
- package/src/cli/commands/admin/index.js +136 -0
- package/src/cli/commands/credits.js +25 -0
- package/src/cli/commands/db/companies.js +133 -0
- package/src/cli/commands/db/export.js +137 -0
- package/src/cli/commands/db/index.js +190 -0
- package/src/cli/commands/find.js +57 -0
- package/src/cli/commands/jobs.js +106 -0
- package/src/cli/commands/login.js +120 -0
- package/src/cli/commands/verify.js +44 -0
- package/src/cli/context.js +134 -0
- package/src/cli/format.js +39 -0
- package/src/cli/index.js +42 -0
- package/src/core/auth.js +79 -0
- package/src/core/client.js +293 -0
- package/src/core/config.js +93 -0
- package/src/core/dbFilter.js +72 -0
- package/src/core/errors.js +65 -0
- package/src/core/identity.js +30 -0
- package/src/mcp/register.js +31 -0
- package/src/mcp/server.js +72 -0
- package/src/mcp/tools/admin.js +77 -0
- package/src/mcp/tools/customer.js +165 -0
- package/src/mcp/tools/database.js +209 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Shared helpers for CLI commands.
|
|
2
|
+
import { readFileSync, existsSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { parse as csvParse } from 'csv-parse/sync';
|
|
5
|
+
import { KantaClient } from '../core/client.js';
|
|
6
|
+
import { resolveKey } from '../core/auth.js';
|
|
7
|
+
import { whoami } from '../core/identity.js';
|
|
8
|
+
import { humanizeError } from '../core/errors.js';
|
|
9
|
+
import { printJson } from './format.js';
|
|
10
|
+
|
|
11
|
+
export const MAX_ROWS = 100_000;
|
|
12
|
+
|
|
13
|
+
export class CliExit extends Error {}
|
|
14
|
+
|
|
15
|
+
// Walk to the root commander program and return its parsed global options.
|
|
16
|
+
export function globalOpts(cmd) {
|
|
17
|
+
let root = cmd;
|
|
18
|
+
while (root.parent) root = root.parent;
|
|
19
|
+
return root.opts();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Root program carries injectable dependencies (overridable in tests).
|
|
23
|
+
export function rootProgram(cmd) {
|
|
24
|
+
let root = cmd;
|
|
25
|
+
while (root.parent) root = root.parent;
|
|
26
|
+
return root;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function defaultDeps() {
|
|
30
|
+
return {
|
|
31
|
+
clientFactory(o) {
|
|
32
|
+
const { key, baseUrl, dbBaseUrl } = resolveKey({
|
|
33
|
+
profile: o.profile,
|
|
34
|
+
apiKey: o.apiKey,
|
|
35
|
+
baseUrl: o.baseUrl,
|
|
36
|
+
dbUrl: o.dbUrl,
|
|
37
|
+
});
|
|
38
|
+
return new KantaClient({ key, baseUrl, dbBaseUrl });
|
|
39
|
+
},
|
|
40
|
+
whoamiFn(o) {
|
|
41
|
+
return whoami({ profile: o.profile, apiKey: o.apiKey, baseUrl: o.baseUrl });
|
|
42
|
+
},
|
|
43
|
+
confirm(question) {
|
|
44
|
+
return defaultConfirm(question);
|
|
45
|
+
},
|
|
46
|
+
sleep(ms) {
|
|
47
|
+
return new Promise(r => setTimeout(r, ms));
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function defaultConfirm(question) {
|
|
53
|
+
return new Promise((resolve) => {
|
|
54
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
55
|
+
rl.question(`${question} [y/N] `, (answer) => {
|
|
56
|
+
rl.close();
|
|
57
|
+
resolve(/^y(es)?$/i.test(String(answer).trim()));
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function getClient(cmd) {
|
|
63
|
+
return rootProgram(cmd)._deps.clientFactory(globalOpts(cmd));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function requireAdmin(cmd) {
|
|
67
|
+
const o = globalOpts(cmd);
|
|
68
|
+
const id = await rootProgram(cmd)._deps.whoamiFn(o);
|
|
69
|
+
if (id.scope !== 'admin') {
|
|
70
|
+
const name = id.profile || o.profile || 'default';
|
|
71
|
+
throw new CliExit(
|
|
72
|
+
`This command requires an admin profile. Active profile "${name}" is a standard key.`,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
return id;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Wrap a command action: honours --json, uniform error handling, exit code 1.
|
|
79
|
+
export function action(fn) {
|
|
80
|
+
return async (...args) => {
|
|
81
|
+
const cmd = args[args.length - 1];
|
|
82
|
+
const o = globalOpts(cmd);
|
|
83
|
+
try {
|
|
84
|
+
await fn(...args);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (err instanceof CliExit) {
|
|
87
|
+
if (o.json) printJson({ error: err.message });
|
|
88
|
+
else process.stderr.write(`Error: ${err.message}\n`);
|
|
89
|
+
process.exitCode = 1;
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
let baseUrl = o.baseUrl;
|
|
93
|
+
try {
|
|
94
|
+
baseUrl = resolveKey({ profile: o.profile, apiKey: o.apiKey, baseUrl: o.baseUrl }).baseUrl;
|
|
95
|
+
} catch {
|
|
96
|
+
/* keep o.baseUrl */
|
|
97
|
+
}
|
|
98
|
+
if (o.json) {
|
|
99
|
+
printJson({ error: err.code || err.name || 'error', status: err.status ?? null });
|
|
100
|
+
} else {
|
|
101
|
+
process.stderr.write(`Error: ${humanizeError(err, { baseUrl })}\n`);
|
|
102
|
+
}
|
|
103
|
+
process.exitCode = 1;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function readCsv(path, requiredColumns) {
|
|
109
|
+
if (!existsSync(path)) throw new CliExit(`File not found: ${path}`);
|
|
110
|
+
const raw = readFileSync(path, 'utf8');
|
|
111
|
+
if (!raw.trim()) throw new CliExit(`File is empty: ${path}`);
|
|
112
|
+
let records;
|
|
113
|
+
try {
|
|
114
|
+
records = csvParse(raw, { columns: true, skip_empty_lines: true, trim: true });
|
|
115
|
+
} catch (err) {
|
|
116
|
+
throw new CliExit(`Could not parse CSV ${path}: ${err.message}`);
|
|
117
|
+
}
|
|
118
|
+
if (records.length === 0) throw new CliExit(`No data rows in ${path}`);
|
|
119
|
+
const found = Object.keys(records[0]);
|
|
120
|
+
const missing = requiredColumns.filter(c => !found.includes(c));
|
|
121
|
+
if (missing.length) {
|
|
122
|
+
throw new CliExit(
|
|
123
|
+
`CSV ${path} is missing column(s): ${missing.join(', ')}. Expected: ${requiredColumns.join(', ')}. Found: ${found.join(', ')}.`,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
if (records.length > MAX_ROWS) {
|
|
127
|
+
throw new CliExit(`${records.length} rows exceeds the ${MAX_ROWS} per-job limit. Split the file.`);
|
|
128
|
+
}
|
|
129
|
+
return records;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function writeOut(path, content) {
|
|
133
|
+
writeFileSync(path, content);
|
|
134
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Output helpers: table / json / csv.
|
|
2
|
+
import { stringify as csvStringify } from 'csv-stringify/sync';
|
|
3
|
+
|
|
4
|
+
export function printJson(obj) {
|
|
5
|
+
process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// Minimal fixed-width table. rows: array of objects; columns: [{ key, label }]
|
|
9
|
+
export function printTable(rows, columns) {
|
|
10
|
+
if (!rows || rows.length === 0) {
|
|
11
|
+
process.stdout.write('(no rows)\n');
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const cols = columns || Object.keys(rows[0]).map(k => ({ key: k, label: k }));
|
|
15
|
+
const widths = cols.map(c =>
|
|
16
|
+
Math.max(
|
|
17
|
+
c.label.length,
|
|
18
|
+
...rows.map(r => String(r[c.key] ?? '').length),
|
|
19
|
+
),
|
|
20
|
+
);
|
|
21
|
+
const line = cells =>
|
|
22
|
+
cells.map((cell, i) => String(cell ?? '').padEnd(widths[i])).join(' ').trimEnd();
|
|
23
|
+
|
|
24
|
+
process.stdout.write(line(cols.map(c => c.label)) + '\n');
|
|
25
|
+
process.stdout.write(cols.map((_, i) => '-'.repeat(widths[i])).join(' ') + '\n');
|
|
26
|
+
for (const r of rows) {
|
|
27
|
+
process.stdout.write(line(cols.map(c => r[c.key])) + '\n');
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function toCsv(rows) {
|
|
32
|
+
if (!rows || rows.length === 0) return '';
|
|
33
|
+
const header = Object.keys(rows[0]);
|
|
34
|
+
return csvStringify(rows, { header: true, columns: header });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function printLines(lines) {
|
|
38
|
+
process.stdout.write(lines.join('\n') + '\n');
|
|
39
|
+
}
|
package/src/cli/index.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { defaultDeps } from './context.js';
|
|
3
|
+
import { registerVerify } from './commands/verify.js';
|
|
4
|
+
import { registerFind } from './commands/find.js';
|
|
5
|
+
import { registerJobs } from './commands/jobs.js';
|
|
6
|
+
import { registerAccount } from './commands/account.js';
|
|
7
|
+
import { registerCredits } from './commands/credits.js';
|
|
8
|
+
import { registerLogin } from './commands/login.js';
|
|
9
|
+
import { registerAdmin } from './commands/admin/index.js';
|
|
10
|
+
import { registerDb } from './commands/db/index.js';
|
|
11
|
+
|
|
12
|
+
export function createProgram(deps = {}) {
|
|
13
|
+
const program = new Command();
|
|
14
|
+
program._deps = { ...defaultDeps(), ...deps };
|
|
15
|
+
|
|
16
|
+
program
|
|
17
|
+
.name('kanta')
|
|
18
|
+
.description('Kanta CLI — verify, find, and manage email jobs over api.kanta.dev')
|
|
19
|
+
.version('0.1.0')
|
|
20
|
+
.option('--profile <name>', 'config profile to use')
|
|
21
|
+
.option('--api-key <key>', 'API key (overrides profile/env; never persisted)')
|
|
22
|
+
.option('--base-url <url>', 'API base URL override')
|
|
23
|
+
.option('--db-url <url>', 'Kanta Database API base URL override')
|
|
24
|
+
.option('--json', 'machine-readable JSON output', false);
|
|
25
|
+
|
|
26
|
+
registerVerify(program);
|
|
27
|
+
registerFind(program);
|
|
28
|
+
registerJobs(program);
|
|
29
|
+
registerAccount(program);
|
|
30
|
+
registerCredits(program);
|
|
31
|
+
registerLogin(program);
|
|
32
|
+
registerAdmin(program);
|
|
33
|
+
registerDb(program);
|
|
34
|
+
|
|
35
|
+
return program;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function run(argv = process.argv, deps = {}) {
|
|
39
|
+
const program = createProgram(deps);
|
|
40
|
+
await program.parseAsync(argv);
|
|
41
|
+
return program;
|
|
42
|
+
}
|
package/src/core/auth.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Resolve which API key + base URLs a command should use.
|
|
2
|
+
//
|
|
3
|
+
// Precedence (key):
|
|
4
|
+
// 1. --api-key flag (envOverride.apiKey) — never persisted
|
|
5
|
+
// 2. KANTA_API_KEY env var (+ optional KANTA_BASE_URL)
|
|
6
|
+
// 3. --profile <name> (opts.profile) from config
|
|
7
|
+
// 4. default_profile from config
|
|
8
|
+
// 5. throw KantaAuthError
|
|
9
|
+
//
|
|
10
|
+
// The Kanta Database API lives on a second host. Its base URL (`dbBaseUrl`)
|
|
11
|
+
// resolves independently with the same shape:
|
|
12
|
+
// --db-url flag → KANTA_DB_URL env → profile `db_base_url` → default
|
|
13
|
+
import { loadConfig, DEFAULT_BASE_URL, DEFAULT_DB_BASE_URL } from './config.js';
|
|
14
|
+
import { KantaAuthError } from './errors.js';
|
|
15
|
+
|
|
16
|
+
function resolveDbBaseUrl({ dbUrl, profileDbBaseUrl } = {}) {
|
|
17
|
+
return (
|
|
18
|
+
dbUrl ||
|
|
19
|
+
process.env.KANTA_DB_URL ||
|
|
20
|
+
profileDbBaseUrl ||
|
|
21
|
+
DEFAULT_DB_BASE_URL
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function resolveKey({ profile, apiKey, baseUrl, dbUrl } = {}) {
|
|
26
|
+
// 1. explicit flag
|
|
27
|
+
if (apiKey) {
|
|
28
|
+
return {
|
|
29
|
+
key: apiKey,
|
|
30
|
+
baseUrl: baseUrl || process.env.KANTA_BASE_URL || DEFAULT_BASE_URL,
|
|
31
|
+
dbBaseUrl: resolveDbBaseUrl({ dbUrl }),
|
|
32
|
+
source: 'flag',
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// 2. environment
|
|
37
|
+
if (process.env.KANTA_API_KEY) {
|
|
38
|
+
return {
|
|
39
|
+
key: process.env.KANTA_API_KEY,
|
|
40
|
+
baseUrl: baseUrl || process.env.KANTA_BASE_URL || DEFAULT_BASE_URL,
|
|
41
|
+
dbBaseUrl: resolveDbBaseUrl({ dbUrl }),
|
|
42
|
+
source: 'env',
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const config = loadConfig();
|
|
47
|
+
|
|
48
|
+
// 3. named profile
|
|
49
|
+
if (profile) {
|
|
50
|
+
const p = config.profiles[profile];
|
|
51
|
+
if (!p || !p.key) {
|
|
52
|
+
throw new KantaAuthError(`No profile named "${profile}". Run: kanta login --profile ${profile}`);
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
key: p.key,
|
|
56
|
+
baseUrl: baseUrl || p.base_url || DEFAULT_BASE_URL,
|
|
57
|
+
dbBaseUrl: resolveDbBaseUrl({ dbUrl, profileDbBaseUrl: p.db_base_url }),
|
|
58
|
+
source: `profile:${profile}`,
|
|
59
|
+
profile,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// 4. default profile
|
|
64
|
+
if (config.default_profile) {
|
|
65
|
+
const p = config.profiles[config.default_profile];
|
|
66
|
+
if (p && p.key) {
|
|
67
|
+
return {
|
|
68
|
+
key: p.key,
|
|
69
|
+
baseUrl: baseUrl || p.base_url || DEFAULT_BASE_URL,
|
|
70
|
+
dbBaseUrl: resolveDbBaseUrl({ dbUrl, profileDbBaseUrl: p.db_base_url }),
|
|
71
|
+
source: `profile:${config.default_profile}`,
|
|
72
|
+
profile: config.default_profile,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 5. nothing
|
|
78
|
+
throw new KantaAuthError('No Kanta credentials. Run: kanta login');
|
|
79
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
// KantaClient — the only module that knows the HTTP shape of api.kanta.dev.
|
|
2
|
+
// One method per endpoint. Returns parsed JSON or throws KantaApiError.
|
|
3
|
+
import { KantaApiError } from './errors.js';
|
|
4
|
+
|
|
5
|
+
const RETRYABLE = new Set([429, 503]);
|
|
6
|
+
|
|
7
|
+
export class KantaClient {
|
|
8
|
+
constructor({
|
|
9
|
+
key,
|
|
10
|
+
baseUrl = 'https://api.kanta.dev',
|
|
11
|
+
dbBaseUrl = 'https://database.kanta.dev/v1',
|
|
12
|
+
fetchImpl,
|
|
13
|
+
retryDelayMs = 2000,
|
|
14
|
+
} = {}) {
|
|
15
|
+
if (!key) throw new KantaApiError('No API key provided to KantaClient.', { status: null, code: 'missing_api_key' });
|
|
16
|
+
this.key = key;
|
|
17
|
+
this.baseUrl = baseUrl.replace(/\/+$/, '');
|
|
18
|
+
this.dbBaseUrl = (dbBaseUrl || 'https://database.kanta.dev/v1').replace(/\/+$/, '');
|
|
19
|
+
this._fetch = fetchImpl || globalThis.fetch;
|
|
20
|
+
this._retryDelayMs = retryDelayMs;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async _request(method, path, { body, query, retry = false } = {}) {
|
|
24
|
+
let url = `${this.baseUrl}${path}`;
|
|
25
|
+
if (query) {
|
|
26
|
+
const qs = new URLSearchParams(
|
|
27
|
+
Object.entries(query).filter(([, v]) => v !== undefined && v !== null),
|
|
28
|
+
).toString();
|
|
29
|
+
if (qs) url += `?${qs}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const init = {
|
|
33
|
+
method,
|
|
34
|
+
headers: {
|
|
35
|
+
'X-API-Key': this.key,
|
|
36
|
+
Accept: 'application/json',
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
if (body !== undefined) {
|
|
40
|
+
init.headers['Content-Type'] = 'application/json';
|
|
41
|
+
init.body = JSON.stringify(body);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let res;
|
|
45
|
+
try {
|
|
46
|
+
res = await this._fetch(url, init);
|
|
47
|
+
} catch (err) {
|
|
48
|
+
// network-level failure — surface raw so the CLI can map it
|
|
49
|
+
throw err;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (retry && RETRYABLE.has(res.status)) {
|
|
53
|
+
await new Promise(r => setTimeout(r, this._retryDelayMs));
|
|
54
|
+
return this._request(method, path, { body, query, retry: false });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const text = await res.text();
|
|
58
|
+
let payload = null;
|
|
59
|
+
if (text) {
|
|
60
|
+
try {
|
|
61
|
+
payload = JSON.parse(text);
|
|
62
|
+
} catch {
|
|
63
|
+
payload = { raw: text };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (!res.ok) {
|
|
68
|
+
const code = payload?.error || payload?.code || null;
|
|
69
|
+
const message = payload?.message || code || `HTTP ${res.status}`;
|
|
70
|
+
throw new KantaApiError(message, { status: res.status, code });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return payload;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---- customer endpoints ----
|
|
77
|
+
verifySingle(email) {
|
|
78
|
+
return this._request('POST', '/verify', { body: { email } });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
verifyBulk(emails, { filename, webhook } = {}) {
|
|
82
|
+
const body = { emails };
|
|
83
|
+
if (filename) body.filename = filename;
|
|
84
|
+
if (webhook) body.webhook = webhook;
|
|
85
|
+
return this._request('POST', '/verify/bulk', { body, retry: true });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Single find is synchronous on the API (POST /find/email): it returns the
|
|
89
|
+
// result inline — { email, confidence, method, pattern } or { email: null } —
|
|
90
|
+
// and only charges a credit on a hit. No job is created.
|
|
91
|
+
findSingle({ firstName, lastName, company } = {}) {
|
|
92
|
+
return this._request('POST', '/find/email', { body: { firstName, lastName, company } });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
findBulk(contacts, { filename } = {}) {
|
|
96
|
+
const body = { contacts };
|
|
97
|
+
if (filename) body.filename = filename;
|
|
98
|
+
return this._request('POST', '/find/bulk', { body, retry: true });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
listJobs({ status } = {}) {
|
|
102
|
+
return this._request('GET', '/jobs', { query: { status } });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
getJob(id) {
|
|
106
|
+
return this._request('GET', `/jobs/${encodeURIComponent(id)}`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
getJobResults(id) {
|
|
110
|
+
return this._request('GET', `/jobs/${encodeURIComponent(id)}/results`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
getJobBreakdown(id) {
|
|
114
|
+
return this._request('GET', `/jobs/${encodeURIComponent(id)}/breakdown`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
cancelJob(id) {
|
|
118
|
+
return this._request('POST', `/jobs/${encodeURIComponent(id)}/cancel`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
resumeJob(id) {
|
|
122
|
+
return this._request('POST', `/jobs/${encodeURIComponent(id)}/resume`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
deleteJob(id) {
|
|
126
|
+
return this._request('DELETE', `/jobs/${encodeURIComponent(id)}`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
getAccount() {
|
|
130
|
+
return this._request('GET', '/me');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
getCredits() {
|
|
134
|
+
return this._request('GET', '/credits');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
getMe() {
|
|
138
|
+
return this._request('GET', '/me');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---- admin endpoints ----
|
|
142
|
+
adminAddCredits({ email, userId, product, amount, reason, label } = {}) {
|
|
143
|
+
const body = { amount, product };
|
|
144
|
+
if (email) body.email = email;
|
|
145
|
+
if (userId) body.user_id = userId;
|
|
146
|
+
// `reason` is kept as an alias for backward compat; the API records it as
|
|
147
|
+
// the free-text ledger label (the ledger `reason` column is a fixed enum).
|
|
148
|
+
const note = label || reason;
|
|
149
|
+
if (note) body.label = note;
|
|
150
|
+
return this._request('POST', '/admin/credits/add', { body });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
adminListJobs({ status, user } = {}) {
|
|
154
|
+
return this._request('GET', '/admin/jobs', { query: { status, user } });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
adminGetUser({ email, userId } = {}) {
|
|
158
|
+
return this._request('GET', '/admin/user', { query: { email, user_id: userId } });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
adminVerify(email) {
|
|
162
|
+
return this._request('POST', '/admin/verify', { body: { email } });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
adminSuppressAdd(value) {
|
|
166
|
+
return this._request('POST', '/admin/suppress', { body: { value } });
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
adminSuppressCheck(email) {
|
|
170
|
+
return this._request('GET', '/admin/suppress/check', { query: { email } });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---- Kanta Database API (second base URL) ----
|
|
174
|
+
// Same API key, different host. Errors map to KantaApiError with any extra
|
|
175
|
+
// fields from the JSON body (e.g. `estimated_max`) preserved on `.extra`.
|
|
176
|
+
async _dbRequest(method, path, { body, retry = false, raw = false } = {}) {
|
|
177
|
+
const url = `${this.dbBaseUrl}${path}`;
|
|
178
|
+
const init = {
|
|
179
|
+
method,
|
|
180
|
+
headers: {
|
|
181
|
+
'X-API-Key': this.key,
|
|
182
|
+
Accept: raw ? 'text/csv, application/json' : 'application/json',
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
if (body !== undefined) {
|
|
186
|
+
init.headers['Content-Type'] = 'application/json';
|
|
187
|
+
init.body = JSON.stringify(body);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const res = await this._fetch(url, init);
|
|
191
|
+
|
|
192
|
+
if (retry && RETRYABLE.has(res.status)) {
|
|
193
|
+
await new Promise(r => setTimeout(r, this._retryDelayMs));
|
|
194
|
+
return this._dbRequest(method, path, { body, retry: false, raw });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const text = await res.text();
|
|
198
|
+
|
|
199
|
+
if (!res.ok) {
|
|
200
|
+
let payload = null;
|
|
201
|
+
if (text) {
|
|
202
|
+
try {
|
|
203
|
+
payload = JSON.parse(text);
|
|
204
|
+
} catch {
|
|
205
|
+
payload = { message: text };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const code = payload?.error || payload?.code || null;
|
|
209
|
+
const message = payload?.message || code || `HTTP ${res.status}`;
|
|
210
|
+
const extra = {};
|
|
211
|
+
if (payload && typeof payload === 'object') {
|
|
212
|
+
for (const [k, v] of Object.entries(payload)) {
|
|
213
|
+
if (k !== 'error' && k !== 'code' && k !== 'message') extra[k] = v;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
throw new KantaApiError(message, { status: res.status, code, extra });
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (raw) return text;
|
|
220
|
+
if (!text) return null;
|
|
221
|
+
try {
|
|
222
|
+
return JSON.parse(text);
|
|
223
|
+
} catch {
|
|
224
|
+
return { raw: text };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// people
|
|
229
|
+
dbSearch(filter, { limit, cursor } = {}) {
|
|
230
|
+
return this._dbRequest('POST', '/db/search', { body: { filter, limit, cursor }, retry: true });
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
dbCount(filter) {
|
|
234
|
+
return this._dbRequest('POST', '/db/count', { body: { filter }, retry: true });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
dbFacets(filter, fields) {
|
|
238
|
+
return this._dbRequest('POST', '/db/facets', { body: { filter, fields }, retry: true });
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
dbLookup(params) {
|
|
242
|
+
return this._dbRequest('POST', '/db/lookup', { body: params, retry: true });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
dbCaCount() {
|
|
246
|
+
return this._dbRequest('GET', '/db/ca-count', { retry: true });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// exports
|
|
250
|
+
dbExport(filter, max, confirmCredits) {
|
|
251
|
+
return this._dbRequest('POST', '/db/export', {
|
|
252
|
+
body: { filter, max, confirm_credits: confirmCredits },
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
listExports() {
|
|
257
|
+
return this._dbRequest('GET', '/db/exports', { retry: true });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
getExport(id) {
|
|
261
|
+
return this._dbRequest('GET', `/db/exports/${encodeURIComponent(id)}`, { retry: true });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
downloadExport(id) {
|
|
265
|
+
return this._dbRequest('GET', `/db/exports/${encodeURIComponent(id)}/download`, { raw: true, retry: true });
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// companies
|
|
269
|
+
companiesSearch(filter, { limit, cursor } = {}) {
|
|
270
|
+
return this._dbRequest('POST', '/db/companies/search', { body: { filter, limit, cursor }, retry: true });
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
companiesCount(filter) {
|
|
274
|
+
return this._dbRequest('POST', '/db/companies/count', { body: { filter }, retry: true });
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
companiesFacets(filter, fields) {
|
|
278
|
+
return this._dbRequest('POST', '/db/companies/facets', { body: { filter, fields }, retry: true });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
companiesExport(filter, max, confirmCredits) {
|
|
282
|
+
return this._dbRequest('POST', '/db/companies/export', {
|
|
283
|
+
body: { filter, max, confirm_credits: confirmCredits },
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
companyContacts(orgId, { limit, cursor } = {}) {
|
|
288
|
+
return this._dbRequest('POST', `/db/companies/${encodeURIComponent(orgId)}/contacts`, {
|
|
289
|
+
body: { limit, cursor },
|
|
290
|
+
retry: true,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Load/save ~/.kanta/config.json (mode 0600) and resolve profiles.
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import {
|
|
5
|
+
readFileSync,
|
|
6
|
+
writeFileSync,
|
|
7
|
+
existsSync,
|
|
8
|
+
mkdirSync,
|
|
9
|
+
chmodSync,
|
|
10
|
+
} from 'node:fs';
|
|
11
|
+
import { KantaConfigError } from './errors.js';
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_BASE_URL = 'https://api.kanta.dev';
|
|
14
|
+
export const DEFAULT_DB_BASE_URL = 'https://database.kanta.dev/v1';
|
|
15
|
+
|
|
16
|
+
export function configDir() {
|
|
17
|
+
return process.env.KANTA_CONFIG_DIR || join(homedir(), '.kanta');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function configPath() {
|
|
21
|
+
return join(configDir(), 'config.json');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const EMPTY = { default_profile: null, profiles: {} };
|
|
25
|
+
|
|
26
|
+
export function loadConfig() {
|
|
27
|
+
const path = configPath();
|
|
28
|
+
if (!existsSync(path)) return { ...EMPTY, profiles: {} };
|
|
29
|
+
let raw;
|
|
30
|
+
try {
|
|
31
|
+
raw = readFileSync(path, 'utf8');
|
|
32
|
+
} catch (err) {
|
|
33
|
+
throw new KantaConfigError(`Cannot read ${path}: ${err.message}`);
|
|
34
|
+
}
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = JSON.parse(raw);
|
|
38
|
+
} catch {
|
|
39
|
+
throw new KantaConfigError(`Config file ${path} is not valid JSON.`);
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
default_profile: parsed.default_profile ?? null,
|
|
43
|
+
profiles: parsed.profiles ?? {},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function saveConfig(config) {
|
|
48
|
+
const dir = configDir();
|
|
49
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
50
|
+
const path = configPath();
|
|
51
|
+
const body = JSON.stringify(
|
|
52
|
+
{
|
|
53
|
+
default_profile: config.default_profile ?? null,
|
|
54
|
+
profiles: config.profiles ?? {},
|
|
55
|
+
},
|
|
56
|
+
null,
|
|
57
|
+
2,
|
|
58
|
+
);
|
|
59
|
+
writeFileSync(path, body + '\n', { mode: 0o600 });
|
|
60
|
+
chmodSync(path, 0o600);
|
|
61
|
+
return path;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function setProfile(name, { key, base_url, db_base_url } = {}) {
|
|
65
|
+
const config = loadConfig();
|
|
66
|
+
config.profiles[name] = {
|
|
67
|
+
key,
|
|
68
|
+
base_url: base_url || DEFAULT_BASE_URL,
|
|
69
|
+
db_base_url: db_base_url || DEFAULT_DB_BASE_URL,
|
|
70
|
+
};
|
|
71
|
+
if (!config.default_profile) config.default_profile = name;
|
|
72
|
+
saveConfig(config);
|
|
73
|
+
return config;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function removeProfile(name) {
|
|
77
|
+
const config = loadConfig();
|
|
78
|
+
if (!config.profiles[name]) {
|
|
79
|
+
throw new KantaConfigError(`No profile named "${name}".`);
|
|
80
|
+
}
|
|
81
|
+
delete config.profiles[name];
|
|
82
|
+
if (config.default_profile === name) {
|
|
83
|
+
config.default_profile = Object.keys(config.profiles)[0] ?? null;
|
|
84
|
+
}
|
|
85
|
+
saveConfig(config);
|
|
86
|
+
return config;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function maskKey(key) {
|
|
90
|
+
if (!key || typeof key !== 'string') return '(none)';
|
|
91
|
+
if (key.length <= 10) return '****';
|
|
92
|
+
return `${key.slice(0, 6)}…${key.slice(-4)}`;
|
|
93
|
+
}
|