npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

desearch-js

v1.15.1

Published

Desearch SDK for the Node.js

Readme

desearch.js

Official JavaScript and TypeScript SDK for the Desearch public API.

This repo publishes the npm package desearch-js. In the current source tree, the package version is 1.15.0.

Related docs:

Package purpose

desearch.js is a thin, Node-oriented SDK for the Desearch API. It wraps the public read-side endpoints implemented in src/index.ts behind one Desearch client class and ships a typed surface from src/types.ts.

What it covers today:

  • Search: web search on the Desearch index, with an optional short answer with numbered citations
  • AI Search: X posts and web with an optional AI summary
  • AI X-links search
  • AI web-links search (deprecated; use search)
  • SERP web search
  • X search and lookup endpoints
  • TikTok, Facebook and Instagram search, profiles, posts, comments and hashtags
  • YouTube search, videos, transcripts, comments and channels; Reddit search, subreddits, posts and comment trees; Threads search, profiles and posts
  • page extraction
  • People Search: X, YouTube, LinkedIn and TikTok searches that run as background tasks
  • Company Search and Company Enrich: companies with their public emails, phones, social profiles and leaders, also as background tasks
  • Monitors: searches over web, X, Reddit, YouTube, Threads, TikTok and the Meta Ad Library, or watched accounts (Instagram and Facebook pages too), that run on a schedule and keep only what is new, with a webhook signature check
  • public network stats, including a live Server-Sent Events stream

What it does not try to be:

  • a browser-first SDK
  • a configurable transport layer
  • a general write or mutation client (People Search tasks, company tasks and monitors are the only things it creates or changes)
  • a framework with retries or runtime validation (People Search and Company Search add small polling helpers and result iterators)

Quick Start

Install

npm install desearch-js

Requires Node.js ≥ 20.18.1

ESM usage

Desearch is both the default export and a named export.

import Desearch from 'desearch-js';
// or: import { Desearch } from 'desearch-js';

const client = new Desearch(process.env.DESEARCH_API_KEY!);

const { results, summary } = await client.search({
  query: 'Who won the 2024 Nobel Prize in Physics?',
  summary: true,
});

console.log(summary?.text);
for (const result of results) {
  console.log(result.title, result.url);
}

CommonJS usage

const { Desearch } = require('desearch-js');
// or: const Desearch = require('desearch-js').default;

const client = new Desearch(process.env.DESEARCH_API_KEY);

Authentication

The constructor accepts a single argument, your API key:

const client = new Desearch('your-api-key');

The SDK sends that value as the Authorization header on every request.

API overview

Search

  • search(payload) → POST /search (web search with an optional summary; searchApi(payload) is the same method)

AI search methods

  • aiSearch(payload) → POST /desearch/ai/search (X posts and web, with an optional AI summary)
  • aiXLinksSearch(payload) → POST /desearch/ai/search/links/twitter
  • aiWebLinksSearch(payload) → POST /desearch/ai/search/links/web (deprecated; use search)

X methods

  • xSearch(params) → GET /twitter
  • xPostsByUrls(params) → GET /twitter/urls
  • xPostById(params) → GET /twitter/post
  • xPostsByUser(params) → GET /twitter/post/user
  • xPostRetweeters(params) → GET /twitter/post/retweeters
  • xUserPosts(params) → GET /twitter/user/posts
  • xUserReplies(params) → GET /twitter/replies
  • xPostReplies(params) → GET /twitter/replies/post
  • xTrends(params) → GET /twitter/trends

TikTok methods

  • tiktokSearch(payload) → POST /desearch/tiktok/search (paginated)
  • tiktokPostById(params) → GET /desearch/tiktok/post/{id}
  • tiktokProfile(params) → GET /desearch/tiktok/profile/{username}
  • tiktokProfilePosts(params) → GET /desearch/tiktok/profile/{username}/posts (paginated)
  • tiktokComments(params) → GET /desearch/tiktok/comments/{video_id} (paginated)
  • tiktokHashtag(params) → GET /desearch/tiktok/hashtag/{tag} (paginated)
  • tiktokTrending(params?) → GET /desearch/tiktok/trending

Facebook methods

  • facebookSearch(payload) → POST /desearch/facebook/search (Meta Ad Library, paginated)
  • facebookPostById(params) → GET /desearch/facebook/post/{id}
  • facebookProfile(params) → GET /desearch/facebook/profile/{profile_id}
  • facebookProfilePosts(params) → GET /desearch/facebook/profile/{profile_id}/posts (paginated)
  • facebookComments(params) → GET /desearch/facebook/comments/{post_id} (paginated)
  • facebookHashtag(params) → GET /desearch/facebook/hashtag/{tag} (Meta Ad Library, paginated)

Instagram methods

  • instagramSearch(payload) → POST /desearch/instagram/search (one page, no cursor)
  • instagramMedia(params) → GET /desearch/instagram/media/{id}
  • instagramProfile(params) → GET /desearch/instagram/profile/{username}
  • instagramProfilePosts(params) → GET /desearch/instagram/profile/{username}/posts (paginated)
  • instagramComments(params) → GET /desearch/instagram/comments/{shortcode} (paginated)
  • instagramHashtag(params) → GET /desearch/instagram/hashtag/{tag} (paginated)

YouTube methods

  • youtubeSearch(payload) → POST /desearch/youtube/search (videos, Shorts, live streams, channels and playlists; paginated)
  • youtubeVideo(params) → GET /desearch/youtube/video/{id}
  • youtubeTranscript(params) → GET /desearch/youtube/transcript/{video_id}
  • youtubeComments(params) → GET /desearch/youtube/comments/{video_id} (paginated)
  • youtubeChannel(params) → GET /desearch/youtube/channel/{handle}
  • youtubeChannelVideos(params) → GET /desearch/youtube/channel/{handle}/videos (paginated)

Reddit methods

  • redditSearch(payload) → POST /desearch/reddit/search (paginated)
  • redditSubreddit(params) → GET /desearch/reddit/subreddit/{name}
  • redditSubredditPosts(params) → GET /desearch/reddit/subreddit/{name}/posts (paginated)
  • redditPostById(params) → GET /desearch/reddit/post/{id}
  • redditComments(params) → GET /desearch/reddit/comments/{post_id} (comment tree; paginated)

Threads methods

  • threadsSearch(payload) → POST /desearch/threads/search (one page, no cursor)
  • threadsSearchUsers(payload) → POST /desearch/threads/search/users
  • threadsProfile(params) → GET /desearch/threads/profile/{username}
  • threadsProfilePosts(params) → GET /desearch/threads/profile/{username}/posts (latest 20-30 posts, no cursor)
  • threadsPostById(params) → GET /desearch/threads/post/{id} (with replies and thread continuation posts)

See Social pagination for the cursor flow.

Web methods

  • webSearch(params) → GET /web
  • extract(params) → GET /web/extract
  • webCrawl(params) → GET /web/crawl (deprecated compatibility method)

Network stats methods

No API key is needed for these, and the SDK sends none.

  • networkStats() → GET /network/stats
  • networkStatsHistory() → GET /network/stats/history
  • streamNetworkStats(options?) → GET /network/stats/stream (Server-Sent Events, async iterator)

People Search methods

  • xProfileSearch(payload, options?) → POST /desearch/people/search/x (billed)
  • youtubeCreatorSearch(payload, options?) → POST /desearch/people/search/youtube (billed)
  • linkedinProfileSearch(payload, options?) → POST /desearch/people/search/linkedin (billed)
  • tiktokCreatorSearch(payload, options?) → POST /desearch/people/search/tiktok (billed)
  • listPeopleTasks(params?) → GET /desearch/people/tasks
  • getPeopleTask(params) → GET /desearch/people/tasks/{task_id}
  • getPeopleResults(params) → GET /desearch/people/tasks/{task_id}/results
  • pausePeopleTask(params) → POST /desearch/people/tasks/{task_id}/pause
  • resumePeopleTask(params) → POST /desearch/people/tasks/{task_id}/resume
  • cancelPeopleTask(params) → POST /desearch/people/tasks/{task_id}/cancel
  • exportPeopleResults(params) → GET /desearch/people/tasks/{task_id}/export
  • listPeopleProfiles(params) → GET /desearch/people/profiles
  • exportPeopleProfiles(params) → GET /desearch/people/profiles/export
  • waitForPeopleTask(params, options?) polls getPeopleTask until the task ends
  • iterPeopleResultPages(params) is an async iterator over getPeopleResults pages

See People Search for the full flow.

Company Search methods

  • companySearch(payload, options?) → POST /desearch/companies/search (billed)
  • companyEnrich(payload, options?) → POST /desearch/companies/enrich (billed)
  • listCompanyTasks(params?) → GET /desearch/companies/tasks
  • getCompanyTask(params) → GET /desearch/companies/tasks/{task_id}
  • getCompanyResults(params) → GET /desearch/companies/tasks/{task_id}/results
  • pauseCompanyTask(params) → POST /desearch/companies/tasks/{task_id}/pause
  • resumeCompanyTask(params) → POST /desearch/companies/tasks/{task_id}/resume
  • cancelCompanyTask(params) → POST /desearch/companies/tasks/{task_id}/cancel
  • exportCompanyResults(params) → GET /desearch/companies/tasks/{task_id}/export
  • waitForCompanyTask(params, options?) polls getCompanyTask until the task ends
  • iterCompanyResults(params) is an async iterator over the companies of getCompanyResults pages

See Company Search and Company Enrich for the full flow.

Monitors methods

  • createMonitor(payload) → POST /desearch/monitors
  • estimateMonitor(payload?) → POST /desearch/monitors/estimate
  • listMonitors(params?) → GET /desearch/monitors
  • getMonitor(params) → GET /desearch/monitors/{monitor_id}
  • updateMonitor(params, fields) → PATCH /desearch/monitors/{monitor_id}
  • deleteMonitor(params) → DELETE /desearch/monitors/{monitor_id}
  • triggerMonitor(params) → POST /desearch/monitors/{monitor_id}/trigger (queues a billed run)
  • listMonitorRuns(params) → GET /desearch/monitors/{monitor_id}/runs
  • getMonitorRun(params) → GET /desearch/monitors/{monitor_id}/runs/{run_id}
  • listMonitorItems(params) → GET /desearch/monitors/{monitor_id}/items
  • testMonitorWebhook(params) → POST /desearch/monitors/{monitor_id}/webhook/test
  • rotateMonitorWebhookSecret(params) → POST /desearch/monitors/{monitor_id}/webhook/rotate-secret
  • iterMonitorItems(params) is an async iterator over the items of listMonitorItems pages
  • verifyWebhookSignature(secret, header, body, options?) checks a webhook delivery (no request)

See Monitors for the full flow.

Usage examples

Search

const { results, summary, meta, cost_usd } = await client.search({
  query: 'Who won the 2024 Nobel Prize in Physics?',
  mode: 'balanced', // or 'fast'
  count: 10, // 10, 15 or 20
  start_date: '2024-01-01',
  include_domains: ['nobelprize.org', 'reuters.com'],
  summary: true,
});
console.log(summary?.text); // "... [1]"
for (const citation of summary?.citations ?? []) {
  console.log(citation.index, citation.url);
}
for (const result of results) {
  console.log(result.title, result.url, result.highlights?.[0]);
}
  • summary: true adds a short answer written from the results. [n] in summary.text refers to summary.citations[].index, and every cited page is also in results. The summary has no extra charge.
  • When the summary could not be written, summary is null and meta.notices has Summary unavailable.; the results are still returned.
  • exclude_domains wins over include_domains and site:.
  • Set page_text: true to get each page's full text, and highlights: false to leave out the best passage.

AI search

AI Search is for X posts, with web results from the Desearch index and an optional AI summary. For web only, use search.

const result = await client.aiSearch({
  prompt: 'reactions to the latest Bittensor halving',
  tools: ['twitter', 'web'],
  result_type: 'LINKS_WITH_FINAL_SUMMARY',
  count: 20,
});

Notes:

  • tools accepts the source names defined in src/types.ts: web, hackernews, reddit, wikipedia, youtube, twitter, arxiv
  • Web results are capped at 20 per request
  • aiSearch always sends streaming: false, even if a caller tries to add a streaming field manually

AI X links search

const xLinks = await client.aiXLinksSearch({
  prompt: 'Bittensor subnet updates',
  count: 20,
});

X search

const tweets = await client.xSearch({
  query: 'bittensor',
  sort: 'Top',
  lang: 'en',
  min_likes: 50,
  count: 20,
});

X posts by URL

const tweets = await client.xPostsByUrls({
  urls: ['https://x.com/DesearchAI/status/1234567890123456789'],
});

Web search

const results = await client.webSearch({
  query: 'site:desearch.ai sdk docs',
  start: 0,
});

Extract

const page = await client.extract({
  url: 'https://desearch.ai',
  format: 'text',
});

format is 'text' (default), 'markdown' or 'html'. 'markdown' keeps headings, lists, tables and code: the main content of articles and docs, and the whole page without its navigation otherwise.

const markdown = await client.extract({
  url: 'https://en.wikipedia.org/wiki/Artificial_intelligence',
  format: 'markdown',
});

format: 'text' returns the page's main content, which can leave out tables, notices and other sections. Pass full_page: true (text only) for all visible text of the page, one block per line.

const everything = await client.extract({
  url: 'https://peles.ro/en/program-si-taxe/',
  format: 'text',
  full_page: true,
});

Pages that cannot be served throw an HTTP <status>: <body> error whose JSON body has an error_code, and they are not charged: page_not_found (404), js_required (422, retry with js: true), blocked (503, the site refused the request or answered with a bot check), upstream_timeout and upstream_failed (503).

Existing webCrawl() integrations continue to use the deprecated GET /web/crawl compatibility route. Use extract() for new integrations.

TikTok, Facebook and Instagram

const posts = await client.tiktokSearch({ query: 'bittensor', count: 10 });
const profile = await client.tiktokProfile({ username: 'tiktok' });
const comments = await client.tiktokComments({ video_id: posts[0].id!, count: 20 });
const trending = await client.tiktokTrending({ region: 'US', count: 10 });

const ads = await client.facebookSearch({ query: 'running shoes', sort: 'recent' });
const page = await client.facebookProfile({ profile_id: 'facebook' });
const pagePosts = await client.facebookProfilePosts({ profile_id: 'facebook' });
const post = await client.facebookPostById({ id: 'Meta/posts/1040495851972958' });

const accounts = await client.instagramSearch({ query: 'nasa' });
const media = await client.instagramMedia({ id: 'https://www.instagram.com/p/DeuOR-CjKE9/' });
const igComments = await client.instagramComments({ shortcode: 'DeuOR-CjKE9' });
const tagged = await client.instagramHashtag({ tag: 'ai', count: 20 });

Notes:

  • Each call reads one provider page. count (1-100) is a maximum, and a page can hold fewer items.
  • The SDK URL-encodes path parameters. An ID or post URL that contains /, such as Meta/posts/1040495851972958, works on the post, media and comments routes.
  • A TikTok post id works with tiktokComments and tiktokPostById. instagramComments takes the post shortcode (the code in the post URL); numeric media IDs return 404.
  • Facebook search and hashtag read the public Meta Ad Library. Organic Facebook post search is not available.
  • facebookSearch takes sort: impressions (the default: most seen first) or recent (Meta's monthly relevance grouping, which puts recently started ads first).
  • Fields the provider does not send are left out of each object, so every field of TikTokPost, FacebookPost, InstagramMedia and the other social types is optional.

YouTube, Reddit and Threads

const videos = await client.youtubeSearch({ query: 'bittensor', type: 'videos', upload_date: 'this_month' });
const video = await client.youtubeVideo({ id: 'https://youtu.be/dQw4w9WgXcQ' });
const transcript = await client.youtubeTranscript({ video_id: 'dQw4w9WgXcQ', language: 'en' });
const ytComments = await client.youtubeComments({ video_id: 'dQw4w9WgXcQ', order: 'top' });
const channel = await client.youtubeChannel({ handle: '@MrBeast' });
const uploads = await client.youtubeChannelVideos({ handle: '@MrBeast', sort: 'popular' });

const redditPosts = await client.redditSearch({ query: 'bittensor', sort: 'new', timeframe: 'month' });
const subreddit = await client.redditSubreddit({ name: 'AskReddit' });
const top = await client.redditSubredditPosts({ name: 'AskReddit', sort: 'top', timeframe: 'week' });
const redditPost = await client.redditPostById({ id: '1q6pxwn' });
const tree = await client.redditComments({ post_id: '1q6pxwn' });

const threads = await client.threadsSearch({ query: 'bittensor', start_date: '2026-01-01' });
const accounts = await client.threadsSearchUsers({ query: 'zuck' });
const threadsProfile = await client.threadsProfile({ username: 'zuck' });
const latest = await client.threadsProfilePosts({ username: 'zuck' });
const thread = await client.threadsPostById({ id: 'https://www.threads.com/@zuck/post/DK-BydcJHkF' });

Notes:

  • These routes take no count: each call returns one provider page. Every request is billed as one unit ($2.07 per 1,000), including an empty page the provider charged for. A 404 (for example a video without captions) and a 422 are not charged.
  • Video, post and comment IDs can be full URLs; the SDK URL-encodes them into the path.
  • youtubeSearch items have a type (video, short, live, channel or playlist) and the fields of that type. Channel and playlist results have no url.
  • Subreddit names are case-sensitive (AskReddit, not askreddit). timeframe on redditSubredditPosts applies to sort: 'top'.
  • redditComments returns top-level comments with the replies Reddit loaded alongside them; hasMoreReplies is true when there are more.
  • Threads routes do not paginate. threadsPostById returns the post with comments (public replies) and threadItems (the author's continuation posts).

Social pagination

The paginated social methods return a JSON array. The cursor for the next page comes in the x-desearch-next-cursor response header, which the SDK returns as metadata.nextCursor when you pass { includeMetadata: true }. Send it back unchanged as cursor, with the same target (username, tag, post or query), to read the next page. On the last page there is no cursor.

import Desearch, { type TikTokPost } from 'desearch-js';

const client = new Desearch(process.env.DESEARCH_API_KEY!);

const posts: TikTokPost[] = [];
let cursor: string | undefined;
do {
  const { data, metadata } = await client.tiktokHashtag(
    { tag: 'ai', count: 20, cursor },
    { includeMetadata: true },
  );
  posts.push(...data);
  cursor = metadata.nextCursor; // undefined on the last page
} while (cursor && posts.length < 100);
  • A cursor is opaque. Do not build or change one; send back exactly what you got.
  • A cursor is valid for 24 hours, on the same method and target. An expired, changed or other-target cursor fails with HTTP 422 and is not charged.
  • The searches (tiktokSearch, facebookSearch, youtubeSearch, redditSearch) take cursor in the request body; the other paginated methods send it as a query parameter. The SDK handles both.
  • instagramSearch, tiktokTrending and the Threads methods return one page and take no cursor.
  • Items repeated from the previous page are dropped and not charged again.

Network stats

These routes are public: no API key is needed, and the SDK does not send yours. The counters are an estimate (telemetry_kind: 'estimated').

const stats = await client.networkStats();
console.log(stats.total_searchable_pages, stats.rates_per_second.urls_crawled_today);

const history = await client.networkStatsHistory(); // the last 20 minutes, one point per second
console.log(history.points.length);

// Live: one snapshot per second over Server-Sent Events.
let lastEventId: string | null = null;
for await (const event of client.streamNetworkStats({
  signal: AbortSignal.timeout(60_000), // stop after a minute; the loop ends without an error
})) {
  lastEventId = event.id;
  console.log(event.data.updated_at, event.data.searches_completed_today);
}

// Resume later: the stream first replays what you missed (up to 20 minutes).
for await (const event of client.streamNetworkStats({ lastEventId })) {
  console.log(event.data.updated_at);
  break; // leaving the loop closes the connection
}

streamNetworkStats does not reconnect by itself. When the server closes the stream, the loop ends; call it again with lastEventId to continue.

Optional response cost metadata

SDK methods return the same raw payload shape by default:

const results = await client.search({ query: 'desearch sdk' });
console.log(results.results);

If you want per-request cost visibility, pass { includeMetadata: true } as the second argument. The SDK reads metadata from the same API response headers; it does not make an extra billing or pricing request.

const response = await client.search(
  { query: 'desearch sdk' },
  { includeMetadata: true },
);

console.log(response.data);
console.log(response.metadata.costUsd);
console.log(response.metadata.usageCount);
console.log(response.metadata.service);
console.log(response.metadata.currency);

The metadata wrapper works for JSON object, JSON array, and text endpoints such as extract() and webCrawl(). Missing or malformed metadata headers are ignored, so successful API calls still resolve normally.

metadata.nextCursor is the next-page cursor of the paginated social methods (the x-desearch-next-cursor header). See Social pagination.

People Search

People Search finds people by what they post and how they describe themselves: X profiles, YouTube creators, LinkedIn members and TikTok creators. Each search runs as a background task. The search call returns a queued task at once. You poll the task until it ends, read the results page by page and export them as CSV or JSON Lines.

End-to-end example

import { randomUUID } from 'node:crypto';
import { writeFileSync } from 'node:fs';
import Desearch from 'desearch-js';

const client = new Desearch(process.env.DESEARCH_API_KEY!);

// 1. Start the search. This is the only billed call.
const task = await client.tiktokCreatorSearch(
  {
    query: 'Skincare creators who review sunscreen',
    count: 25,
    filters: { min_followers: 10000, require_contact: true },
  },
  { idempotencyKey: randomUUID() },
);
console.log(task.task_id, task.status, task.reserved_cost_usd);

// 2. Wait until it ends. Polling is free.
const done = await client.waitForPeopleTask(task, {
  intervalMs: 5000,
  timeoutMs: 10 * 60 * 1000,
  onProgress: (t) => console.log(t.status, `${t.result_count}/${t.count}`),
});
console.log(done.status, done.final_cost_usd);

// 3. Read every result page.
for await (const page of client.iterPeopleResultPages({
  task_id: task.task_id,
  limit: 100,
})) {
  for (const person of page.results) {
    console.log(person.handle, person.score?.value, person.metrics.followers);
  }
}

// 4. Export only the creators with a public email, as CSV.
const csv = await client.exportPeopleResults({
  task_id: task.task_id,
  format: 'csv',
  has: ['email'],
});
writeFileSync(`people-${task.task_id}.csv`, csv);

xProfileSearch, youtubeCreatorSearch and linkedinProfileSearch work the same way. Each request takes query, count (5-200, default 25), min_score, exclude, metadata, and that platform's filters. The types XProfileSearchFilters, YouTubeCreatorSearchFilters, LinkedInProfileSearchFilters and TikTokCreatorSearchFilters list the filters for each platform.

Pricing

People Search is billed per profile delivered. Each search call reserves count times the route's unit price. When the task ends, it settles to the qualified profiles it delivered, and the rest of the reservation is returned:

  • A minimum per search applies when it finds anyone.
  • A search that finds nobody costs $0.
  • reserved_cost_usd and final_cost_usd on the task show the reserved and final amounts.
  • All task, results, export and profiles calls are free.

Current prices are at https://console.desearch.ai/pricing.

Idempotency

Pass { idempotencyKey } as the second argument of a search method. The SDK sends it as the Idempotency-Key header. If you retry a create call with the same key, the API returns the original task and does not charge again. Search methods also accept { includeMetadata: true }, which returns the reservation's cost headers as metadata.

Tagging searches with metadata

Pass metadata to label a search with your own keys, for example the campaign or workspace it belongs to. The task returns it as metadata ({} when none was sent), and listPeopleTasks can filter by it. The search itself never uses it.

await client.linkedinProfileSearch({
  query: 'Heads of sales at fintech startups who post about outbound',
  count: 25,
  metadata: { campaign: 'q4-outbound', workspace_id: 'ws_42' },
});

// Later: every search of that campaign, newest first.
const { tasks } = await client.listPeopleTasks({
  metadata: { campaign: 'q4-outbound' },
});
console.log(tasks.map((t) => [t.task_id, t.status, t.metadata.workspace_id]));
  • A search takes at most 10 keys. Keys are 1-40 characters of a-z, 0-9, _, . or -; values are strings of at most 200 characters. The API answers 422 otherwise.
  • listPeopleTasks takes up to 3 pairs. The SDK sends each as a metadata.<key>=<value> query parameter, and a task must match all of them exactly. Keep the same filter when you page with cursor.

Reading a finished search

A finished task says why it ended and how complete it is. Each result says what was confirmed (1.8.0 and later):

import { unverifiedCriteria } from 'desearch-js';

const done = await client.waitForPeopleTask(task);

// count_reached, rounds_exhausted, no_candidates, zero_qualified,
// candidate_budget, cost_limit, time_limit, cancelled or failed.
console.log(done.completion_reason);
if (done.coverage_limited) {
  // A budget stopped it before `count`: there may be more matching people.
}
for (const warning of done.warnings ?? []) {
  // partial_enrichment: some profiles could not be read after search.
  console.log(warning.code, warning.platform, `${warning.failed}/${warning.attempted}`, warning.by_reason);
}

for await (const page of client.iterPeopleResultPages({ task_id: task.task_id })) {
  for (const person of page.results) {
    // Criteria not confirmed, and disqualifiers that apply (verdict `met`).
    const unverified = unverifiedCriteria(person.score).map(
      (check) => `${check.criterion} (${check.verdict})`,
    );
    console.log(person.handle, person.score?.fully_verified, unverified);
    if (person.attributes?.enrichment === 'failed') {
      // Scored on the search hit only; enrichment_error says why (not_found, rate_limited, ...).
      console.log('profile not read:', person.attributes.enrichment_error);
    }
  }
}
  • completion_reason is null while the task is queued, running or paused. A search that a budget stopped is still completed, so check coverage_limited.
  • score.criteria_checks has one check per criterion, with verdict met, not_met or unknown, and the quote and source_url behind a met. It is information only: a qualified person can still have unknown criteria. For a disqualifier (is_disqualifier, 1.8.1 and later), met means it applies.
  • score.fully_verified is true when every criterion is met and no disqualifier is. Results scored before 2026-10-20 have no criteria_checks or fully_verified.
  • unverifiedCriteria(score) returns the checks that are not confirmed: every criterion that is not met, and every disqualifier that is met. It reads is_disqualifier, and the API's keyword rule for older checks without it. Their criterion texts are what the CSV export lists in its new unverified_criteria column, next to fully_verified.

Waiting and paging

  • waitForPeopleTask(params, options?) polls until the status is completed, partial, failed, cancelled or expired. It then returns the task. If the task has not ended within timeoutMs, it throws an Error. A paused task has not ended. params only needs task_id, so you can pass the task object itself.
  • iterPeopleResultPages(params) follows next_cursor until has_more is false. Results arrive while a search is still running. To read only new results later, keep the last page's next_cursor and pass it back as cursor.

Result filters

exportPeopleResults, listPeopleProfiles and exportPeopleProfiles accept the same filters. The SDK sends them as query parameters and joins has with commas:

| Filter | Meaning | | --- | --- | | has | Channels every person must have: email, website, x, linkedin, instagram, youtube, tiktok | | min_audience / max_audience | Followers (subscribers on YouTube) | | min_score | Minimum fit score, 0-100 | | location | Case-insensitive text in the location | | verified | Only verified accounts (X, TikTok) |

Pause, resume and cancel

import { PeopleTaskConflictError } from 'desearch-js';

await client.pausePeopleTask({ task_id: task.task_id });
await client.resumePeopleTask({ task_id: task.task_id });

try {
  await client.cancelPeopleTask({ task_id: task.task_id });
} catch (error) {
  if (error instanceof PeopleTaskConflictError) {
    // HTTP 409: the task's status does not allow this action.
    console.log(error.detail, error.task.status);
  } else {
    throw error;
  }
}

Cancelling bills only the profiles delivered so far. A search cancelled before it starts costs nothing.

Tasks and the profiles library

const { tasks, next_cursor } = await client.listPeopleTasks({
  platform: 'tiktok',
  status: ['running', 'paused'],
  limit: 20,
});

const library = await client.listPeopleProfiles({
  platform: 'tiktok',
  q: 'sunscreen',
  sort: 'audience',
  has: ['email'],
  min_audience: 10000,
});
console.log(library.total, library.profiles[0]?.found_by.query);

const allCreators = await client.exportPeopleProfiles({
  platform: 'tiktok',
  format: 'jsonl',
  has: ['email'],
});

The profiles library lists everyone your searches on one platform found, one entry per person, together with the search that found them (found_by). Results and profiles stay available for 30 days after a search ends.

Company Search and Company Enrich

Company Search finds companies on the web from a description and scores how well each one fits. Company Enrich starts from domains you already have. Both collect each company's public contact data: emails, phones, social profiles, and its leaders (CEO, founders, CTO, CFO by default) with their LinkedIn profiles and emails. Every contact keeps the page it came from (source_url).

Both run as background tasks on the People Search engine, so the flow is the same: the create call returns a queued task at once, you poll it, read the companies and export them as CSV or JSON Lines. They have their own routes under /desearch/companies. A People Search task ID is a 404 there, and the other way round.

| | Company Search | Company Enrich | | --- | --- | --- | | Method | companySearch | companyEnrich | | Input | a description (query) | 1-200 domains or URLs (domains) | | search_type / platform on the task | company_search / company | company_enrich / company_enrich | | Fit score | yes (score) | no (score is null) |

End-to-end example

import { randomUUID } from 'node:crypto';
import { writeFileSync } from 'node:fs';
import Desearch from 'desearch-js';

const client = new Desearch(process.env.DESEARCH_API_KEY!);

// 1. Start the search. This is the only billed call.
const task = await client.companySearch(
  {
    query: 'Series A fintech startups in Berlin building payment infrastructure',
    count: 25,
    min_score: 60,
    exclude: ['stripe.com'],
    roles: ['ceo', 'founder', 'cto', 'cfo'],
    filters: { countries: ['DE'], require: ['email'] },
    metadata: { campaign: 'q4' },
  },
  { idempotencyKey: randomUUID() },
);
console.log(task.task_id, task.status, task.reserved_cost_usd);

// 2. Wait until it ends. Polling is free. `stage` is `enriching` once every
//    company is published and only the later stages of some are left.
const done = await client.waitForCompanyTask(task, {
  intervalMs: 5000,
  timeoutMs: 15 * 60 * 1000,
  onProgress: (t) => console.log(t.status, t.stage, `${t.result_count}/${t.count}`),
});
console.log(done.status, done.completion_reason, done.final_cost_usd);

// 3. Read every company.
for await (const company of client.iterCompanyResults({ task_id: task.task_id })) {
  console.log(
    company.domain,
    company.score?.value,
    company.primary_email?.value,
    company.people.map((person) => `${person.name} (${person.roles.join('/')})`),
  );
}

// 4. Export as CSV: one row per company, with its CEO, founder, CTO and CFO.
const csv = await client.exportCompanyResults({ task_id: task.task_id, format: 'csv' });
writeFileSync(`companies-${task.task_id}.csv`, csv);

Company Search takes query (3-1000 characters), count (5-200, default 25), min_score (0-100), exclude (domains or URLs, up to 1000), roles, infer_emails, verify_emails, filters, max_cost_usd, continue_from and metadata:

  • roles: any of ceo, founder, cto, cfo, coo, cmo, president, owner, managing_director. The default is ['ceo', 'founder', 'cto', 'cfo']. A managing director (Geschäftsführer) counts as ceo when ceo is asked for.
  • infer_emails (default true) guesses leaders' emails from the company's address pattern, such as first.last. verify_emails (default true) checks every email.
  • filters.countries takes ISO 3166-1 alpha-2 codes or names (up to 20). filters.require takes email, phone, linkedin, leader and leader_email: a company that does not have them is not delivered and not billed.
  • max_cost_usd (more than 0, at most 100) is a search budget, and continue_from continues an ended search. See below.
  • To check only companies you name, give their websites in query: Restrict this search to Acme (acme.com.au) and Beta (beta.co.uk). Return only those. checks only those domains, with no web search. interpreted.interpretation.only_domains lists them and the task ends all_domains_processed. A query that names companies without their websites is not restricted: the search runs as usual with warning scope_not_applied.

Search budget and continuing a search

Without a budget, a search stops once it costs more than the companies it found pay for. It then ends with completion_reason cost_limit and coverage_limited: true, so there may be more matching companies. There are two ways to look further:

  • max_cost_usd is your search budget in USD (more than 0, at most 100). It must be at least what count reserves at the route price; below that, the API answers 422. The whole budget is reserved, and the search goes on until it delivers count or spends the budget. Its search effort is billed where the companies delivered do not cover it, up to the budget, even when it finds few companies or none. The unused part is returned. progress.effort_units shows that effort. Set a budget only when you accept paying for search effort.
  • continue_from takes the task_id of an ended Company Search of yours. The new search leaves out every company that one excluded, delivered or held for review (progress.review), so it only finds new ones. Send the same query and filters with the count you still want. While that task is running or paused, the API answers 409. A task that is not your Company Search is a 404. Both are plain HTTP <status> errors.
const query = 'Family-owned civil engineering contractors in Western Australia';
const filters = { countries: ['AU'] };

const first = await client.waitForCompanyTask(
  await client.companySearch({ query, filters, count: 50 }),
);

if (first.coverage_limited) {
  // Same query and filters, the count still wanted (at least 5), and the companies of `first` left out.
  const more = await client.companySearch({
    query,
    filters,
    count: Math.max(5, 50 - first.result_count),
    continue_from: first.task_id,
    max_cost_usd: 10, // only when you accept paying for search effort
  });
  await client.waitForCompanyTask(more);
}

Company Enrich

const task = await client.companyEnrich({
  domains: ['acme.com', 'https://www.beta.io/about'],
  roles: ['ceo', 'cto'],
});
console.log(task.query, task.count); // 'acme.com, beta.io', 2

await client.waitForCompanyTask(task);
for await (const company of client.iterCompanyResults({ task_id: task.task_id })) {
  console.log(company.domain, company.score); // score is null for Company Enrich
}

The API reduces each domain or URL to its host without www., lowercases it and removes duplicates. task.count is the number left. task.query is a short label of the domains, such as acme.com, beta.io and 3 more. task.request keeps the normalized request of both products.

How results fill in

Each company goes through five stages: profile (its homepage, and the fit score for Company Search), contacts (its contact, about, team and imprint pages), people (its leaders), email_patterns (inferred emails) and email_check. A company is published as soon as the stages its request needs have run:

| filters.require contains | Published after | | --- | --- | | nothing | profile | | email, phone, linkedin | contacts | | leader | people | | leader_email | email_check |

While any stage is pending, the company has enrichment.status partial; enrichment.stages shows pending, done, failed or skipped for each stage (a stage cut by the time limit is skipped). The later stages fill the company in place while you read. Keep next_cursor from getCompanyResults to get only new companies, and call it again without cursor to get the latest version of the ones you have:

let lastCursor: string | undefined;

// While the task runs: new companies since the last read...
const page = await client.getCompanyResults({ task_id: task.task_id, cursor: lastCursor });
lastCursor = page.next_cursor;

// ...and every company in its latest version.
const latest = await client.getCompanyResults({ task_id: task.task_id, limit: 500 });
const pending = latest.results.filter((c) => c.enrichment?.status === 'partial');

iterCompanyResults yields each company once, as it was when its page was read. Call it after waitForCompanyTask to get every company complete.

Reading a company

import { unverifiedCriteria } from 'desearch-js';

for await (const company of client.iterCompanyResults({ task_id: task.task_id })) {
  console.log(company.name, company.location?.country, company.industry);

  // The company's best address: never a support, press, legal, careers or other one,
  // and an inferred one only once it was checked valid.
  console.log(company.primary_email?.value, company.primary_email?.type);
  console.log(company.primary_contact?.name, company.primary_contact?.reason);

  for (const person of company.people) {
    for (const email of person.emails) {
      // source 'inferred' with confidence 'high' (pattern learned from the company's own addresses) or 'low'.
      console.log(person.name, email.value, email.source, email.confidence, email.verification?.status);
    }
  }

  // Search only: the fit score and what the company's own pages confirm.
  if (company.score) {
    console.log(company.score.value, company.score.fully_verified);
    console.log(unverifiedCriteria(company.score).map((check) => check.criterion));
  }
}
  • emails[].type is personal, leadership, sales, general, press, support, careers, legal or other. source is website, search, linkedin or inferred.
  • verification is null until the email_check stage ran (and when verify_emails is false). verification.status is valid, invalid, risky (catch-all domain, or no MX but an A record) or unknown. verification.checks has syntax, mx, smtp and web.
  • phones[].value is E.164 when the number parses. socials[].type is linkedin, x, facebook, instagram, github, youtube, tiktok, crunchbase, discord, telegram or medium. pages lists the pages that were read.
  • people[].roles is the subset of the request's roles the person holds. verified is true when a quote on the company's own site or the person's current LinkedIn position shows the role, and evidence has that quote.
  • contact_coverage says what was found, with the names of filters.require.
  • score (Company Search) has value, qualified, relevance, summary, matched_signals, reasons, concerns, criteria_checks and fully_verified. unverifiedCriteria works on it as on a People Search score.
  • Result types accept fields a newer API adds, so a newer worker does not break your types.

A finished task has completion_reason: People Search's reasons, plus all_domains_processed for Company Enrich and for a search restricted to the domains its query names. coverage_limited is true when a budget stopped it before count, and warnings lists what made part of it less reliable, such as enrichment_time_limit or scope_not_applied.

Pricing

Company Search and Company Enrich are billed per company delivered. The create call reserves count companies (Company Enrich: one per domain you send) at the route price, and the rest of the reservation is returned when the task ends:

  • Company Search: $45 per 1000 companies ($0.045 each), with a minimum of 1 when it delivers any.
  • Company Enrich: $50 per 1000 companies ($0.05 each), with a minimum of 1 when it delivers any.
  • A task that delivers no companies costs $0. A company left out by min_score or filters.require is not billed.
  • With max_cost_usd, Company Search reserves the whole budget instead, and also bills its search effort where the companies delivered do not cover it, up to the budget. Such a search can cost up to the budget even when it delivers no companies.
  • reserved_cost_usd and final_cost_usd on the task show the reserved and final amounts. All task, results and export calls are free.

Current prices are at https://desearch.ai/pricing. Results stay available for 30 days after a task ends. After that, getCompanyResults and exportCompanyResults fail with HTTP 410.

Idempotency and metadata

Both create methods take { idempotencyKey } and { includeMetadata: true } as the second argument, like the People Search methods. Both requests take metadata, with the same rules as People Search. The task returns it, and listCompanyTasks can filter by it:

const { tasks, next_cursor } = await client.listCompanyTasks({
  type: 'enrich', // or 'search'; leave out for both
  status: ['running', 'paused'],
  metadata: { campaign: 'q4' },
  limit: 20,
});

Pause, resume and cancel

import { CompanyTaskConflictError } from 'desearch-js';

await client.pauseCompanyTask({ task_id: task.task_id });
await client.resumeCompanyTask({ task_id: task.task_id });

try {
  await client.cancelCompanyTask({ task_id: task.task_id });
} catch (error) {
  if (error instanceof CompanyTaskConflictError) {
    // HTTP 409: the task's status does not allow this action.
    console.log(error.detail, error.task.status);
  } else {
    throw error;
  }
}

Cancelling bills only the companies delivered so far. A task cancelled before it starts costs nothing. A task paused for more than 7 days is cancelled.

Export

exportCompanyResults({ task_id, format }) returns text. format is csv (the default) or jsonl. CSV has one row per company: its domain, name, fit score, location, primary email, emails, phones and social profiles, then the CEO (or managing director), founder, CTO and CFO with their title, email, email status and LinkedIn profile, and fully_verified, unverified_criteria and enrichment_status. JSON Lines has one company per line with every field. Fields the later stages have not filled in yet are empty.

Monitors

A monitor is a search that runs on a schedule (1h, 3h, 6h, 12h, 1d or 7d) and keeps only what is new since its last run. Each run searches its sources (web, x, reddit, youtube, threads, tiktok, instagram, facebook, meta_ads) from where the previous run ended, drops everything the monitor has already seen, and screens the rest with an AI classifier: is the item about what the monitor watches (relevant), does it report something new (new_info), and one question per criterion. An item's score is the lowest of relevant and the criteria × 100, and it is kept at min_score (default 60). item.signals holds the answers (0-1): relevant, new_info and, when the monitor has criteria, criteria, the lowest answer across them. Kept items go to your webhook and stay readable through the API.

End-to-end example

import Desearch from 'desearch-js';

const client = new Desearch(process.env.DESEARCH_API_KEY!);

// What it can cost before you create it (free).
const estimate = await client.estimateMonitor({ sources: ['web', 'x', 'reddit'], interval: '1d' });
console.log(estimate.max_run_cost_usd, estimate.max_monthly_cost_usd);

// 1. Create it. The first run is queued at once (run_now defaults to true).
const monitor = await client.createMonitor({
  query: 'Bittensor subnet launches and updates',
  name: 'Bittensor subnet news',
  criteria: ['Announces a new subnet, release or partnership'],
  sources: ['web', 'x', 'reddit'],
  interval: '1d',
  options: { x: { count: 20, lang: 'en' }, web: { count: 10 } },
  min_score: 60,
  webhook: { url: 'https://example.com/hooks/desearch' },
  metadata: { team: 'growth' },
});
// Returned only here and by rotateMonitorWebhookSecret: store it.
const secret = monitor.webhook_secret!;

// 2. Read what it found, newest first.
for await (const item of client.iterMonitorItems({ monitor_id: monitor.monitor_id, source: 'x' })) {
  console.log(item.score, item.url, item.text?.slice(0, 80));
}

// 3. Runs: what each source returned, how many items were new and kept, and the cost.
const { runs } = await client.listMonitorRuns({ monitor_id: monitor.monitor_id, limit: 5 });
const run = await client.getMonitorRun(runs[0]); // the run with its items, most relevant first

// 4. Change it, pause it, run it now, delete it.
await client.updateMonitor(monitor, { min_score: 70, status: 'paused' });
await client.triggerMonitor(monitor); // a paused monitor can still run by hand
await client.deleteMonitor(monitor);

createMonitor takes query (3-500 characters; the only required field), name, criteria (up to 5, each at most 300 characters), sources (default ['web', 'x']), interval (default 1d), options, min_score (0-100, default 60), summary (default false), webhook ({ url, events }), metadata (up to 20 string keys) and run_now (default true):

  • options.web.count is 10, 15 or 20; options.x takes count (1-100, default 20), lang, min_likes and accounts; options.tiktok takes count (10, 20 or 30, default 10), accounts and hashtags; options.reddit takes subreddits, options.youtube takes channels and options.threads takes accounts; options.instagram takes accounts and hashtags (one of them is required with that source) and options.facebook.pages is required with facebook; options.meta_ads.count is 10, 20 or 30 (default 10).
  • summary: true adds a short LLM digest of the items each run keeps (run.summary).
  • webhook.events is any of monitor.items.found (a run kept at least one item), monitor.run.completed and monitor.run.failed. The default is ['monitor.items.found', 'monitor.run.failed']. The URL must be HTTPS on a public address; redirects are not followed.

Watched accounts

A source can watch up to 10 accounts instead of searching: options.x.accounts (X usernames), options.reddit.subreddits, options.youtube.channels, options.tiktok.accounts and options.threads.accounts. Instagram (options.instagram.accounts, or hashtags) and Facebook (options.facebook.pages) only watch accounts, as neither has a keyword search for posts: a monitor with either source needs at least one. Each run then reads every account's newest posts, and the query and criteria still decide what is kept, like search results. Both stay required; min_score: 0 keeps every new post.

const watched = await client.createMonitor({
  query: 'Product launches and model releases',
  sources: ['x', 'reddit', 'youtube', 'tiktok'],
  options: {
    x: { accounts: ['@OpenAI', 'https://x.com/AnthropicAI'], lang: 'en' },
    reddit: { subreddits: ['r/LocalLLaMA'] },
    youtube: { channels: ['@OpenAI', 'UCXZCJLdBC09xxGZ6gcdrc6A'] },
    tiktok: { accounts: ['@openai'], count: 10 },
  },
  min_score: 0,
});
console.log(watched.options.x?.accounts); // ['OpenAI', 'AnthropicAI']

const social = await client.createMonitor({
  query: 'Product launches and campaigns',
  sources: ['instagram', 'facebook', 'threads'],
  options: {
    instagram: { accounts: ['@openai', 'https://www.instagram.com/nasa/'] },
    facebook: { pages: ['https://www.facebook.com/NASA/', '100064869009429'] },
    threads: { accounts: ['https://www.threads.com/@zuck'] },
  },
  min_score: 0,
});
console.log(social.options.facebook?.pages); // ['NASA', '100064869009429']
  • Send names the way people paste them: OpenAI, @OpenAI or a profile URL for X (at most 15 characters); LocalLLaMA, r/LocalLLaMA or a URL for Reddit; @handle, a UC... channel ID or a channel URL for YouTube; openai, @openai or a profile URL for TikTok, Instagram and Threads; a page name, a numeric page ID or a page URL for Facebook (profile.php?id=... and /pages/Name/123... URLs give the ID). The API cleans them and returns them that way (OpenAI, LocalLLaMA, @OpenAI or UC..., openai, NASA or 100064869009429); the SDK sends them as given. An invalid name, or more than 10 on one source, is an HTTP 422 error, and so is an instagram or facebook source without accounts, on create and on update (updateMonitor checks the monitor as changed).
  • With x.accounts, X reads each account's timeline (20 posts), so x.count is not used; x.lang and x.min_likes still filter. With tiktok.accounts, tiktok.count is the posts read per account. Instagram reads up to 12 posts per account and Facebook up to 10 per page.
  • An item read from a watched account has data.account, the name it was watched as. An account that cannot be read (unknown or private) is listed in the run's stats.sources.<source>.accounts_failed; the source fails only when all of its accounts do.
  • TikTok items have data.views, likes, comments, shares, saves and duration_s; Threads items likes; Instagram items likes, comments, views and media_type; Facebook items reactions, comments, shares and views. MonitorTikTokItemData, MonitorThreadsItemData, MonitorInstagramItemData and MonitorFacebookItemData type them.
  • TikTok, Instagram and Facebook items also have data.post_id (the ID GET /desearch/social/post gives the same post; an Instagram shortcode), type (video, image, carousel, reel, ...), hashtags, mentions (TikTok and Instagram), media (links to the post's videos and pictures) and thumbnail (MonitorSocialPostItemData). Media and thumbnail links expire after a few days, so copy what you keep. The metrics are the post's when the run found it; GET /desearch/social/post?url=<link> reads them again, and author=true adds the author's followers.
  • TikTok search has no working date filter and ranks by relevance, so a TikTok keyword monitor finds a new video only when it reaches TikTok's top results. To follow creators, watch their accounts (options.tiktok.accounts). Threads keyword search returns loosely matched posts, so accounts work better there too.

Watched hashtags

TikTok and Instagram can also watch up to 10 hashtags each: options.tiktok.hashtags and options.instagram.hashtags, in any script (skincare, #სილამაზე, or a tag URL such as https://www.tiktok.com/tag/skincare or https://www.instagram.com/explore/tags/skincare/). A hashtag feed lists popular as well as recent posts from any account, so a monitor finds posts outside the accounts it watches; the window drops the old ones and the monitor's seen items the rest. With accounts or hashtags, a source reads those feeds instead of searching by keyword, and Instagram needs one of them. Facebook has no organic hashtag feed; for ads by keyword, use meta_ads.

import type { MonitorTikTokItemData } from 'desearch-js';

const tags = await client.createMonitor({
  query: 'Posts about our skincare brand',
  sources: ['tiktok', 'instagram'],
  options: {
    tiktok: { count: 10, hashtags: ['#სილამაზე', 'https://www.tiktok.com/tag/skincare'] },
    instagram: { hashtags: ['skincare', 'სილამაზე'] }, // no accounts needed
  },
  min_score: 0,
});
console.log(tags.options.tiktok?.hashtags); // ['სილამაზე', 'skincare']

for await (const item of client.iterMonitorItems({ monitor_id: tags.monitor_id, source: 'tiktok' })) {
  const data = item.data as MonitorTikTokItemData;
  console.log(data.hashtag, data.post_id, data.views, item.url);
}
  • The API returns hashtags without # (a tag URL becomes its tag) and answers HTTP 422 for an invalid hashtag or more than 10 on one source.
  • Each run reads tiktok.count posts per TikTok hashtag and up to 12 per Instagram hashtag. A hashtag is billed as one read, whatever the number of posts (see Pricing).
  • An item read from a hashtag has data.hashtag. A hashtag that cannot be read is listed in the run's stats.sources.<source>.hashtags_failed; the source fails only when all of its accounts and hashtags do.

Meta ads

The meta_ads source searches the Meta Ad Library by keyword and reads options.meta_ads.count ads per run (10, 20 or 30, default 10). The Ad Library matches keywords, so the query should be a brand, product or short phrase (ChatGPT); a sentence finds nothing. It has no date filter: an ad is new the first time a run sees it, if it started within the last 30 days. Ads are screened with their own question (is the ad about what the monitor watches) and get no new_info.

import type { MonitorMetaAdsItemData } from 'desearch-js';

const ads = await client.createMonitor({
  query: 'ChatGPT',
  sources: ['meta_ads'],
  options: { meta_ads: { count: 20 } },
});
for await (const ad of client.iterMonitorItems({ monitor_id: ads.monitor_id, source: 'meta_ads' })) {
  const data = ad.data as MonitorMetaAdsItemData;
  console.log(ad.title, data.page, data.link, ad.url); // headline, page, landing page, Ad Library record
}

A Meta ad item has the ad headline as title, its Ad Library record as url and when the ad started as published_at; data has page, active, cta, link (the landing page), platforms and thumbnail (MonitorMetaAdsItemData).

updateMonitor(monitor, fields) takes the same fields, all optional, plus status. status: 'paused' stops scheduled runs; status: 'active' resumes them, also after the API paused the monitor itself (paused_reason insufficient_credits or webhook_failing). webhook: null removes the webhook.

Webhooks

Each delivery is a POST with the event in Desearch-Event, the delivery ID in Desearch-Delivery and a signature in Desearch-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">, keyed with the monitor's webhook_secret. Verify it against the raw body before you parse it:

import express from 'express';
import { verifyWebhookSignature, WEBHOOK_SIGNATURE_HEADER, type MonitorWebhookEvent } from 'desearch-js';

const app = express();

app.post('/hooks/desearch', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyWebhookSignature(process.env.DESEARCH_WEBHOOK_SECRET!, req.get(WEBHOOK_SIGNATURE_HEADER), req.body)) {
    return res.status(400).end();
  }
  const event = JSON.parse(req.body.toString('utf8')) as MonitorWebhookEvent;
  if (event.type === 'monitor.items.found') {
    for (const item of event.items) console.log(item.source, item.score, item.url);
  }
  res.status(204).end(); // answer 2xx within 10 seconds
});

verifyWebhookSignature returns false for a missing or malformed header, a wrong signature, or a timestamp more than 5 minutes from now (toleranceSeconds changes that). It compares in constant time and throws a TypeError when given a parsed object instead of the raw body. A delivery without a 2xx within 10 seconds is retried after 1, 5, 30, 120 and 360 minutes; after 5 deliveries in a row fail every attempt, the monitor pauses with paused_reason: 'webhook_failing'.

monitor.webhook.last_delivery is the newest delivery, null before the first: status is pending while it waits for its first or next attempt (next_attempt_at, with the last answer in status_code and error), delivered, or failed after every retry, with event, attempts, created_at and delivered_at.

testMonitorWebhook(monitor) sends a signed monitor.test event with one sample item and returns what your endpoint answered (delivered, status_code, error, duration_ms). A test is not a delivery: last_delivery stays as it was. rotateMonitorWebhookSecret(monitor) returns a new secret once; deliveries from then on are signed with it.

Pricing

Creating, reading, changing and deleting monitors is free. Each run pays for what it uses: its searches at their list price (the same as calling those endpoints yourself), AI screening per item screened, and with summary the LLM usage plus 50%. A run with no new items still pays for its searches. TikTok, Instagram, Facebook and Meta ads are billed per read, $3.00 per 1,000 reads ($0.003 a read), whatever the number of posts a read returns: one read per watched account, hashtag or Facebook page, one per TikTok keyword search, and one per Ad Library page (meta_ads, whatever meta_ads.count). A read that returns nothing is free, except an empty or private TikTok account, which takes two reads, so a run's hold counts two reads per TikTok account. The other sources pay their feed's list price: an X account is about $0.003 (a 20-post timeline), and a subreddit, a YouTube channel or a Threads account $0.00207 each. estimateMonitor includes them in its breakdown. When a run is queued, max_run_cost_usd is held on the balance; when it ends it is billed what it used (never more) and the rest is released. A run that cannot be held fails with insufficient_credits and the monitor pauses until you resume it.

Errors

Monitors use the standard HTTP <status>: <body> errors: 422 for an invalid body (including a bad account name or hashtag, more than 10 accounts or hashtags on a source, an instagram source without accounts or hashtags, or a facebook source without pages), 402 when the balance cannot hold one run (create, even with run_now: false, and trigger), 404 for an unknown monitor or run, 409 when the account already has 25 monitors (create) or a run is already queued or running (trigger), and 400 for a webhook URL that is not public HTTPS, an invalid cursor or source filter, or a webhook test or secret rotation on a monitor without a webhook.

Tech stack

  • TypeScript ^5.9.3
  • undici ^6.28.1 || ^7.29.1 for HTTP transport
  • dotenv ^17.3.1 as a runtime dependency in package.json
  • tsup ^8.5.1 for bundling
  • vitest ^4.0.18 for tests
  • typedoc ^0.28.17
  • typedoc-plugin-markdown ^4.10.0
  • output targets: CommonJS, ESM, and bundled declaration files

Commands

| Command | Purpose | | --- | --- | | npm run build | Build dist/ with tsup using the config in tsup.config.ts | | npm run build-fast | Build src/index.ts directly into CJS and ESM without the full default tsup command | | npm test | Run the Vitest test suite | | npm run generate-docs | Generate markdown API docs from src/index.ts using TypeDoc | | npm run build:beta | Build for beta publishing | | npm run version:beta | Bump a beta prerelease version | | npm run version:stable | Bump a stable patch version | | npm run publish:beta | Version, build, and publish with the beta npm tag | | npm run publish:stable | Version, build, and publish as the default release | | npm run prepublishOnly | Automatic npm hook that runs npm run build before publish | | node scripts/e2e-youtube-reddit-threads.mjs [--base-url URL] [--key-env NAME] | Live smoke test of the 16 YouTube, Reddit and Threads methods, with page 2 of each paginated one (billed, about $0.05; run npm run build first). Reads the key from DESEARCH_API_KEY, or the variable --key-env names, or ~/.config/desearch/e2e.env. | | node scripts/e2e-monitors.mjs [--base-url URL] [--key-env NAME] [--with-accounts] [--with-meta] | Live smoke test of the Monitors methods (free: it creates one monitor with run_now: false, never triggers a run, and deletes it; run npm run build first). --with-accounts adds a second monitor with the TikTok source and watched accounts and checks the cleaned names. --with-meta adds one with the Instagram, Facebook, Meta ads and Threads sources and a webhook, and checks the cleaned names, the 422s for Instagram and Facebook without accounts, the estimate breakdown, webhook.last_delivery and the meta_ads items filter; it also makes one billed facebookSearch call with sort: 'recent' (2 ads, about $0.004). Same key lookup as above. | | DESEARCH_API_KEY=... node scripts/e2e-full-coverage.mjs | Live smoke test of the TikTok, Facebook, Instagram, Search API and network stats methods against the production API (billed; run npm run build first). Prints PASS / FAIL per call. It starts a People Search task only with --with-people. |

Architecture overview

Source layout:

  • src/index.ts, the Desearch client plus the shared handleRequest<T>() transport helper
  • src/types.ts, request/response contracts and X entity models
  • tsup.config.ts, build output configuration
  • package.json, scripts, exports, dependency versions, and package metadata

Key design decisions in the current source:

  • one shared request helper powers every public method
  • GET payloads are serialized through URLSearchParams
  • POST and PATCH payloads are serialized as JSON
  • response parsing switches between JSON and text based on content-type
  • default calls return the parsed payload directly, preserving the existing SDK response shape
  • callers can opt into { data, metadata } wrappers with { includeMetadata: true }
  • extract() and the legacy webCrawl() method return text while most other methods return JSON-shaped data
  • the base URL is fixed to https://api.desearch.ai
  • aiSearch() forcibly disables streaming
  • People Search and company methods put task_id in the path, join array query parameters (has, status) with commas, and send Idempotency-Key only when you pass idempotencyKey
  • path parameters (task_id, monitor_id, run_id, social IDs, usernames, tags) are URL-encoded
  • the network stats methods send no Authorization header; streamNetworkStats() reads the Server-Sent Events body incrementally instead of buffering it

See docs/architecture.md for the detailed flow and ADR 0001 for the reasoning behind the current transport design.

Error handling

HTTP failures are thrown as plain Error instances in this format:

HTTP <status>: <response body>

Non-HTTP failures are wrapped as:

Unexpected Error: <message>

The exceptions are PeopleTaskConflictError and CompanyTaskConflictError, which People Search and company pause, resume and cancel throw on HTTP 409. Their message keeps the HTTP 409: <response body> format, and they add status, detail and the current task.

streamNetworkStats() throws the same two formats from inside the loop: HTTP <status>: <body> when the API refuses the stream, and Unexpected Error: <message> when the connection fails or an event is not valid JSON. Aborting its signal ends the loop without an error.

Example:

try {
  await client.search({ query: 'desea