### Quick Start Usage Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Demonstrates initializing the client, listing monitors with pagination, creating a monitor, running an instant check, and verifying webhook signatures. ```ts import { HostTracker, HostTrackerError, paginate, parseWebhookEvent, verifyWebhookSignature, } from '@hosttracker/sdk'; const ht = new HostTracker({ token: process.env.HT_TOKEN }); // 1. List monitors - one page, or every page. const page = await ht.monitors.listMonitor({ query: { limit: 10, state: ['down'] } }); console.log(page.data.length, 'monitors down'); for await (const monitor of paginate(ht.monitors.listMonitor)) { console.log(monitor.id, monitor.url, monitor.state); } // 2. Create one. An Idempotency-Key is generated for you, so a retry is free. const created = await ht.monitors.createMonitor({ body: { url: 'https://example.com', type: 'http', name: 'Example homepage', interval: 5, locations: { pools: ['allworld'] }, }, }); // 3. Run an instant check and wait for the locations to report. const result = await ht.runCheck({ url: 'https://example.com', type: 'http' }); console.log(result.state, result.events?.length, 'locations reported'); // 4. Verify a webhook delivery (Express-style; give yourself the RAW body). app.post('/hooks/hosttracker', express.raw({ type: '*/*' }), (req, res) => { if (!verifyWebhookSignature(req.headers, req.body, process.env.HT_WEBHOOK_SECRET!)) { return res.status(400).end(); } const event = parseWebhookEvent(req.body); if (event.event === 'monitor.down') console.log('DOWN:', event.data); res.status(200).end(); }); ``` -------------------------------- ### Install the SDK Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/llms.txt Use npm to install the HostTracker SDK package. ```bash npm install @hosttracker/sdk ``` -------------------------------- ### Initialize and use the SDK Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/llms.txt Demonstrates client initialization, pagination, resource creation, instant checks, and webhook signature verification. ```ts import { HostTracker, HostTrackerError, paginate, verifyWebhookSignature } from '@hosttracker/sdk'; const ht = new HostTracker({ token: process.env.HT_TOKEN }); // One page, or every page. const page = await ht.monitors.listMonitor({ query: { limit: 10, state: ['down'] } }); for await (const monitor of paginate(ht.monitors.listMonitor)) console.log(monitor.id, monitor.url); // Create one. An Idempotency-Key is generated for you, so a retry is free. const created = await ht.monitors.createMonitor({ body: { url: 'https://example.com', type: 'http', name: 'Example homepage', interval: 5, locations: { pools: ['allworld'] } }, }); // Run an instant check and wait for the locations to report. const result = await ht.runCheck({ url: 'https://example.com', type: 'http' }); // Verify a webhook delivery, on the RAW body. if (!verifyWebhookSignature(req.headers, rawBody, process.env.HT_WEBHOOK_SECRET!)) return 400; ``` -------------------------------- ### Build and Verify SDK Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Standard commands for type checking, testing, building, and verifying the SDK project. ```bash npm run typecheck # tsc over src + tests npm test # unit tests, mocked transport npm run build # dual ESM + CJS output into dist/ npm run verify # everything above, in order ``` -------------------------------- ### Initialize HostTracker Client Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Configure the SDK instance with authentication, base URL, and network behavior settings. ```ts const ht = new HostTracker({ token: process.env.HT_TOKEN, // string, or a (possibly async) function baseUrl: 'https://api2.host-tracker.com', timeout: 30_000, // per ATTEMPT, in ms; 0 disables maxRetries: 2, // attempts after the first idempotency: 'auto', // or 'off' userAgent: 'acme-deployer/2.1', // appended to the SDK's own User-Agent headers: { 'X-Tenant': 'acme' }, // sent on every request fetch: myFetch, // any fetch-compatible transport }); ``` -------------------------------- ### HostTracker Client Initialization Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Initializes the HostTracker SDK client with required authentication and optional network configuration parameters. ```APIDOC ## Constructor: new HostTracker(options) ### Description Initializes a new instance of the HostTracker SDK client. ### Parameters - **token** (string | function) - Optional - API token for authentication. Omit for anonymous access to public catalogues. - **baseUrl** (string) - Optional - The base URL for the API. Defaults to 'https://api2.host-tracker.com'. - **timeout** (number) - Optional - Request timeout in milliseconds per attempt. Defaults to 30000. - **maxRetries** (number) - Optional - Number of retries after the first attempt. Defaults to 2. - **idempotency** (string) - Optional - Idempotency setting, 'auto' or 'off'. Defaults to 'auto'. - **userAgent** (string) - Optional - Custom string appended to the SDK's User-Agent header. - **headers** (object) - Optional - Custom headers sent on every request. - **fetch** (function) - Optional - A fetch-compatible transport function. ### Example ```ts const ht = new HostTracker({ token: process.env.HT_TOKEN, baseUrl: 'https://api2.host-tracker.com', timeout: 30_000, maxRetries: 2, idempotency: 'auto', userAgent: 'acme-deployer/2.1', headers: { 'X-Tenant': 'acme' } }); ``` ``` -------------------------------- ### Run Live Smoke Tests Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Execute smoke tests against a specific API instance by providing the base URL and authentication token. ```bash HT_BASE_URL=https://api2.host-tracker.com HT_TOKEN=… npm run test:smoke ``` -------------------------------- ### Run an instant check Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Initiates a check against a URL and monitors progress via the onPoll callback. The SDK automatically follows the result URL provided by the API. ```ts const result = await ht.runCheck( { url: 'https://example.com', type: 'http', pools: ['allworld'] }, { waitTimeout: 90_000, onPoll: (r) => console.log(r.state, r.events?.length) }, ); ``` -------------------------------- ### Executing SDK Operations Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Operations accept a single object containing path, query, body, and headers, returning the response body. ```ts const monitor = await ht.monitors.getMonitor({ path: { id }, query: { expand: ['settings', 'lastResult'] }, }); ``` -------------------------------- ### Paginate list endpoints Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Use these helpers to iterate over paginated resources, collect all items, or perform bounded walks. ```ts import { collect, pages, paginate } from '@hosttracker/sdk'; // Items, across every page. for await (const contact of paginate(ht.contacts.listContact, { query: { limit: 200 } })) { … } // Whole envelopes, when you want syncCursor / count / summary. for await (const page of pages(ht.monitors.listMonitor, { query: { expand: ['count'] } })) { console.log(page.count, page.syncCursor); } // Everything in one array (mind the size). const all = await collect(ht.webhooks.listWebhook); // Guards, for a bounded walk. await collect(ht.results.listResult, { query: { monitor: [monitorId] } }, { maxItems: 500 }); ``` -------------------------------- ### Regenerate SDK from OpenAPI Spec Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Commands to regenerate the SDK code from the OpenAPI specification, supporting both published and local/remote files. ```bash npm ci # From the published spec (github.com/HostTracker/openapi): npm run regen # From a local or pre-release document: HT_SPEC=/path/to/openapi-3.1.gen.json npm run regen HT_SPEC=https://api2.host-tracker.com/openapi/v2.json npm run regen ``` -------------------------------- ### Configure Custom Fetch for Local Development Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Implement a custom fetch transport to bypass TLS verification for local instances with self-signed certificates. ```ts import { Agent, fetch as undiciFetch } from 'undici'; const dispatcher = new Agent({ connect: { rejectUnauthorized: false } }); const ht = new HostTracker({ baseUrl: 'https://localhost:5001', token, fetch: async (input) => { const request = input as Request; const body = ['GET', 'HEAD'].includes(request.method) ? undefined : new Uint8Array(await request.arrayBuffer()); return (await undiciFetch(request.url, { method: request.method, headers: Object.fromEntries(request.headers.entries()), body, dispatcher, signal: request.signal, })) as unknown as Response; }, }); ``` -------------------------------- ### Pagination Helpers Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Utilities for iterating over paginated list endpoints, collecting all items, or processing full page envelopes. ```APIDOC ## Pagination Helpers ### Description Helpers to simplify cursor-based pagination for list endpoints. These utilities handle cursor management automatically. ### Methods - **paginate(fn, options)**: Async generator that yields individual items across all pages. - **pages(fn, options)**: Async generator that yields full page envelopes (including metadata like syncCursor, count, and summary). - **collect(fn, options, config)**: Resolves all items into a single array. Supports a `maxItems` guard in the config object. ### Usage ```ts // Iterate items for await (const contact of paginate(ht.contacts.listContact, { query: { limit: 200 } })) { ... } // Iterate pages for await (const page of pages(ht.monitors.listMonitor, { query: { expand: ['count'] } })) { console.log(page.count, page.syncCursor); } // Collect all const all = await collect(ht.webhooks.listWebhook); ``` ``` -------------------------------- ### Query list endpoints via POST Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Use body-query helpers when filters are too long or complex for URL parameters. ```ts await collect(ht.monitors.queryMonitor, { body: { id: manyIds } }); ``` -------------------------------- ### Job Management Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Utilities for handling bulk mutations that return job identifiers and require polling for completion. ```APIDOC ## Job Management ### Description Bulk mutations return a job identifier. Use `waitForJob` to poll for the final state of the operation. ### Methods - **waitForJob(jobId, options)**: Polls the job status until completion. Honors `Retry-After` headers. - **ht.jobs.resumeJob({ path: { id: jobId } })**: Resumes a job that has been interrupted. ### Job States - **succeeded**: Operation completed successfully. - **partial**: Operation completed with some item failures. - **failed**: Operation failed. - **cancelled**: Operation was cancelled. - **interrupted**: Operation stopped unexpectedly; requires manual resumption. ``` -------------------------------- ### Accessing SDK Namespaces and Operations Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Operations are grouped into namespaces based on OpenAPI tags, with methods named after their operationId. ```ts ht.monitors.listMonitor(…) ht.contacts.createContact(…) ht.monitorTypes.getMonitorType(…) ht.alerts.setMonitorAlert(…) ht.results.listResult(…) ht.reports.generateReport(…) ht.incidents.getIncident(…) ht.webhooks.testWebhook(…) ht.maintenance.listMaintenance(…) ht.statusPages.createStatusPage(…) ht.account.getAccountQuota(…) ht.monitoringLocations.listAgent(…) ht.instantChecks.listInstantCheck(…) ht.jobs.getJob(…) ``` -------------------------------- ### Manage Idempotency Keys Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Use custom idempotency keys for retries across process crashes or check the meta response to determine if a request was replayed by the server. ```ts // Reuse your own key so a retry from a crashed process still collapses. await ht.monitors.bulkCreateMonitor({ body, idempotencyKey: `import-${batchId}` }); // Was this answer a replay of an earlier identical request? const { meta } = await ht.monitors.bulkCreateMonitor.withResponse({ body, idempotencyKey }); if (meta.idempotencyReplayed) console.log('server replayed the original answer'); ``` -------------------------------- ### ht.runCheck Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Executes an instant check on a specified URL. The method follows the result URL and provides incremental updates via an onPoll callback. ```APIDOC ## POST /check ### Description Initiates an instant check for a given URL. The method returns a result object and tracks progress through an optional polling callback. ### Method POST ### Endpoint /check ### Parameters #### Request Body - **url** (string) - Required - The URL to check. - **type** (string) - Required - The type of check (e.g., 'http'). - **pools** (array) - Required - List of monitoring pools to use. ### Response #### Success Response (202) - **id** (string) - Unique identifier for the check. - **dbId** (string) - Database identifier for the check. - **retryAfter** (number) - Suggested retry interval. - **estimatedDurationSec** (number) - Estimated time to complete. - **resultUrl** (string) - URL to poll for results. ``` -------------------------------- ### Convert Timestamps in HostTracker SDK Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Use the provided utility functions to convert between Unix seconds and JavaScript Date objects when interacting with the API. ```ts import { fromDate, toDate } from '@hosttracker/sdk'; toDate(monitor.created); // → Date await ht.results.listResult({ query: { from: fromDate(new Date('2026-01-01')) } }); ``` -------------------------------- ### Accessing Transport Metadata Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Use the withResponse method to retrieve transport-level details like status, headers, and rate-limit information. ```ts const { data, meta } = await ht.monitors.listMonitor.withResponse({ query: { limit: 50 } }); console.log(meta.requestId, meta.rateLimit?.remaining, meta.idempotencyReplayed); ``` -------------------------------- ### Handle HostTracker SDK errors Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Use the isCode method to branch logic based on specific error codes, ensuring proper handling of different failure scenarios. ```ts import { HostTrackerError } from '@hosttracker/sdk'; try { await ht.monitors.createMonitor({ body }); } catch (error) { if (!(error instanceof HostTrackerError)) throw error; if (error.isCode('duplicate_monitor')) { const existing = error.errors?.[0]?.existingId; // …adopt the monitor that is already there } else if (error.isCode('quota_exceeded')) { // Wait for the window or upgrade - retrying immediately cannot help. } else if (error.isCode('missing_scope')) { console.error('token needs', error.errors?.[0]?.required); } else { console.error(error.code, error.status, error.detail, 'requestId:', error.requestId); } } ``` -------------------------------- ### Webhook Verification Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Utilities for verifying the authenticity of incoming webhooks using HostTracker signatures. ```APIDOC ## Webhook Verification ### Description Functions to verify webhook signatures and parse event payloads. Supports standard webhook verification and signature rotation. ### Methods - **assertWebhookSignature(headers, rawBody, secrets)**: Verifies the signature and throws a WebhookVerificationError if invalid. - **parseWebhookEvent(rawBody)**: Parses the raw webhook body into a typed event object. ### Parameters - **headers** (object) - Required - The request headers containing the signature. - **rawBody** (string) - Required - The raw request body bytes. - **secrets** (array) - Required - Array of current and previous secrets for verification. ``` -------------------------------- ### Manage bulk jobs Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Poll bulk mutation jobs using waitForJob and handle various job states including partial successes and interruptions. ```ts const { jobId } = await ht.monitors.bulkCreateMonitor({ body: { items } }); const job = await ht.waitForJob(jobId, { waitTimeout: 10 * 60_000, onPoll: (j) => console.log(j.state, j.progress), }); switch (job.state) { case 'succeeded': break; case 'partial': // SUCCESS with some items failed - resubmit only those for (const item of job.results ?? []) { if (item.status === 'failed') console.error(item.index, item.error?.code); } break; case 'failed': case 'cancelled': break; case 'interrupted': // the server running it died; continue where it stopped await ht.jobs.resumeJob({ path: { id: jobId } }); break; } ``` -------------------------------- ### Narrow webhook event data Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Demonstrates how to narrow the parsed event type to access specific data fields based on the event name. ```ts if (event.event === 'incident.opened') console.log(event.data.incidentId, event.data.monitorId); ``` -------------------------------- ### HostTrackerError Interface Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md The HostTrackerError class provides structured error information. Developers should use the isCode() method to handle specific error scenarios. ```APIDOC ## HostTrackerError ### Description Every failure in the SDK throws a `HostTrackerError`. Use the `isCode()` method to branch logic based on the stable machine code. ### Members - **code** (string) - The stable machine code used for branching logic. - **status** (number) - The HTTP status code; 0 for network failures. - **type, title, detail, instance** (string) - RFC 9457 problem document fields. - **errors[]** (ProblemError[]) - Array of offending values with remediation details. - **requestId** (string) - The X-Request-Id for support tracking. - **retryAfter** (number) - Seconds to wait if provided. - **rateLimit** (object) - Parsed RateLimit snapshot. - **attempts** (number) - Number of SDK attempts made. - **isTimeout** (boolean) - True if the SDK per-attempt timeout fired. ### Usage Example ```ts try { await ht.monitors.createMonitor({ body }); } catch (error) { if (!(error instanceof HostTrackerError)) throw error; if (error.isCode('duplicate_monitor')) { const existing = error.errors?.[0]?.existingId; } else if (error.isCode('quota_exceeded')) { // Handle quota limit } else { console.error(error.code, error.status); } } ``` ``` -------------------------------- ### Verify and parse webhooks Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Validates webhook signatures using raw request bodies and parses the event payload. Always use the raw body to ensure signature integrity. ```ts import { assertWebhookSignature, parseWebhookEvent } from '@hosttracker/sdk'; assertWebhookSignature(request.headers, rawBody, [currentSecret, previousSecret]); const event = parseWebhookEvent(rawBody); ``` -------------------------------- ### Override Configuration Per Call Source: https://github.com/hosttracker/hosttracker-sdk-js/blob/main/README.md Modify request-specific settings like timeout and retries during individual API method calls. ```ts await ht.monitors.bulkCreateMonitor({ body, timeout: 120_000, maxRetries: 0 }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.