/** Server-side Zabalist read client. Pass credentials explicitly. */ export type SignalKind = 'bid.status_changed' | 'project.stage_changed' | 'contractor.filing_linked' | 'contractor.filing_unlinked' | 'area.appraisal_published' | 'area.appraisal_withdrawn'; export type SignalIssuer = 'tdlr' | 'city_of_austin' | 'esbd' | 'travis_cad'; export interface SignalTerritory { county: string | null; county_source: 'tdlr' | 'recorded_plat' | null; issuers: SignalIssuer[]; } export interface ZabalistSignal { id: string; position: string; kind: SignalKind; subject_id: string; observed_at: string; territory: SignalTerritory | null; before: unknown; after: unknown; evidence: Array<{source: string; reference: string}>; } export interface SignalFilters { kind?: SignalKind; subject_id?: string; county?: string; issuer?: SignalIssuer; after?: string; limit?: number; } export interface SourceEvidence { source: string; reference: string; url: string | null } export interface Plat { id: string; area_name: string; tax_year: number; cohort: '10–24' | '25–49' | '50–99' | '100–249' | '250+'; median_appraised_psf: number; appraisal_edition: string; boundary_edition: string; published_at: string; } export interface Coverage { captured_at: string; sources: Array<{source: string; status: 'ok' | 'review' | 'unknown'; record_count: number | null; last_checked_at: string | null; last_synced_at: string | null; latest_source_date: string | null; last_check_age_days: number | null; latest_filing_age_days: number | null}>; signals: Array<{kind: SignalKind; published_count: number; latest_published_at: string | null}>; } export interface ResourceRecords { projects: Project; permits: Permit; bids: Bid; plats: Plat } export interface ResourceInsights {projects: ProjectFilingInsight; permits: PermitProjectInsight; bids: BidInsight; plats: PlatBenchmark} export type Resource = keyof ResourceRecords; export type Dataset = Exclude; export interface RecordDetail {record: T; evidence: SourceEvidence[]; history_url: string | null} export interface ObjectResponse {data: T; meta: {notes?: string[]; test_mode?: true}} export type ResourceDetail = RecordDetail & {insight: ResourceInsights[R]}; export interface SignalPage {signals: ZabalistSignal[]; nextAfter: string; hasMore: boolean} export interface ListPage {data: T[]; meta: {next_cursor: string | null; count: number; limit: number; offset: number; has_more?: boolean; total?: number; sync_through?: string; next_since?: string; [key: string]: unknown}} export interface VerifyResult extends ListPage { match?: VerifyMatch | null; alternates?: Array<{id: string; name: string | null; confidence: number}>; usage?: {verify_used: number; verify_included: number; period_start: string; period_end: string}; } export interface HistoryPage extends ListPage {contractor: {id: string; name: string | null}} export interface StreamOptions {maxPages?: number} function textField(value: unknown): string | null { return typeof value === 'string' && value.length > 0 ? value : null; } export class ZabalistApiError extends Error { readonly status: number; readonly code: string; readonly requestId: string | null; readonly retryAfter: string | null; readonly apiMessage: string | null; readonly hint: string | null; readonly details: unknown; readonly docs: string | null; readonly upgradeUrl: string | null; constructor(status: number, code: string, requestId: string | null, retryAfter: string | null, error: Record = {}) { const summary = 'Zabalist HTTP ' + status + ', ' + code + ', request ' + (requestId ?? 'unknown') + ', retry-after ' + (retryAfter ?? 'unspecified'); const apiMessage = textField(error.message); const hint = textField(error.hint); super([summary, apiMessage, hint].filter(Boolean).join('\n')); this.name = 'ZabalistApiError'; this.status = status; this.code = code; this.requestId = requestId; this.retryAfter = retryAfter; this.apiMessage = apiMessage; this.hint = hint; this.details = error.details; this.docs = textField(error.docs); this.upgradeUrl = textField(error.upgrade_url); } } async function read(key: string, path: string, filters?: object): Promise { if (!key) throw new Error('A Zabalist API key is required'); const url = new URL('https://www.zabalist.com/api/public/v1' + path); for (const [name, value] of Object.entries(filters ?? {})) if (value != null) url.searchParams.set(name, String(value)); const response = await fetch(url, {method: 'GET', headers: {Authorization: 'Bearer ' + key, Accept: 'application/json'}, redirect: 'error', signal: AbortSignal.timeout(15000)}); if (!response.ok) { const body = await response.json().catch(() => null); const error = body?.error && typeof body.error === 'object' ? body.error : {}; throw new ZabalistApiError(response.status, textField(error.code) ?? 'http_error', response.headers.get('x-request-id') ?? textField(error.request_id), response.headers.get('retry-after'), error); } return response.json() as Promise; } function bound(value: number, maximum: number, name: string): number { if (!Number.isInteger(value) || value < 1 || value > maximum) throw new RangeError(name + ' must be an integer from 1 through ' + maximum); return value; } function idSegment(id: string | number, allowSlash = false): string { const value = String(id); if (!value || value === '.' || value === '..' || (value.includes('/') && !allowSlash) || value.includes('\\') || value.length > 220) throw new Error('Supply one published record ID'); return encodeURIComponent(value); } export async function signalPage(key: string, filters: SignalFilters = {}): Promise { const page = await read<{data: ZabalistSignal[]; meta: {next_after: string; has_more?: boolean}}>( key, '/signals', {...filters, limit: bound(filters.limit ?? 25, 100, 'limit')}); return {signals: page.data, nextAfter: page.meta.next_after, hasMore: page.meta.has_more === true}; } /** Compatibility entry point. Save nextAfter after storing the page. */ export async function listSignals(key: string, filters: SignalFilters = {}) { const {signals, nextAfter} = await signalPage(key, filters); return {signals, nextAfter}; } export async function* signalPages(key: string, filters: SignalFilters = {}, options: StreamOptions = {}): AsyncGenerator { const maximum = bound(options.maxPages ?? 10, 100, 'maxPages'); let after = filters.after; for (let i = 0; i < maximum; i++) { const page = await signalPage(key, {...filters, after}); if ((page.hasMore && !page.signals.length) || (page.signals.length && BigInt(page.nextAfter) <= BigInt(after ?? '0'))) { throw new Error('The signal page did not advance its checkpoint'); } yield page; if (!page.hasMore) return; after = page.nextAfter; } } export async function getRecordResponse(key: string, resource: R, id: string | number): Promise>> { if (!['projects', 'permits', 'bids', 'plats'].includes(resource)) throw new Error('Unsupported record type'); return read(key, '/' + resource + '/' + idSegment(id, resource === 'bids' || resource === 'plats')); } export async function getRecord(key: string, resource: R, id: string | number): Promise> { return (await getRecordResponse(key, resource, id)).data; } export function getCoverageResponse(key: string): Promise> { return read(key, '/coverage'); } export async function getCoverage(key: string): Promise { return (await getCoverageResponse(key)).data; } type PageFilter = {limit?: number; offset?: number; cursor?: string}; export async function listRecords(key: string, dataset: D, filters: DatasetFilters[D] = {}): Promise> { if (!['projects', 'permits', 'bids'].includes(dataset)) throw new Error('Unsupported list dataset'); if (dataset === 'projects' && 'trade' in filters) throw new Error('Use project_type to filter projects'); return read(key, '/' + dataset, filters); } export function resolveContractor(key: string, filters: VerifyFilters): Promise { return read(key, '/contractors/verify', filters); } export function contractorHistory(key: string, contractorId: string, filters: HistoryFilters = {}): Promise { return read(key, '/contractors/' + idSegment(contractorId) + '/history', filters); } async function* cursorPages

, F extends PageFilter>(load: (filters: F) => Promise

, filters: F, options: StreamOptions) { const maximum = bound(options.maxPages ?? 10, 100, 'maxPages'); bound(filters.limit ?? 25, 100, 'limit'); const query = {...filters}; const seen = new Set([query.cursor]); for (let i = 0; i < maximum; i++) { const page = await load(query); const cursor = page.meta.next_cursor; if (cursor && (!page.data.length || seen.has(cursor))) throw new Error('The result page did not advance its cursor'); yield page; if (!cursor) return; seen.add(cursor); delete query.offset; query.cursor = cursor; } } export function recordPages(key: string, dataset: D, filters: DatasetFilters[D] = {}, options: StreamOptions = {}): AsyncGenerator> { return cursorPages(query => listRecords(key, dataset, query), filters, options); } export function contractorHistoryPages(key: string, contractorId: string, filters: HistoryFilters = {}, options: StreamOptions = {}): AsyncGenerator { return cursorPages(query => contractorHistory(key, contractorId, query), filters, options); } export interface DatasetFilters { projects: ProjectFilters; permits: PermitFilters; bids: BidFilters } // Record and filter types from OpenAPI. Regenerate with scripts/developer-tools/sync-types.py. export interface Address { street?: string | null; city?: string | null; state?: string; zip?: string | null; county?: string | null; } export type LatLng = {latitude?: number; longitude?: number} | null; export interface Party { role?: "contractor" | "owner" | "developer"; id?: string | null; name?: string | null; } export interface Project { id?: string; slug?: string | null; name?: string | null; project_type?: string | null; status?: string | null; filed_date?: string | null; last_activity_date?: string | null; ingested_at?: string | null; changed_at?: string | null; estimated_value?: number | null; estimated_value_basis?: "sum_of_filed_estimates"; estimated_value_excluded?: number | null; square_feet?: number | null; unit_count?: number | null; lot_count?: number | null; acreage?: number | null; address?: Address; location?: LatLng; parties?: Array; source_counts?: {tdlr?: number; permit?: number; site_plan?: number; subdivision?: number}; coverage?: Array<"tdlr" | "permit" | "site_plan" | "subdivision">; source?: {name?: string; url?: string | null}; } export interface Permit { id?: string; permit_number?: string | null; jurisdiction?: string; permit_type?: string | null; permit_type_description?: string | null; permit_class?: string | null; work_class?: string | null; description?: string | null; status?: string | null; is_final?: boolean | null; is_closed?: boolean | null; issued_date?: string | null; finaled_date?: string | null; valuation?: number | null; address?: Address; location?: LatLng; contractor?: {id?: null; name?: string; tdlr_license?: null} | null; council_district?: number | null; ingested_at?: string | null; source?: {name?: string; url?: string; record_url?: string | null; retrieved_at?: string | null}; } export interface Bid { id?: string; solicitation_number?: string; type?: string | null; title?: string | null; status?: string | null; description?: string | null; agency?: {id?: string | null; name?: string | null}; posted_date?: string | null; posting_date?: string | null; ingested_at?: string | null; due_date?: string | null; response_due_on?: string | null; response_due_at?: string | null; due_time?: string | null; pre_bid_date?: string | null; class_item_codes?: Array; nigp_codes?: Array; naics_codes?: Array; counties?: Array; posting_requirement?: string | null; estimated_cost?: number | null; estimated_value?: number | null; bond_required?: boolean | null; construction_category?: string | null; addenda_count?: number; location?: {address?: string | null; city?: string | null; county?: string | null; state?: string | null; latitude?: number | null; longitude?: number | null}; award?: {awardee_name?: string; awardee_names?: Array; amount?: number | null; contractor_id?: string | null; history_url?: string | null} | null; source_url?: string | null; portal_url?: string | null; source?: {key?: "esbd" | "austin_afo" | "txdot" | "sam_gov" | "unknown"; name?: string; url?: string | null; record_url?: string | null}; } export interface VerifyMatch { filing_evidence: ContractorFilingEvidence; confidence?: number; risk_flags?: Array<"dormant" | "no_verified_work" | "name_churn">; licenses?: Array; entity?: {id?: string; slug?: string | null; name?: string | null; canonical_name?: string | null; types?: Array; business_type?: string | null; city?: string | null; county?: string | null; state?: string; reported_state?: string | null; zip?: string | null; name_variants_merged?: number | null}; matched_on?: "name" | "license"; matched_value?: string; tdlr?: {registered_projects?: number; last_registered_project_date?: string | null; activity_status?: "active" | "dormant" | "unknown"; license_verified?: false; license_note?: string; registry_url?: string}; work_history?: {project_count?: number; verified_project_count?: number; active_projects?: number; total_value?: number | null; first_activity_date?: string | null; last_activity_date?: string | null; counties_active?: number; counties?: Array; top_counties?: Array<{county?: string | null; project_count?: number; last_project_date?: string | null}>; by_source?: {permit?: number; site_plan?: number; subdivision?: number; tdlr?: number}; by_role?: {owner?: number; design_firm?: number; contractor?: number; developer?: number}}; govcon?: {sam_registered?: boolean; reported_sam_registered?: boolean | null; uei?: string | null; certifications?: Array; primary_naics?: string | null; naics_codes?: Array}; provenance?: Array; history_url?: string; } export interface HistoryRecord { id?: string; contractor_id?: string; work_type?: "tdlr_project" | "permit" | "site_plan" | "subdivision" | null; classified_as?: string | null; role?: string | null; title?: string | null; city?: string | null; state?: string | null; value?: number | null; issued_date?: string | null; completed_date?: string | null; status?: string | null; source_reference?: string | null; } export interface ContractorFilingEvidence { method: "eligible-government-filings/v1"; scope: "complete" | "bounded"; distinct_filings: number; dated_filings: number; first_filing_date: string | null; last_filing_date: string | null; pattern: "none_observed" | "single_filing" | "multiple_filings_one_date" | "multiple_filing_dates" | "dates_incomplete"; by_source: {permit: number; site_plan: number; subdivision: number; tdlr: number}; roles: Array<{role: string; filings: number}>; citations: Array<{source: "permit" | "site_plan" | "subdivision" | "tdlr"; reference: string; filing_date: string | null; role: string | null}>; } export interface ProjectFilingInsight { method: "project_filing_activity/v1"; coverage: "complete_link_scan" | "recent_100_links"; verified_filing_count: number; source_counts: {tdlr: number; permit: number; site_plan: number; subdivision: number}; permit_evidence: "issued_permit_observed" | "permit_record_without_issue_date" | "no_permit_record_observed"; latest_filing: {source: "tdlr" | "permit" | "site_plan" | "subdivision"; reference: string; date: string; date_basis: "tdlr_registration" | "permit_issue" | "application_start"} | null; valuation: {positive_estimate_count: number; repeated_across_sources: boolean; largest_filed_estimate: {source: "tdlr" | "permit"; reference: string; amount_usd: number} | null} | null; registration_to_permit: {registration: {source: "tdlr" | "permit" | "site_plan" | "subdivision"; reference: string; date: string; date_basis: "tdlr_registration" | "permit_issue" | "application_start"}; permit: {source: "tdlr" | "permit" | "site_plan" | "subdivision"; reference: string; date: string; date_basis: "tdlr_registration" | "permit_issue" | "application_start"}; days_between: number} | null; } export type PermitProjectInsight = {method: "permit_project_filing/v1"; status: "linked_registration"; project_id: string; registration: {reference: string; date: string; days_to_permit: number}} | {method: "permit_project_filing/v1"; status: "project_only"; project_id: string; registration: null} | {method: "permit_project_filing/v1"; status: "no_supported_link" | "issuer_not_covered"; project_id: null; registration: null}; export interface BidInsight { response_window: "upcoming" | "due_today_confirm_time" | "past_due_still_posted" | "agency_closed" | "not_a_response_notice" | "verify_source"; response_window_verification_reason: "no_response_date" | "posting_date_conflict" | "status_unconfirmed" | "source_clock_unavailable" | "source_clock_stale" | "issuer_time_zone_unconfirmed" | "no_observation_after_deadline" | null; as_of_date: string; source_checked_at: string | null; days_until_due: number | null; precedent: {state: "matched" | "no_match" | "insufficient_basis"; window_start: string | null; before: string | null; matched_notice_count: number | null; examples: Array<{id: string; posting_date: string; shared_nigp_codes: Array; source_url: string | null}>}; } export type PlatBenchmark = {method: "same_edition_county_cohort_v1"; minimum_peers: 10; status: "available"; county: string; peer_plat_count: number; peer_q1_appraised_psf: number; peer_median_appraised_psf: number; peer_q3_appraised_psf: number; difference_from_peer_median_psf: number; position: "below_middle_half" | "within_middle_half" | "above_middle_half"} | {method: "same_edition_county_cohort_v1"; minimum_peers: 10; status: "unavailable"; county: string | null; peer_plat_count: number; reason: "county_unreported" | "insufficient_peers"}; export interface ProjectFilters { limit?: number; offset?: number; cursor?: string; county?: string; city?: string; zip?: string; project_type?: string; type?: string; filed_after?: string; filed_before?: string; contractor_id?: string; status?: string; min_value?: number; max_value?: number; active_after?: string; added_since?: string; changed_since?: string; q?: string; sort?: "last_activity" | "first_activity" | "valuation"; } export interface PermitFilters { limit?: number; offset?: number; cursor?: string; city?: string; county?: string; zip?: string; issued_after?: string; issued_before?: string; permit_type?: string; type?: string; status?: string; min_valuation?: number; address?: string; q?: string; added_since?: string; } export interface BidFilters { limit?: number; offset?: number; cursor?: string; agency?: string; county?: string; city?: string; status?: string; type?: "solicitation" | "award" | "pre_solicitation" | "grant"; naics?: string; class_code?: string; nigp_code?: string; min_value?: number; due_after?: string; due_before?: string; posted_after?: string; added_since?: string; construction_only?: "true" | "false" | boolean; q?: string; sort?: "due_date" | "posted" | "value"; } export interface HistoryFilters { limit?: number; offset?: number; cursor?: string; work_type?: "tdlr_project" | "permit" | "site_plan" | "subdivision"; record_type?: "project" | "permit" | "site_plan" | "subdivision" | "bid" | "award"; role?: "owner" | "applicant" | "contractor" | "design_firm" | "developer"; since?: string; until?: string; min_value?: number; sort?: "recent" | "oldest" | "value"; } export interface VerifyFilters { name?: string; license?: string; county?: string; city?: string; address?: string; trade?: string; min_confidence?: number; limit?: number; }