desearch-mcp-server 0.5.0 → 0.7.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.
@@ -0,0 +1,433 @@
1
+ import { createDesearchApi, withQuery } from "./desearch-api.js";
2
+ import { PEOPLE_API_BASE_URL, PEOPLE_ENDED_STATUSES, PEOPLE_TASK_STATUSES, arrayOf, compact, numberOf, objectOf, stringOf, unverifiedCriteria, } from "./people.js";
3
+ /**
4
+ * Company Search and Company Enrich on the Desearch API (`/desearch/companies/*`).
5
+ *
6
+ * desearch-js 1.5 has no Company Search methods, so this module calls the routes
7
+ * directly through `desearch-api.ts`, with the same base URL, `Authorization: <key>`
8
+ * header, and `HTTP <status>: <detail>` error text as People Search (people.ts).
9
+ *
10
+ * - `POST /desearch/companies/search` finds companies from a description and
11
+ * `POST /desearch/companies/enrich` reads the domains you send. Both are billed:
12
+ * they reserve companies at the route price and settle to what they deliver.
13
+ * - Every other route (tasks, results, pause/resume/cancel) is free. Both kinds of task
14
+ * run on the People Search engine, but a People Search task_id is a 404 on these
15
+ * routes and a company task_id is a 404 on People Search's.
16
+ *
17
+ * A company is published once the stages its request needs have run
18
+ * (`enrichment.status: "partial"`); later stages (contacts, people, email_patterns,
19
+ * email_check) fill it in place until it is `complete`. A results cursor returns only
20
+ * companies delivered after it; reading without a cursor returns every company in its
21
+ * latest version.
22
+ */
23
+ /** Statuses are People Search's (desearch-public-api model/people.py TaskStatus). */
24
+ export const COMPANY_TASK_STATUSES = PEOPLE_TASK_STATUSES;
25
+ /** `roles` (desearch-public-api model/companies.py Role). */
26
+ export const COMPANY_ROLES = [
27
+ "ceo",
28
+ "founder",
29
+ "cto",
30
+ "cfo",
31
+ "coo",
32
+ "cmo",
33
+ "president",
34
+ "owner",
35
+ "managing_director",
36
+ ];
37
+ /** `filters.require` (model/companies.py Requirement). */
38
+ export const COMPANY_REQUIREMENTS = ["email", "phone", "linkedin", "leader", "leader_email"];
39
+ /** `type` on `GET /desearch/companies/tasks` (routers/companies.py TYPE_SERVICES). */
40
+ export const COMPANY_TASK_TYPES = ["search", "enrich"];
41
+ /** Request limits (model/companies.py, model/people.py). */
42
+ export const COMPANY_DOMAINS_MAX = 200;
43
+ export const COMPANY_COUNTRIES_MAX = 20;
44
+ export const COMPANY_EXCLUDE_MAX = 1000;
45
+ export function createCompanyClient(apiKey, baseUrl = PEOPLE_API_BASE_URL) {
46
+ return companyClientFor(createDesearchApi(apiKey, baseUrl));
47
+ }
48
+ /** A Company Search client on an existing API caller, so the server shares one per key. */
49
+ export function companyClientFor(call) {
50
+ const taskPath = (taskId) => `/desearch/companies/tasks/${encodeURIComponent(taskId)}`;
51
+ const start = (path, body, idempotencyKey) => call("POST", path, {
52
+ body,
53
+ headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined,
54
+ });
55
+ return {
56
+ startSearch(body, idempotencyKey) {
57
+ return start("/desearch/companies/search", body, idempotencyKey);
58
+ },
59
+ startEnrich(body, idempotencyKey) {
60
+ return start("/desearch/companies/enrich", body, idempotencyKey);
61
+ },
62
+ async getTask(taskId) {
63
+ return (await call("GET", taskPath(taskId))).data;
64
+ },
65
+ async getResults(taskId, params) {
66
+ return (await call("GET", withQuery(`${taskPath(taskId)}/results`, params))).data;
67
+ },
68
+ async controlTask(taskId, action) {
69
+ return (await call("POST", `${taskPath(taskId)}/${action}`)).data;
70
+ },
71
+ async listTasks(params) {
72
+ return (await call("GET", withQuery("/desearch/companies/tasks", params))).data;
73
+ },
74
+ };
75
+ }
76
+ /** `roles`, `infer_emails`, and `verify_emails`, only when the caller set them. */
77
+ function leaderFields(args, body) {
78
+ if (args.roles !== undefined)
79
+ body.roles = args.roles;
80
+ if (args.infer_emails !== undefined)
81
+ body.infer_emails = args.infer_emails;
82
+ if (args.verify_emails !== undefined)
83
+ body.verify_emails = args.verify_emails;
84
+ }
85
+ /** `metadata`, left out when empty. */
86
+ function metadataField(args, body) {
87
+ if (args.metadata !== undefined && Object.keys(args.metadata).length > 0)
88
+ body.metadata = args.metadata;
89
+ return body;
90
+ }
91
+ /**
92
+ * Request body for `POST /desearch/companies/search` (model/companies.py CompanySearchRequest).
93
+ * The tool takes `countries` and `require` as top-level arguments; they go in `filters`.
94
+ */
95
+ export function companySearchBody(args) {
96
+ const body = { query: args.query };
97
+ if (args.count !== undefined)
98
+ body.count = args.count;
99
+ if (args.min_score !== undefined)
100
+ body.min_score = args.min_score;
101
+ if (args.exclude !== undefined)
102
+ body.exclude = args.exclude;
103
+ leaderFields(args, body);
104
+ const filters = {};
105
+ if (args.countries !== undefined)
106
+ filters.countries = args.countries;
107
+ if (args.require !== undefined)
108
+ filters.require = args.require;
109
+ if (Object.keys(filters).length > 0)
110
+ body.filters = filters;
111
+ return metadataField(args, body);
112
+ }
113
+ /** Request body for `POST /desearch/companies/enrich` (model/companies.py CompanyEnrichRequest). */
114
+ export function companyEnrichBody(args) {
115
+ const body = { domains: args.domains };
116
+ leaderFields(args, body);
117
+ return metadataField(args, body);
118
+ }
119
+ const MAX_DESCRIPTION_CHARS = 300;
120
+ const MAX_REASONS = 3;
121
+ function truncated(value, max) {
122
+ const text = stringOf(value);
123
+ return text && text.length > max ? `${text.slice(0, max - 3)}...` : text;
124
+ }
125
+ function strings(value) {
126
+ return arrayOf(value).filter((item) => typeof item === "string" && item !== "");
127
+ }
128
+ /**
129
+ * One email: the address, what kind it is, where it came from (`source`, `source_url`),
130
+ * the inference details (`confidence`, `pattern`) and `verification` (the check's status:
131
+ * valid, invalid, risky, or unknown; left out until the email checks ran).
132
+ */
133
+ function compactEmail(value, withPerson = true) {
134
+ const e = objectOf(value);
135
+ return compact({
136
+ value: stringOf(e.value),
137
+ type: e.type,
138
+ source: e.source,
139
+ source_url: stringOf(e.source_url),
140
+ person: withPerson ? stringOf(e.person) : undefined,
141
+ confidence: e.confidence,
142
+ pattern: stringOf(e.pattern),
143
+ verification: stringOf(objectOf(e.verification).status),
144
+ });
145
+ }
146
+ function compactEmails(value, withPerson = true) {
147
+ return arrayOf(value)
148
+ .map((email) => compactEmail(email, withPerson))
149
+ .filter((email) => email.value !== undefined);
150
+ }
151
+ function compactPhones(value) {
152
+ return arrayOf(value)
153
+ .map(objectOf)
154
+ .filter((phone) => stringOf(phone.value))
155
+ .map((phone) => compact({ value: phone.value, type: phone.type, source_url: stringOf(phone.source_url) }));
156
+ }
157
+ function compactSocials(value) {
158
+ return arrayOf(value)
159
+ .map(objectOf)
160
+ .filter((social) => stringOf(social.url))
161
+ .map((social) => compact({ type: social.type, url: social.url, source_url: stringOf(social.source_url) }));
162
+ }
163
+ /** One leader: who, which of the request's roles, where the role is shown, and how to reach them. */
164
+ function compactLeader(value) {
165
+ const p = objectOf(value);
166
+ return compact({
167
+ name: stringOf(p.name),
168
+ title: stringOf(p.title),
169
+ roles: strings(p.roles),
170
+ verified: typeof p.verified === "boolean" ? p.verified : undefined,
171
+ linkedin_url: stringOf(p.linkedin_url),
172
+ x_url: stringOf(p.x_url),
173
+ github_url: stringOf(p.github_url),
174
+ emails: compactEmails(p.emails, false),
175
+ phones: compactPhones(p.phones),
176
+ evidence_url: stringOf(objectOf(p.evidence).source_url),
177
+ });
178
+ }
179
+ function compactEnrichment(value) {
180
+ const e = objectOf(value);
181
+ const stages = objectOf(e.stages);
182
+ return compact({
183
+ status: stringOf(e.status),
184
+ stages: compact(stages),
185
+ errors: arrayOf(e.errors)
186
+ .map(objectOf)
187
+ .map((error) => compact({ stage: stringOf(error.stage), message: stringOf(error.message) }))
188
+ .filter((error) => Object.keys(error).length > 0),
189
+ });
190
+ }
191
+ /**
192
+ * One company as an agent needs it: what it is, how well it fits (Company Search; `score`
193
+ * is null for Company Enrich), how to reach it and its leaders, with the page each contact
194
+ * came from, and how far its enrichment has got.
195
+ */
196
+ export function compactCompany(company) {
197
+ const c = objectOf(company);
198
+ const location = objectOf(c.location);
199
+ const score = objectOf(c.score);
200
+ const contact = objectOf(c.primary_contact);
201
+ const primaryEmail = compactEmail(c.primary_email);
202
+ return {
203
+ ...compact({
204
+ domain: stringOf(c.domain) ?? stringOf(c.handle),
205
+ name: stringOf(c.name),
206
+ url: stringOf(c.url),
207
+ industry: stringOf(c.industry),
208
+ location: compact({
209
+ country: stringOf(location.country),
210
+ city: stringOf(location.city),
211
+ address: stringOf(location.address),
212
+ }),
213
+ description: truncated(c.description, MAX_DESCRIPTION_CHARS),
214
+ }),
215
+ // Always present: a number for Company Search, null for Company Enrich (no fit score).
216
+ score: numberOf(score.value) ?? null,
217
+ ...compact({
218
+ why: stringOf(score.summary),
219
+ reasons: strings(score.reasons).slice(0, MAX_REASONS),
220
+ fully_verified: typeof score.fully_verified === "boolean" ? score.fully_verified : undefined,
221
+ unverified_criteria: unverifiedCriteria(score),
222
+ primary_email: primaryEmail.value !== undefined ? primaryEmail : undefined,
223
+ primary_contact: compact({
224
+ name: stringOf(contact.name),
225
+ title: stringOf(contact.title),
226
+ email: stringOf(contact.email),
227
+ linkedin_url: stringOf(contact.linkedin_url),
228
+ reason: stringOf(contact.reason),
229
+ }),
230
+ contact_coverage: compact(objectOf(c.contact_coverage)),
231
+ emails: compactEmails(c.emails),
232
+ phones: compactPhones(c.phones),
233
+ socials: compactSocials(c.socials),
234
+ leaders: arrayOf(c.people)
235
+ .map(compactLeader)
236
+ .filter((leader) => leader.name !== undefined),
237
+ enrichment: compactEnrichment(c.enrichment),
238
+ }),
239
+ };
240
+ }
241
+ /** Company task warnings are short (`code`, `message`), so both are kept. */
242
+ function compactWarning(warning) {
243
+ const w = objectOf(warning);
244
+ return compact({ code: stringOf(w.code), message: stringOf(w.message) });
245
+ }
246
+ /**
247
+ * Task fields an agent polls on. `progress` is the worker's counters, passed through
248
+ * without its copy of `warnings` (listed once, at the top). `completion_reason` appears
249
+ * once the task has ended, `coverage_limited` only when true.
250
+ */
251
+ export function compactCompanyTask(task, options = {}) {
252
+ const t = objectOf(task);
253
+ const status = typeof t.status === "string" ? t.status : undefined;
254
+ let progress;
255
+ if (options.progress) {
256
+ const { warnings: _warnings, ...rest } = objectOf(t.progress);
257
+ progress = rest;
258
+ }
259
+ return compact({
260
+ task_id: t.task_id,
261
+ search_type: t.search_type,
262
+ status,
263
+ stage: t.stage,
264
+ done: status ? PEOPLE_ENDED_STATUSES.has(status) : undefined,
265
+ query: t.query,
266
+ metadata: t.metadata,
267
+ count: t.count,
268
+ result_count: t.result_count,
269
+ completion_reason: stringOf(t.completion_reason),
270
+ coverage_limited: t.coverage_limited === true ? true : undefined,
271
+ warnings: arrayOf(t.warnings).map(compactWarning),
272
+ progress,
273
+ errors: options.progress ? t.errors : undefined,
274
+ reserved_cost_usd: t.reserved_cost_usd,
275
+ final_cost_usd: t.final_cost_usd,
276
+ refunded_usd: t.refunded_usd,
277
+ created_at: t.created_at,
278
+ finished_at: t.finished_at,
279
+ results_expire_at: t.results_expire_at,
280
+ });
281
+ }
282
+ const LATEST = "call company-search-status without cursor to read every company in its latest version";
283
+ /**
284
+ * One sentence (or two) on what to do next, so an agent does not have to infer it from the status.
285
+ * `nextCursor` is the results cursor when the caller just read a page of companies.
286
+ * `task` adds the stage (`enriching`) and why an ended task stopped.
287
+ * `page.partial` counts the companies on this page whose enrichment is still `partial`;
288
+ * `page.readAfterStart` is true when the caller passed a cursor, so it may hold older
289
+ * versions of companies it read before.
290
+ */
291
+ export function companyNextStep(status, nextCursor, hasMore = false, task = {}, page = {}) {
292
+ const again = nextCursor === undefined
293
+ ? "company-search-status again"
294
+ : `company-search-status again with cursor "${nextCursor}"`;
295
+ const partial = page.partial ?? 0;
296
+ if (hasMore) {
297
+ return `More companies are ready now: call ${again}.`;
298
+ }
299
+ const ended = (first) => {
300
+ const notes = [first];
301
+ if (partial > 0) {
302
+ notes.push(`${partial === 1 ? "1 company" : `${partial} companies`} on this page stayed partial: the task ended before every stage ran for ${partial === 1 ? "it" : "them"}.`);
303
+ }
304
+ if (page.readAfterStart) {
305
+ notes.push("If you read companies while it ran, call company-search-status without cursor to read every company in its final version.");
306
+ }
307
+ return notes.join(" ");
308
+ };
309
+ switch (status) {
310
+ case "queued":
311
+ case "running": {
312
+ if (task.stage === "enriching") {
313
+ return `Every company is delivered; later stages (leaders, inferred emails, email checks) are still filling some in. Wait 15 to 30 seconds, then ${LATEST}.`;
314
+ }
315
+ const wait = nextCursor === undefined
316
+ ? `Still running. Wait 15 to 30 seconds, then call ${again}.`
317
+ : `Still running. Wait 15 to 30 seconds, then call ${again} to get only the companies delivered since this call.`;
318
+ return partial > 0 || page.readAfterStart
319
+ ? `${wait} Companies with enrichment status "partial" are still being filled in; when the task is done, ${LATEST}.`
320
+ : wait;
321
+ }
322
+ case "pausing":
323
+ return "Pausing after the current batch. Resume it with company-search-resume.";
324
+ case "paused":
325
+ return "Paused. Resume it with company-search-resume, or cancel it with company-search-cancel.";
326
+ case "cancelling":
327
+ return "Cancelling. Call company-search-status again to read the final status.";
328
+ case "completed":
329
+ if (task.coverage_limited === true) {
330
+ const wanted = typeof task.count === "number" ? `${task.count} companies` : "the count you asked for";
331
+ return ended(`Finished early: a budget stopped it (${String(task.completion_reason)}) before it delivered ${wanted}, so more companies may match. You have every company it delivered.`);
332
+ }
333
+ if (task.completion_reason === "no_candidates") {
334
+ return "Finished: its searches found no company to check. Try a broader description.";
335
+ }
336
+ if (task.completion_reason === "zero_qualified") {
337
+ return "Finished: it checked the companies its searches found and none fit. Try a broader description, a lower min_score, or fewer require values.";
338
+ }
339
+ if (task.completion_reason === "all_domains_processed") {
340
+ return ended("Finished: it read every domain. You have every company it delivered.");
341
+ }
342
+ return ended("Finished. You have every company this task delivered.");
343
+ case "partial":
344
+ return ended("Finished with partial results: some searches failed. You have every company it delivered.");
345
+ case "failed":
346
+ return "The task failed. See errors. A task that delivers no companies is not charged.";
347
+ case "cancelled":
348
+ return ended("Cancelled. You pay only for the companies it delivered; the rest of the reservation is returned.");
349
+ case "expired":
350
+ return "Results expired 30 days after the task ended.";
351
+ default:
352
+ return `Call ${again} to check for changes.`;
353
+ }
354
+ }
355
+ const POLL_HINT = "The task runs in the background. Poll company-search-status with this task_id every 15 to 30 seconds: companies appear while it runs, and later stages fill them in.";
356
+ async function startCompanyTask(start, body, idempotencyKey) {
357
+ const { status, data } = await start(body, idempotencyKey);
358
+ const raw = objectOf(data);
359
+ // 200 means the same Idempotency-Key already created this task; the API does not charge again.
360
+ const existing = status === 200;
361
+ return compact({
362
+ ...compactCompanyTask(data),
363
+ cost_usd: numberOf(raw.cost_usd),
364
+ currency: stringOf(raw.currency),
365
+ existing_task: existing ? true : undefined,
366
+ next: existing
367
+ ? `This idempotency_key already started this task, so it was not charged again. ${POLL_HINT}`
368
+ : POLL_HINT,
369
+ });
370
+ }
371
+ /** `company-search`: start a billed background Company Search and return the task to poll. */
372
+ export async function startCompanySearch(client, args) {
373
+ return startCompanyTask((body, key) => client.startSearch(body, key), companySearchBody(args), args.idempotency_key);
374
+ }
375
+ /** `company-enrich`: start a billed background Company Enrich and return the task to poll. */
376
+ export async function startCompanyEnrich(client, args) {
377
+ return startCompanyTask((body, key) => client.startEnrich(body, key), companyEnrichBody(args), args.idempotency_key);
378
+ }
379
+ /** `company-search-status`: task status and progress, plus a page of companies when there are any. */
380
+ export async function readCompanyStatus(client, args) {
381
+ const task = await client.getTask(args.task_id);
382
+ const summary = compactCompanyTask(task, { progress: true });
383
+ const status = typeof summary.status === "string" ? summary.status : undefined;
384
+ if (args.include_companies === false) {
385
+ return { ...summary, next: companyNextStep(status, undefined, false, summary) };
386
+ }
387
+ let nextCursor = args.cursor ?? "0";
388
+ let hasMore = false;
389
+ let partial = 0;
390
+ let companies = [];
391
+ const resultCount = numberOf(summary.result_count) ?? 0;
392
+ // No results yet, or expired (the results route answers 410): skip the second call.
393
+ if (resultCount > 0 && status !== "expired") {
394
+ const page = objectOf(await client.getResults(args.task_id, { cursor: args.cursor, limit: args.limit }));
395
+ const rows = arrayOf(page.results);
396
+ companies = rows.map(compactCompany);
397
+ partial = rows.filter((row) => objectOf(objectOf(row).enrichment).status === "partial").length;
398
+ nextCursor = stringOf(page.next_cursor) ?? nextCursor;
399
+ hasMore = page.has_more === true;
400
+ }
401
+ const readAfterStart = args.cursor !== undefined && args.cursor !== "0";
402
+ return {
403
+ ...summary,
404
+ companies,
405
+ next_cursor: nextCursor,
406
+ has_more: hasMore,
407
+ next: companyNextStep(status, nextCursor, hasMore, summary, { partial, readAfterStart }),
408
+ };
409
+ }
410
+ /** `company-search-pause`, `company-search-resume`, `company-search-cancel`: change a task's state. */
411
+ export async function controlCompanyTask(client, args) {
412
+ const task = compactCompanyTask(await client.controlTask(args.task_id, args.action));
413
+ const status = typeof task.status === "string" ? task.status : undefined;
414
+ return { ...task, next: companyNextStep(status, undefined, false, task) };
415
+ }
416
+ /** `company-search-tasks`: the caller's Company Search and Company Enrich tasks, newest first. */
417
+ export async function listCompanyTasks(client, args) {
418
+ const params = {
419
+ type: args.type,
420
+ status: args.status?.length ? args.status.join(",") : undefined,
421
+ limit: args.limit,
422
+ cursor: args.cursor,
423
+ };
424
+ // The API reads metadata filters as `metadata.<key>=<value>`, one parameter per pair.
425
+ for (const [key, value] of Object.entries(args.metadata ?? {})) {
426
+ params[`metadata.${key}`] = value;
427
+ }
428
+ const page = objectOf(await client.listTasks(params));
429
+ return {
430
+ tasks: arrayOf(page.tasks).map((task) => compactCompanyTask(task)),
431
+ next_cursor: stringOf(page.next_cursor) ?? null,
432
+ };
433
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Direct calls to the Desearch API for routes desearch-js 1.5 does not cover
3
+ * (People Search, the TikTok, Facebook and Instagram routes, `POST /search`).
4
+ *
5
+ * Same base URL, `Authorization: <key>` header, and `HTTP <status>: <detail>`
6
+ * error text that desearch-js uses, so every tool reports API errors the same way.
7
+ */
8
+ export declare const DESEARCH_API_BASE_URL = "https://api.desearch.ai";
9
+ export type QueryValue = string | number | boolean | undefined;
10
+ export interface ApiResponse {
11
+ status: number;
12
+ /** Parsed JSON body, or the body text when it is not JSON. */
13
+ data: unknown;
14
+ /** The body exactly as sent, for CSV and JSON Lines downloads. */
15
+ text: string;
16
+ headers: {
17
+ get(name: string): string | null;
18
+ };
19
+ }
20
+ export interface ApiRequestOptions {
21
+ query?: Record<string, QueryValue>;
22
+ body?: Record<string, unknown>;
23
+ headers?: Record<string, string>;
24
+ }
25
+ export type DesearchApi = (method: "GET" | "POST", path: string, options?: ApiRequestOptions) => Promise<ApiResponse>;
26
+ /** The API's `detail` (plus the task status People Search adds on a 409), or the start of the body. */
27
+ export declare function errorDetail(data: unknown, text: string): string;
28
+ /** `path?key=value`, leaving out undefined values. */
29
+ export declare function withQuery(path: string, params: Record<string, QueryValue>): string;
30
+ export declare function createDesearchApi(apiKey: string, baseUrl?: string): DesearchApi;
31
+ //# sourceMappingURL=desearch-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"desearch-api.d.ts","sourceRoot":"","sources":["../desearch-api.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AAEH,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;AAE/D,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC;AAE/D,MAAM,WAAW,WAAW;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,8DAA8D;IAC9D,IAAI,EAAE,OAAO,CAAC;IACd,kEAAkE;IAClE,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE;QAAE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;CACjD;AAED,MAAM,WAAW,iBAAiB;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACpC;AAED,MAAM,MAAM,WAAW,GAAG,CACtB,MAAM,EAAE,KAAK,GAAG,MAAM,EACtB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,iBAAiB,KAC1B,OAAO,CAAC,WAAW,CAAC,CAAC;AAM1B,uGAAuG;AACvG,wBAAgB,WAAW,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAO/D;AAED,sDAAsD;AACtD,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,MAAM,CASlF;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,MAA8B,GAAG,WAAW,CAgCtG"}
@@ -0,0 +1,67 @@
1
+ import { fetch } from "undici";
2
+ /**
3
+ * Direct calls to the Desearch API for routes desearch-js 1.5 does not cover
4
+ * (People Search, the TikTok, Facebook and Instagram routes, `POST /search`).
5
+ *
6
+ * Same base URL, `Authorization: <key>` header, and `HTTP <status>: <detail>`
7
+ * error text that desearch-js uses, so every tool reports API errors the same way.
8
+ */
9
+ export const DESEARCH_API_BASE_URL = "https://api.desearch.ai";
10
+ function isPlainObject(value) {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+ /** The API's `detail` (plus the task status People Search adds on a 409), or the start of the body. */
14
+ export function errorDetail(data, text) {
15
+ if (isPlainObject(data) && data.detail !== undefined) {
16
+ const detail = typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail);
17
+ const task = isPlainObject(data.task) ? data.task : undefined;
18
+ return typeof task?.status === "string" ? `${detail} Task status: ${task.status}.` : detail;
19
+ }
20
+ return text.length > 500 ? `${text.slice(0, 500)}...` : text;
21
+ }
22
+ /** `path?key=value`, leaving out undefined values. */
23
+ export function withQuery(path, params) {
24
+ const search = new URLSearchParams();
25
+ for (const [key, value] of Object.entries(params)) {
26
+ if (value !== undefined) {
27
+ search.append(key, String(value));
28
+ }
29
+ }
30
+ const qs = search.toString();
31
+ return qs ? `${path}?${qs}` : path;
32
+ }
33
+ export function createDesearchApi(apiKey, baseUrl = DESEARCH_API_BASE_URL) {
34
+ return async (method, path, options = {}) => {
35
+ const headers = { Authorization: apiKey, ...options.headers };
36
+ if (options.body) {
37
+ headers["Content-Type"] = "application/json";
38
+ }
39
+ const url = `${baseUrl}${options.query ? withQuery(path, options.query) : path}`;
40
+ let response;
41
+ let text;
42
+ try {
43
+ response = await fetch(url, {
44
+ method,
45
+ headers,
46
+ body: options.body ? JSON.stringify(options.body) : undefined,
47
+ });
48
+ text = await response.text();
49
+ }
50
+ catch (error) {
51
+ throw new Error(`Unexpected Error: ${error instanceof Error ? error.message : String(error)}`);
52
+ }
53
+ let data = text;
54
+ if (text) {
55
+ try {
56
+ data = JSON.parse(text);
57
+ }
58
+ catch {
59
+ // Not JSON: keep the text.
60
+ }
61
+ }
62
+ if (!response.ok) {
63
+ throw new Error(`HTTP ${response.status}: ${errorDetail(data, text)}`);
64
+ }
65
+ return { status: response.status, data, text, headers: response.headers };
66
+ };
67
+ }
package/build/people.d.ts CHANGED
@@ -1,13 +1,14 @@
1
+ import { type DesearchApi, type QueryValue } from "./desearch-api.js";
1
2
  /**
2
3
  * People Search on the Desearch API (`/desearch/people/*`).
3
4
  *
4
5
  * desearch-js 1.5 has no People Search methods, so this module calls the routes
5
- * directly with the same base URL, `Authorization: <key>` header, and
6
- * `HTTP <status>: <detail>` error text that desearch-js uses.
6
+ * directly through `desearch-api.ts`, with the same base URL, `Authorization: <key>`
7
+ * header, and `HTTP <status>: <detail>` error text that desearch-js uses.
7
8
  *
8
9
  * - `POST /desearch/people/search/{platform}` starts a background search and is billed:
9
10
  * it reserves `count` people at the route price and settles to what it delivers.
10
- * - Every other route (tasks, results, pause/resume/cancel, profiles) is free.
11
+ * - Every other route (tasks, results, pause/resume/cancel, profiles, exports) is free.
11
12
  */
12
13
  export declare const PEOPLE_API_BASE_URL = "https://api.desearch.ai";
13
14
  export declare const PEOPLE_PLATFORMS: readonly ["x", "youtube", "linkedin", "tiktok"];
@@ -63,7 +64,8 @@ export interface PeopleApiResponse {
63
64
  status: number;
64
65
  data: unknown;
65
66
  }
66
- type QueryValue = string | number | boolean | undefined;
67
+ export declare const PEOPLE_EXPORT_FORMATS: readonly ["csv", "jsonl"];
68
+ export type PeopleExportFormat = (typeof PEOPLE_EXPORT_FORMATS)[number];
67
69
  export interface PeopleClient {
68
70
  startSearch(platform: PeoplePlatform, body: Record<string, unknown>, idempotencyKey?: string): Promise<PeopleApiResponse>;
69
71
  getTask(taskId: string): Promise<unknown>;
@@ -74,13 +76,24 @@ export interface PeopleClient {
74
76
  controlTask(taskId: string, action: PeopleControlAction): Promise<unknown>;
75
77
  listTasks(params: Record<string, QueryValue>): Promise<unknown>;
76
78
  listProfiles(params: Record<string, QueryValue>): Promise<unknown>;
79
+ /** `GET /desearch/people/tasks/{task_id}/export`: the file body as text. */
80
+ exportTask(taskId: string, params: Record<string, QueryValue>): Promise<string>;
81
+ /** `GET /desearch/people/profiles/export`: the file body as text. */
82
+ exportProfiles(params: Record<string, QueryValue>): Promise<string>;
77
83
  }
78
84
  export declare function createPeopleClient(apiKey: string, baseUrl?: string): PeopleClient;
85
+ /** A People Search client on an existing API caller, so the server shares one per key. */
86
+ export declare function peopleClientFor(call: DesearchApi): PeopleClient;
79
87
  /**
80
88
  * Request body for `POST /desearch/people/search/{platform}`.
81
89
  * Throws when a filter does not apply to the platform, so no billed call is made.
82
90
  */
83
91
  export declare function peopleSearchBody(args: PeopleSearchArgs): Record<string, unknown>;
92
+ export declare function compact(fields: Record<string, unknown>): Record<string, unknown>;
93
+ export declare function objectOf(value: unknown): Record<string, unknown>;
94
+ export declare function arrayOf(value: unknown): unknown[];
95
+ export declare function numberOf(value: unknown): number | undefined;
96
+ export declare function stringOf(value: unknown): string | undefined;
84
97
  /**
85
98
  * The criteria a person's own profile and posts do not confirm, as short strings:
86
99
  * a criterion that is not met ("(unknown)" or "(not met)"), or a disqualifier that
@@ -146,5 +159,56 @@ export interface PeopleProfilesArgs {
146
159
  }
147
160
  /** `people-profiles`: everyone the caller's searches found on one platform. */
148
161
  export declare function listPeopleProfiles(client: PeopleClient, args: PeopleProfilesArgs): Promise<Record<string, unknown>>;
149
- export {};
162
+ /** Rows `people-search-export` returns when the caller does not set `max_rows`. */
163
+ export declare const PEOPLE_EXPORT_DEFAULT_ROWS = 100;
164
+ export declare const PEOPLE_EXPORT_MAX_ROWS = 1000;
165
+ /** Most characters of file text one reply carries; whole rows only. */
166
+ export declare const PEOPLE_EXPORT_MAX_CHARS = 50000;
167
+ export interface PeopleExportArgs {
168
+ task_id?: string;
169
+ platform?: PeoplePlatform;
170
+ format?: PeopleExportFormat;
171
+ q?: string;
172
+ sort?: (typeof PEOPLE_PROFILE_SORTS)[number];
173
+ has?: string[];
174
+ min_audience?: number;
175
+ max_audience?: number;
176
+ min_score?: number;
177
+ location?: string;
178
+ verified?: boolean;
179
+ max_rows?: number;
180
+ }
181
+ export interface PeopleExportResult {
182
+ /** One sentence: what was exported, how many rows, and how many were cut. */
183
+ note: string;
184
+ /** The file text up to the last row kept, byte for byte (CSV keeps its header). */
185
+ text: string;
186
+ total_rows: number;
187
+ returned_rows: number;
188
+ cut_rows: number;
189
+ }
190
+ /**
191
+ * End offset (after the line break) of each non-blank record. CSV fields in quotes
192
+ * may hold line breaks, so a CSV line break only ends a record outside quotes; a
193
+ * doubled quote inside a field toggles twice and changes nothing. JSON Lines escape
194
+ * line breaks, so every line is a record.
195
+ */
196
+ export declare function exportRecordEnds(text: string, format: PeopleExportFormat): number[];
197
+ /**
198
+ * Keep the CSV header and at most `maxRows` whole rows that fit in `maxChars`.
199
+ * The kept text is a prefix of the file, so it parses the same way the file does.
200
+ */
201
+ export declare function truncateExport(text: string, format: PeopleExportFormat, maxRows: number, maxChars?: number): {
202
+ text: string;
203
+ total_rows: number;
204
+ returned_rows: number;
205
+ cut_rows: number;
206
+ char_limited: boolean;
207
+ };
208
+ /**
209
+ * `people-search-export`: one search's people (`task_id`) or everyone the caller's
210
+ * searches found on a platform (`platform`), as CSV or JSON Lines text cut to
211
+ * `max_rows` rows and PEOPLE_EXPORT_MAX_CHARS characters.
212
+ */
213
+ export declare function exportPeople(client: PeopleClient, args: PeopleExportArgs): Promise<PeopleExportResult>;
150
214
  //# sourceMappingURL=people.d.ts.map