/** * Trackshon client. Copy this file into any Node/edge project, or import it * once it ships as @raeven-co/trackshon. Zero dependencies. * * const tk = createTrackshon({ apiKey: process.env.TRACKSHON_API_KEY!, baseUrl: "https://www.trackshon.com" }); * await tk.log({ type: "lead.waitlist", person: { email }, idempotencyKey: `waitlist:${email}` }); */ export type TrackshonStage = "exposure" | "signal" | "lead" | "conversation" | "deal" | "revenue" | "retention"; export type TrackshonEvent = { type: string; stage?: TrackshonStage; occurredAt?: string; idempotencyKey?: string; account?: { domain?: string; name?: string }; person?: { email?: string; handle?: string; name?: string }; armCode?: string; value?: number; note?: string; props?: Record; }; export type TrackshonResult = { accepted: number; duplicates: number; rejected: Array<{ index: number; reason: string }> }; export type SearchMode = "auto" | "web" | "discussions" | "code" | "news"; export type SearchRequest = { query: string; /** 1-20, default 10. */ maxResults?: number; /** Only results from the last N days. */ sinceDays?: number; includeDomains?: string[]; excludeDomains?: string[]; /** auto (default) | web | discussions | code | news */ mode?: SearchMode; /** Also read the top pages and return their text. Counts as 3 searches. */ includeContent?: boolean; /** How many top results to read (1-8, default 5). */ contentTop?: number; maxContentChars?: number; }; export type SearchResult = { title: string; url: string; domain: string; snippet: string; publishedAt: string | null; score: number; engines: string[]; content?: string; contentChars?: number; }; export type SearchResponse = { query: string; results: SearchResult[]; meta: { tookMs: number; cached: boolean; /** True when the general web engines were unavailable and results come from smaller sources only. Retry later for a fuller answer. */ limited: boolean; relaxedQuery: string | null; contentFetched: number; engines: Array<{ name: string; ok: boolean; hits: number }>; }; usage: SearchUsage; }; /** The workspace's daily search allowance after this call. `charged` is what this call cost (0 is never returned; failed calls throw and cost nothing). */ export type SearchUsage = { dailyLimit: number; charged: number; used: number; remaining: number }; export type ExtractedPage = { url: string; finalUrl: string | null; ok: boolean; status: number | null; title: string | null; description: string | null; author: string | null; siteName: string | null; publishedAt: string | null; language: string | null; content: string | null; contentChars: number; truncated: boolean; links: string[]; error?: string; }; /** Thrown for non-2xx answers from the search endpoints; `code` is the API's machine-readable reason. */ export class TrackshonApiError extends Error { constructor( message: string, readonly status: number, readonly code?: string, /** Seconds to wait before retrying, from Retry-After. */ readonly retryAfter?: number, ) { super(message); this.name = "TrackshonApiError"; } } export type TrackshonOptions = { apiKey: string; baseUrl: string; /** Defaults to globalThis.fetch. */ fetch?: typeof fetch; /** Request timeout in ms. Default 5000 for ledger; analyze/scout need longer. */ timeoutMs?: number; }; async function readJson(response: Response): Promise { try { return await response.json(); } catch { return null; } } export function createTrackshon(options: TrackshonOptions) { const base = options.baseUrl.replace(/\/$/, ""); const doFetch = options.fetch ?? globalThis.fetch; const timeoutMs = options.timeoutMs ?? 5000; async function request(path: string, init: RequestInit & { timeoutMs?: number } = {}): Promise { const ms = init.timeoutMs ?? timeoutMs; const { timeoutMs: _drop, ...rest } = init; return doFetch(`${base}${path}`, { ...rest, headers: { authorization: `Bearer ${options.apiKey}`, ...(rest.body ? { "content-type": "application/json" } : {}), ...(rest.headers ?? {}), }, signal: AbortSignal.timeout(ms), }); } async function send(events: TrackshonEvent[]): Promise { const response = await request("/api/v1/events", { method: "POST", body: JSON.stringify({ events }), }); if (!response.ok && response.status !== 422) { throw new Error(`Trackshon ingest failed: ${response.status}`); } return (await readJson(response)) as TrackshonResult; } async function post(path: string, body: unknown, timeout: number): Promise { const response = await request(path, { method: "POST", body: JSON.stringify(body), timeoutMs: timeout }); const json = (await readJson(response)) as ({ error?: string; code?: string } & T) | null; if (!response.ok) { const retry = Number(response.headers.get("retry-after")); throw new TrackshonApiError(json?.error ?? `Trackshon ${path} failed: ${response.status}`, response.status, json?.code, Number.isFinite(retry) && retry > 0 ? retry : undefined); } return json as T; } return { /** * Search the open web (beta). Several engines run in parallel and are fused and re-ranked; add * `includeContent` to get the readable text of the top pages for an agent or RAG step. Capacity is small * and shared, so expect 2 to 20 seconds and check `meta.limited`. * * Throws TrackshonApiError with `status` and `code`: 400 bad_request (the message names the field), * 401 (missing or invalid key), 402 plan_required, 403 scope_denied, 429 daily_quota or rate_limited * (both with retryAfter), 503 search_unavailable (retryAfter) or search_not_configured. Calls that fail * with a 5xx are not counted against the allowance. A timeout throws a TimeoutError, not a TrackshonApiError. */ search: (body: SearchRequest) => post("/api/v1/search", body, 60_000), /** Fetch up to five public pages and return their readable text and metadata. */ extract: (urls: string[], options?: { maxChars?: number }) => post<{ pages: ExtractedPage[]; usage: SearchUsage }>("/api/v1/extract", { urls, ...options }, 60_000), /** Log one event. Never throws on validation problems; check `rejected`. */ log: (event: TrackshonEvent) => send([event]), /** Log up to 500 events in one request. */ logMany: (events: TrackshonEvent[]) => send(events), /** KPI tree for the key's workspace. */ tree: async () => { const response = await request("/api/v1/tree"); if (!response.ok) throw new Error(`Trackshon tree failed: ${response.status}`); return readJson(response); }, /** Paginated ledger events. */ events: async (query?: { limit?: number; before?: string }) => { const params = new URLSearchParams(); if (query?.limit) params.set("limit", String(query.limit)); if (query?.before) params.set("before", query.before); const qs = params.toString(); const response = await request(`/api/v1/events${qs ? `?${qs}` : ""}`); if (!response.ok) throw new Error(`Trackshon events failed: ${response.status}`); return readJson(response); }, /** Register a tracked arm (post/page). */ createArm: async (body: { channel: string; url: string; title: string; hypothesis?: string; idempotencyKey: string }) => { const response = await request("/api/v1/arms", { method: "POST", body: JSON.stringify(body) }); if (!response.ok) throw new Error(`Trackshon arms failed: ${response.status}`); return readJson(response); }, /** Run analyze (long). */ analyze: async (body: { url?: string; idea?: string; answers?: Record }) => { const response = await request("/api/v1/analyze", { method: "POST", body: JSON.stringify(body), timeoutMs: 300_000 }); if (!response.ok) throw new Error(`Trackshon analyze failed: ${response.status}`); return readJson(response); }, /** Run scout (long). */ scout: async (body?: { words?: { audience?: string; pains?: string; keywords?: string } }) => { const response = await request("/api/v1/scout", { method: "POST", body: JSON.stringify(body ?? {}), timeoutMs: 120_000 }); if (!response.ok) throw new Error(`Trackshon scout failed: ${response.status}`); return readJson(response); }, /** List opportunities / drafts. */ opportunities: async (query?: { limit?: number; status?: string; drafted?: boolean }) => { const params = new URLSearchParams(); if (query?.limit) params.set("limit", String(query.limit)); if (query?.status) params.set("status", query.status); if (query?.drafted) params.set("drafted", "1"); const qs = params.toString(); const response = await request(`/api/v1/opportunities${qs ? `?${qs}` : ""}`); if (!response.ok) throw new Error(`Trackshon opportunities failed: ${response.status}`); return readJson(response); }, }; }