SDKs
TypeScript SDK
kloakd-sdk for Node.js and browser — one API for everything, full module coverage
8 min read
Install
npm install kloakd-sdk@^0.7.0
Node.js 18+ | version 0.7.0 | native fetch
Client
import { Kloakd } from 'kloakd-sdk';
const client = new Kloakd({
apiKey: process.env.KLOAKD_API_KEY!,
organizationId: process.env.KLOAKD_ORG_ID!,
timeout: 100, // seconds (the default); keep it above the API's 85 s hand-off
maxRetries: 3,
});
Quickstart — one call does everything
const result = await client.crawl('https://example.com', {
maxPages: 50,
extractSchema: { title: 'css:h1', content: 'css:article' },
});
for (const page of result.pages) {
if (page.ok) {
console.log(`${page.url} →`, page.structuredData);
}
}
That's it. crawl() internally:
- Discovers all pages on the site (Webgrph BFS)
- Fetches each page through the anti-bot engine, which works out per site what it takes (a browser, a residential exit, a challenge solver) — no
forceBrowserneeded - Extracts structured data from each page if
extractSchemais provided (Kolektr, using cached fetch artifacts — no second HTTP round-trip)
Per-page failures are caught and marked success: false — the crawl never aborts on a single page error.
Primary method
client.crawl()
const result = await client.crawl('https://example.com', {
maxDepth: 3,
maxPages: 100,
extractSchema: { title: 'css:h1', price: 'css:.price' },
includeExternalLinks: false,
sessionArtifactId: undefined, // reuse a Fetchyr session for login-protected sites
});
console.log(`Discovered: ${result.totalPagesDiscovered} pages`);
console.log(`Fetched: ${result.pagesFetched}`);
console.log(`Failed: ${result.pagesFailed}`);
for (const page of result.pages) {
if (page.ok) {
console.log(` ${page.url}`, page.structuredData);
} else {
console.log(` ${page.url} FAILED: ${page.error}`);
}
}
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| url | string | required | Seed URL to start crawling from |
| maxDepth | number | your plan's maximum | Maximum BFS depth (sent only when set) |
| maxPages | number | your plan's maximum | Maximum pages to crawl (sent only when set) |
| extractSchema | Record<string, string> or a fields list | undefined | { field: 'css:selector' } (the css: prefix is optional) or [{ name, selector, attribute? }] |
| includeExternalLinks | boolean | false | Follow off-domain links |
| sessionArtifactId | string | undefined | Reuse an authenticated session artifact (from Fetchyr) |
Returns: SiteCrawlResult
| Field | Type | Description |
|---|---|---|
| success | boolean | The crawl's own success |
| url | string | Seed URL |
| totalPagesDiscovered | number | Pages found during BFS |
| pagesFetched | number | Pages successfully fetched |
| pagesFailed | number | Pages that failed (included with success: false) |
| pages | CrawlPage[] | All pages with HTML and optional structured data |
| crawlArtifactId | string \| null | Artifact ID for the site hierarchy |
| error | string \| null | Error message if crawl failed entirely |
| crawlId | string | The crawl's id |
| status | string | The crawl's own status, including held_quota |
| held | boolean | The crawl is held for quota (below) |
| message | string \| null | The API's note on the crawl's state, such as why it is held |
client.crawlStream() — async streaming
For long-running crawls, use the async streaming version to receive real-time progress events:
import type { SiteCrawlResult } from 'kloakd-sdk';
for await (const event of client.crawlStream('https://example.com', {
maxPages: 500,
extractSchema: { title: 'css:h1' },
})) {
if (event.type === 'page_fetched') {
console.log(`[${event.page}/${event.total}] ${event.url} OK`);
} else if (event.type === 'page_failed') {
console.log(`[${event.page}/${event.total}] ${event.url} FAIL: ${event.error}`);
} else if (event.type === 'crawl_complete') {
const result = event.metadata['result'] as SiteCrawlResult;
console.log(`Done: ${result.pagesFetched} fetched, ${result.pagesFailed} failed`);
}
}
Event types
| Type | Description |
|---|---|
| discovery_started | Crawl discovery has begun |
| discovery_complete | Discovery finished, fetch phase starting |
| page_fetching | About to fetch page N of total |
| page_fetched | Page fetched successfully |
| page_failed | Page fetch failed (crawl continues) |
| crawl_complete | All pages processed, final summary in metadata.result |
Low-level methods
Need fine-grained control? The individual modules are still available:
evadr.fetch()
const page = await client.evadr.fetch('https://example.com'); // follows a 202 hand-off to the result
if (!page.success) console.log(`Fetch failed: ${page.error}`); // still HTTP 200: check success
console.log(`Status: ${page.statusCode}`);
console.log(`Artifact ID: ${page.artifactId}`);
webgrph.crawl()
const crawl = await client.webgrph.crawl('https://example.com', { // waits; startCrawl() returns at once
maxDepth: 3,
maxPages: 100,
});
console.log(`${crawl.crawlId}: ${crawl.totalPages} pages`);
kolektr.page()
const result = await client.kolektr.page(
'https://example.com',
{ schema: { title: 'css:h1', price: 'css:.price' } }
);
console.log(result.records);
One record per item
SDK 0.6.0 and later. itemSelector is sent as the API's item_selector.
The 0.5.0 SDK drops it; upgrade with npm install kloakd-sdk@^0.7.0.
const result = await client.kolektr.page('https://books.toscrape.com/', {
schema: {
itemSelector: 'article.product_pod',
fields: [
{ name: 'title', selector: 'h3 a', attribute: 'title' },
{ name: 'price', selector: 'p.price_color' },
],
},
});
console.log(result.totalRecords); // 20: one record per book
Each element matching itemSelector is one record, with the field selectors read inside it (rules). Without it the page is one record.
Artifact chaining
Pass artifact IDs between low-level methods to skip redundant work:
const page = await client.evadr.fetch('https://example.com');
const data = await client.kolektr.page('https://example.com', {
schema: { title: 'css:h1' },
fetchArtifactId: page.artifactId ?? undefined,
});
Error handling
import {
AuthenticationError, KloakdError, PaymentRequiredError, QuotaExceededError, RateLimitError,
} from 'kloakd-sdk';
try {
const result = await client.crawl('https://example.com');
} catch (e) {
if (e instanceof AuthenticationError) console.log('Invalid API key');
else if (e instanceof PaymentRequiredError || e instanceof QuotaExceededError) console.log('Billing:', e.message);
else if (e instanceof RateLimitError) console.log(`Retry after ${e.retryAfter}s`);
else if (e instanceof KloakdError) console.log(e.message);
}
Advanced namespaces
client.skanyr // Site store: resources, APIs, snapshots
client.nexus // Strategy engine
client.parlyr // Natural language queries
client.fetchyr // Logins & authenticated scraping
Crawls: held, partial, continue
A crawl whose organisation ran out of allowance is held (held_quota), not failed, and resumes by itself. webgrph.crawl and webgrph.waitForCrawl return it at once with held true and message the server's text. client.crawl returns SiteCrawlResult with held, crawlId, status and message.
A crawl that stopped early ends completed with isPartial true. CrawlResult also has partialReason, resumable, pagesDiscovered, pagesFetched, pagesUnfetched and errorCode.
let crawl = await client.webgrph.crawl('https://example.com');
if (crawl.held) {
console.log(crawl.message); // held for quota; it resumes by itself
} else if (crawl.resumable) {
await client.webgrph.continueCrawl(crawl.crawlId); // ApiError 409 when it cannot be continued
crawl = await client.webgrph.waitForCrawl(crawl.crawlId);
}
console.log(crawl.isPartial, crawl.pagesFetched, crawl.pagesUnfetched);
Each PageNode has fetchStatus and fetchError.
Login sessions
const login = await client.fetchyr.startLoginSession('https://example.com/login');
console.log(login.status, login.next, login.sessionArtifactId);
if (login.sessionArtifactId) {
const status = await client.fetchyr.getSession(login.sessionArtifactId);
console.log(status.status, status.pauseReason);
await client.fetchyr.resumeSession(status.artifactId); // ApiError 409 when the session is not paused
}
startLoginSession(targetUrl, opts) takes method, cookies, userAgent and country and returns a LoginSession; getSession and resumeSession return a SessionStatus. The flow is described under logins.
Batch jobs
let batch = await client.createBatchJob(
['https://books.toscrape.com/catalogue/page-1.html',
'https://books.toscrape.com/catalogue/page-2.html'],
{ entityType: 'products', fields: ['title', 'price'] },
);
batch = await client.getBatchJob(batch.id);
console.log(batch.status, batch.completedItems, batch.totalItems);
await client.pauseBatchJob(batch.id);
await client.resumeBatchJob(batch.id);
await client.cancelBatchJob(batch.id);
const page = await client.listBatchJobs({ page: 1, pageSize: 20 }); // page.total, page.batchJobs
const results = await client.getBatchJobResults(batch.id, { limit: 100, offset: 0 });
for (const item of results.results) {
console.log(item.url, item.status, item.extractedData);
}
const saved = await client.downloadBatchJob(batch.id, 'batch.csv', { format: 'csv' });
createBatchJob(urls, opts) takes extractionConfig, crawlId, entityType and fields and returns a BatchJob (id, name, status, totalItems, completedItems, createdAt, message). A control the batch's state does not allow throws ApiError with statusCode 409 and code invalid_batch_transition. A create or resume that could not be queued throws ApiError 503 with code dispatch_failed and is not retried. The limit on batches at once throws ConcurrencyLimitError; its activeCrawls holds the API's active_batches. The rules are on the batch jobs page.
Unified scrape
const scrape = await client.unifiedScrape('https://books.toscrape.com/', {
prompt: 'extract all book titles and prices',
});
if (scrape.status === 'failed') { // success is true even then: check status
console.log('the scrape failed');
} else if (scrape.authRequired) {
console.log('login needed:', scrape.discoveryId);
} else {
const job = await client.getUnifiedScrape(scrape.jobId);
console.log(job.status, job.result);
}
unifiedScrape(url, opts) takes prompt, mode, schema, options, context, constraints and sessionArtifactId, follows a 202 hand-off and returns a UnifiedScrapeResult. See unified scrape for the failed and login answers.
Crawl-extract jobs and exports
webgrph has startCrawlExtract, crawlExtract, getCrawlExtract, waitForCrawlExtract, getCrawlExtractResults, iterCrawlExtractResults, crawlExtractAllResults, getCrawlExtractPages, exportCrawlExtract, downloadCrawlExtract and cancelCrawlExtract for the crawl-extract job.
An export (ExportDownload, SavedExport) has a crawl object read from the response's X-Crawl-* headers. For a batch export crawl and jobStatus are null.
Changes in 0.7.0
PageNode.statusCodeandPageNode.crawlParentUrl: the API sends neither.ExtractionResult.hasMoreandtotal: usetotalRecords.ExtractionResultgainslevel,levelReasonandloginOptions.nexus.executeandnexus.knowledge, anderroron the Nexus results: a failed call throws.
Next steps
- Quickstart — your first calls
- API reference — detailed endpoint docs
- Batch jobs and unified scrape — the routes behind the batch and unified scrape methods
- Error reference — full error taxonomy
