import { d as ErrorCode, R as ResponseMeta, f as RouteDefinition, e as OpenAPIObject, h as ApiKeyService, W as WithApiKeyOptions, A as ApiKey, a as ApiKeyValidator, i as RateLimitService, j as WithRateLimitOptions } from './permission_failure-BVs18ugU.js'; export { b as AuthMode, E as EnvelopeResponse, c as ErrorBody, k as ErrorCodes, F as FailResponse, H as HttpMethod, I as IssuedApiKey, O as OkResponse, P as PermissionFailureDetails, l as RateLimitConsumeInput, m as RateLimitResult, g as RouteResponseSpec } from './permission_failure-BVs18ugU.js'; import { z } from 'zod'; import { HazoConnectAdapter } from 'hazo_connect/server'; declare function ok(data: T, opts?: { status?: number; meta?: Partial; }): Response; declare function fail(code: ErrorCode | (string & {}), message: string, opts?: { details?: unknown; status?: number; meta?: Partial; }): Response; interface Logger { info: (msg: string, data?: Record) => void; warn: (msg: string, data?: Record) => void; error: (msg: string, data?: Record) => void; debug: (msg: string, data?: Record) => void; } /** * HTTP-specific request context fields (extends hazo_core's HazoContext * which supplies correlationId and userId via the shared ALS). */ interface RequestContext { /** Primary correlation ID — same value as hazo_core's correlationId. */ correlationId: string; /** Backwards-compatibility alias for correlationId. */ request_id: string; start_time: number; logger: Logger; elapsed_ms: () => number; } /** * Read the current request context. Prefers hazo_core's shared context store * (which carries correlationId + our HTTP-specific fields) and falls back to * the local AsyncLocalStorage if the call ran outside `withRequestContext`. */ declare function getRequestContext(): RequestContext | undefined; /** * Wrap a Next.js / Web-standard route handler with request context. * * - Reads `X-Request-Id` from the incoming request header. * - Generates a new ID if none is present (via hazo_core.generateRequestId * when available, otherwise a local UUID). * - Calls hazo_core.withContext({ correlationId }) so the correlation ID is * shared across hazo_logs, hazo_files, etc. * - Stores HTTP-specific fields (start_time, logger, elapsed_ms) in the same * context object so getRequestContext() returns them. * - Falls back to the local ALS when hazo_core is absent. */ declare function withRequestContext(handler: (req: Request, ...args: TArgs) => Promise | Response): (req: Request, ...args: TArgs) => Promise; declare function defineRoute(opts: RouteDefinition): RouteDefinition; declare function getAllRoutes(): RouteDefinition[]; declare function resetRouteRegistry(): void; interface GenerateOpenAPIOptions { info: { title: string; version: string; description?: string; }; servers: Array<{ url: string; description?: string; }>; routes: RouteDefinition[]; } declare function generateOpenAPI(opts: GenerateOpenAPIOptions): OpenAPIObject; interface FieldIssue { field: string; issue: string; } declare function zodIssuesToDetails(issues: ReadonlyArray): FieldIssue[]; /** * Shared opaque-cursor codec for keyset pagination. * * Several consuming apps had independently reinvented the exact same * "base64(JSON.stringify(payload))" envelope for a pagination cursor, each * with its own encode/decode pair and its own thrown error class on a * malformed cursor. This factors out the shared mechanics (base64/JSON * round-trip, catching any decode/parse failure) while leaving each caller * free to keep its own payload shape and its own error type — `onInvalid` * is the caller's error, not a new generic one, so existing * `instanceof SomeAppSpecificCursorError` checks at call sites keep working * unchanged after adopting this. */ declare function encodeCursor(payload: T): string; /** * Decodes a cursor produced by `encodeCursor`. * * `validate` receives the parsed JSON (typed `unknown`) and must return the * typed payload, or throw/return a signal the caller recognizes as invalid * — in practice, just narrow and return, or throw. Any failure anywhere in * the pipeline (malformed base64, invalid JSON, or `validate` throwing) * calls `onInvalid(cursor)`, which must throw (typed `never`) so every * `decodeCursor` call always either returns `T` or throws the caller's own * error. */ declare function decodeCursor(cursor: string, validate: (parsed: unknown) => T, onInvalid: (cursor: string) => never): T; interface ApiConfig { api: { version: string; mode: 'internal' | 'public'; }; logging: { enabled: boolean; level: 'error' | 'warn' | 'info' | 'debug'; redact_headers: string[]; }; debug: { enabled: boolean; }; swagger_ui: { cdn: string; version: string; }; auth: { key_prefix: string; bind_user_default: boolean; }; rate_limit: { default_limit: number; default_window_sec: number; }; } declare const DEFAULTS: ApiConfig; type IniSection = Record; type IniData = Record; interface ResolveApiConfigOptions { skipFileLoad?: boolean; overlay?: IniData; } declare function resolveApiConfig(opts?: ResolveApiConfigOptions): Promise; declare function resetApiConfigCache(): void; interface CreateAuthServiceOptions { getHazoConnect: () => Promise | unknown; table_name?: string; key_prefix?: string; } declare function createApiKeyService(opts: CreateAuthServiceOptions): ApiKeyService; interface CreatePostgrestApiKeyServiceOptions { postgrest_url: string; postgrest_api_key?: string; table_name?: string; key_prefix?: string; } declare function createPostgrestApiKeyService(opts: CreatePostgrestApiKeyServiceOptions): ApiKeyService; declare function withApiKey(opts: WithApiKeyOptions, handler: (req: Request, key: ApiKey, ...args: TArgs) => Promise | Response): (req: Request, ...args: TArgs) => Promise; declare function createVerifyOnlyService(verify: ApiKeyValidator): ApiKeyService; interface CreateApiKeyRoutesOptions { service: ApiKeyService; } declare function createApiKeyRoutes(opts: CreateApiKeyRoutesOptions): { list: (req: Request) => Promise; create: (req: Request) => Promise; revoke: (req: Request, ctx: { params: { id: string; }; }) => Promise; update: (req: Request, ctx: { params: { id: string; }; }) => Promise; }; interface CreateRateLimitServiceOptions { /** * Returns either: * - a raw hazo_connect adapter directly (anything exposing `.raw(sql, * params)` returning rows and `.getConfig()` returning `{type}`, e.g. * hazo_connect's `PgAdapter`/`BetterSqlite3Adapter`) — detected and * used as-is, no shim needed. * - the legacy `{dialect, query(sql, params) => {rows}}` shape, for * callers that already have (or want) their own thin wrapper. */ getHazoConnect: () => Promise | unknown; table_name?: string; } declare function createRateLimitService(opts: CreateRateLimitServiceOptions): RateLimitService; interface CreateHazoConnectRateLimitServiceOptions { getHazoConnect: () => HazoConnectAdapter | Promise; table_name?: string; } /** * PostgREST-compatible token-bucket rate limiter. * * `createRateLimitService` (rate_limit_service.ts) needs a raw-SQL adapter * (`{dialect, query(sql, params)}`) to do its atomic single-UPDATE * refill-and-deduct. Consuming apps that only have PostgREST (REST-only, no * raw Postgres connection at runtime) can't supply that adapter. This * factory gets the same token-bucket semantics over `HazoConnectAdapter` * instead, using a prior read + an optimistic-concurrency (CAS) conditional * write rather than a single atomic UPDATE. * * ## Why this does NOT use `HazoConnectAdapter.claimRows` * * The design this was built from assumed `claimRows` (hazo_connect's * atomic-claim primitive) could be pointed at this table via * `idColumn: 'bucket_key'`. Reading the real source * (`hazo_connect/src/lib/adapters/postgrest-adapter.ts`, * `claimRows()` ~line 484) shows `PostgrestAdapter.claimRows` hardcodes the * `id` column for both the candidate SELECT (`candidateSelectCols = ['id', * ...incCols]`) and the claim PATCH (`id: eq.${String(cand.id)}`) — the * `idColumn` option on `ClaimRowsOptions` is explicitly documented as * "currently honored by SqliteAdapter (sql.js) and BetterSqlite3Adapter * only — PgAdapter and PostgrestAdapter still hardcode 'id' and ignore this * option if set" (`hazo_connect/src/lib/types.ts` ~line 282). This table's * schema (`hazo_api_rate_limits` / chartomatic's `app_rate_limits`) has * `bucket_key` as its only key column and no `id` column at all, so * `claimRows` would select a nonexistent `id` column and fail outright * against a PostgREST backend — not just be unsafe, but mechanically * broken for this table. * * Instead, this uses `createCrudService(...).query()` — the same * `QueryBuilder` + `HazoConnectAdapter.query()` primitive `claimRows` * itself is built on, minus the `id`-column assumption — to issue a plain * conditional `PATCH`: `WHERE bucket_key = :bucket_key AND updated_at = * :observed_updated_at`. `PostgrestAdapter.query()` serializes `where()` * conditions generically (no hardcoded column names), and a PATCH whose * WHERE no longer matches the live row (because a concurrent request already * changed `updated_at`) returns an empty array rather than throwing — this * is exactly the CAS-miss signal `claimRows` itself relies on, just without * requiring an `id` column. * * Row creation uses `.onConflict(['bucket_key']).doNothing()` (PostgREST * `Prefer: resolution=ignore-duplicates`) rather than `insert()` + a * catch-the-unique-violation-error, because `hazo_connect`'s * `BaseAdapter.throwError` (`hazo_connect/src/lib/adapters/base-adapter.ts`) * maps every PostgREST 4xx/5xx query failure to the same * `HazoInternalError` / `HAZO_CONNECT_QUERY_ERROR` code and drops the * original HTTP status (the `_statusCode` parameter is accepted but never * attached to the thrown error) — there is no reliable, non-message-sniffing * way to distinguish "row already exists" from any other query failure. * `doNothing()` sidesteps that: on conflict, PostgREST just omits the row * from the response instead of erroring, matching the raw-SQL version's * `INSERT ... ON CONFLICT DO NOTHING`. */ declare function createHazoConnectRateLimitService(opts: CreateHazoConnectRateLimitServiceOptions): RateLimitService; declare function withRateLimit(opts: WithRateLimitOptions, handler: (req: Request, ...args: TArgs) => Promise | Response): (req: Request, ...args: TArgs) => Promise; interface OkStreamOptions { format: 'sse' | 'ndjson'; status?: number; meta?: Partial; } declare function okStream(iterable: AsyncIterable | Iterable, opts: OkStreamOptions): Response; export { type ApiConfig, DEFAULTS as ApiConfigDefaults, ApiKey, ApiKeyService, ApiKeyValidator, type CreateApiKeyRoutesOptions, type CreateAuthServiceOptions, type CreateHazoConnectRateLimitServiceOptions, type CreatePostgrestApiKeyServiceOptions, type CreateRateLimitServiceOptions, ErrorCode, type FieldIssue, type GenerateOpenAPIOptions, type OkStreamOptions, OpenAPIObject, RateLimitService, ResponseMeta, RouteDefinition, WithApiKeyOptions, WithRateLimitOptions, createApiKeyRoutes, createApiKeyService, createHazoConnectRateLimitService, createPostgrestApiKeyService, createRateLimitService, createVerifyOnlyService, decodeCursor, defineRoute, encodeCursor, fail, generateOpenAPI, getAllRoutes, getRequestContext, ok, okStream, resetApiConfigCache, resetRouteRegistry, resolveApiConfig, withApiKey, withRateLimit, withRequestContext, zodIssuesToDetails };