@secondlayer/sdk 14.0.0 → 14.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -251,7 +251,9 @@ function parseErrorEnvelope(text) {
251
251
  let code;
252
252
  if (json && typeof json === "object") {
253
253
  const err = json.error ?? json.message;
254
- if (typeof err === "string" && err.length > 0)
254
+ if (typeof err === "string" && typeof json.message === "string" && json.message.length > 0) {
255
+ message = json.message;
256
+ } else if (typeof err === "string" && err.length > 0)
255
257
  message = err;
256
258
  else if (err && typeof err === "object")
257
259
  message = JSON.stringify(err);
@@ -1601,5 +1603,5 @@ export {
1601
1603
  isStxTransfer
1602
1604
  };
1603
1605
 
1604
- //# debugId=80C188DCCCC86F1064756E2164756E21
1606
+ //# debugId=F2E7E752B64FBB0D64756E2164756E21
1605
1607
  //# sourceMappingURL=index.js.map
@@ -4,7 +4,7 @@
4
4
  "sourcesContent": [
5
5
  "import { ed25519 } from \"@secondlayer/shared\";\nimport { buildQuery, resolveApiKey, resolveBaseUrl } from \"../base.ts\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { ConsumerSink } from \"../sinks/types.ts\";\nimport {\n\ttype StreamsEventsFetcher,\n\tconsumeStreamsEvents,\n\titerateStreamsBatches,\n\tstreamStreamsEvents,\n} from \"./consumer.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { decode } from \"./decode.ts\";\nimport { createStreamsDumps } from \"./dumps.ts\";\nimport {\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tValidationError,\n\tmapStreamsError,\n} from \"./errors.ts\";\nimport {\n\ttype StreamsEventsSubscribeWireParams,\n\tsubscribeStreamsEvents,\n} from \"./subscribe.ts\";\nimport type {\n\tFetchLike,\n\tStreamsBatch,\n\tStreamsCanonicalBlock,\n\tStreamsClient,\n\tStreamsConsumeParams,\n\tStreamsEvent,\n\tStreamsEventsConsumeBitcoinParams,\n\tStreamsEventsConsumeParams,\n\tStreamsEventsConsumeResult,\n\tStreamsEventsEnvelope,\n\tStreamsEventsListEnvelope,\n\tStreamsEventsListParams,\n\tStreamsEventsReplayParams,\n\tStreamsEventsStreamParams,\n\tStreamsEventsSubscribeParams,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorgsListEnvelope,\n\tStreamsReorgsListParams,\n\tStreamsSubscription,\n\tStreamsTip,\n} from \"./types.ts\";\n\n/** Parse a `<block>:<index>` cursor; null sorts before genesis. */\nfunction cursorTuple(cursor: string | null): [number, number] {\n\tif (!cursor) return [-1, -1];\n\tconst { blockHeight, eventIndex } = Cursor.parse(cursor);\n\treturn [blockHeight, eventIndex];\n}\n\n/** The greater of two cursors (later in the stream). */\nfunction maxCursor(a: string | null, b: string | null): string | null {\n\tconst [ah, ai] = cursorTuple(a);\n\tconst [bh, bi] = cursorTuple(b);\n\treturn ah > bh || (ah === bh && ai >= bi) ? a : b;\n}\n\n/**\n * The narrowing set every Streams read forwards verbatim to the consumer\n * loops. Kept in one place because each field is optional: a forgotten one is\n * a type-checkable object that silently widens the stream toward the full\n * firehose — which is billed per row, and has happened. `events.replay()`\n * deliberately forwards a subset and stays explicit.\n */\nfunction streamsFilters(params: {\n\tchain?: \"stacks\" | \"bitcoin\";\n\t// `readonly string[]`, not `StreamsEventType[]`: this helper is shared by\n\t// the Stacks and Bitcoin branches, whose `types` element types (\n\t// `StreamsEventType` vs `RuneEventType`) are disjoint. It forwards the\n\t// field verbatim with no type-based logic, so the wider type costs nothing.\n\ttypes?: readonly string[];\n\tnotTypes?: readonly string[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\trune?: string;\n\taddress?: string;\n\tfilters?: StreamsFilterMap;\n}) {\n\treturn {\n\t\tchain: params.chain,\n\t\ttypes: params.types,\n\t\tnotTypes: params.notTypes,\n\t\tcontractId: params.contractId,\n\t\tsender: params.sender,\n\t\trecipient: params.recipient,\n\t\tassetIdentifier: params.assetIdentifier,\n\t\trune: params.rune,\n\t\taddress: params.address,\n\t\tfilters: params.filters,\n\t};\n}\n\nexport type CreateStreamsClientOptions = {\n\tapiKey?: string;\n\tbaseUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\tfetchImpl?: FetchLike;\n\t/**\n\t * Public base URL for bulk parquet dumps (the R2/CDN bucket root). Required\n\t * to use `client.dumps`. See `GET /public/streams/dumps/manifest`.\n\t */\n\tdumpsBaseUrl?: string;\n\t/**\n\t * Verify the ed25519 `X-Signature` on every REST response and per-frame SSE\n\t * signature. Three states:\n\t * - **default (omitted)** — *lenient*: verify when the server signs (the\n\t * hosted API signs every response), and pass through when no signature is\n\t * present (e.g. a self-hosted instance with no `STREAMS_SIGNING_PRIVATE_KEY`).\n\t * So verification is on by default against the hosted API without breaking\n\t * unsigned self-host deployments. An *invalid* signature always throws.\n\t * - **`true`** (or `{ publicKey }` to pin a known PEM) — *strict*: a missing\n\t * OR invalid signature throws `StreamsSignatureError`. Use this when you\n\t * require a portable, non-repudiable attestation and won't accept unsigned\n\t * data (it also closes the lenient mode's strip-the-header downgrade).\n\t * - **`false`** — off.\n\t *\n\t * The key is fetched once from `/public/streams/signing-key` (cached; a\n\t * rotated `X-Signature-KeyId` triggers one refresh) unless a PEM is pinned.\n\t */\n\tverify?: boolean | { publicKey: string };\n\t/**\n\t * Verify the bulk dumps manifest's ed25519 signature in `client.dumps.list()`\n\t * before trusting any file sha256 (default ON). Uses the same key source as\n\t * `verify` (fetches `/public/streams/signing-key`, or a pinned PEM). Pass\n\t * `false` to opt out. A missing or invalid signature throws\n\t * `StreamsSignatureError`.\n\t */\n\tverifyDumpsManifest?: boolean;\n};\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\n/** Loopback hosts, where plain http carries no more exposure than the box\n * itself. Anywhere else, http means a network hop anyone on the path can\n * rewrite, key endpoint included. */\nfunction isLoopbackUrl(baseUrl: string): boolean {\n\ttry {\n\t\tconst { hostname } = new URL(baseUrl);\n\t\treturn (\n\t\t\thostname === \"localhost\" ||\n\t\t\thostname === \"127.0.0.1\" ||\n\t\t\thostname === \"::1\" ||\n\t\t\thostname === \"[::1]\" ||\n\t\t\thostname.startsWith(\"127.\")\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function createStreamsClient(\n\toptions: CreateStreamsClientOptions,\n): StreamsClient {\n\tconst baseUrl = normalizeBaseUrl(resolveBaseUrl(options.baseUrl));\n\t// Same credential precedence as every other client (explicit option, then\n\t// INSTANCE_TOKEN, then SECONDLAYER_API_KEY), so the same code authenticates\n\t// the same way whether it enters through `new SecondLayer()` or here.\n\tconst apiKey = resolveApiKey(options.apiKey);\n\tconst origin = options.origin ?? \"cli\";\n\tconst authHeaders = (): Record<string, string> => ({\n\t\t\"x-sl-origin\": origin,\n\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t});\n\tconst fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));\n\tconst verify = options.verify;\n\t// On by default, but lenient: the hosted API signs every response, while a\n\t// self-hosted instance without STREAMS_SIGNING_PRIVATE_KEY serves none.\n\t// Lenient verifies when a signature is present and passes through when it is\n\t// absent — so the default neither skips hosted verification nor breaks OSS.\n\t// `verify: true` / `{ publicKey }` is strict (missing signature throws);\n\t// `verify: false` is off. An invalid signature always throws.\n\tconst verifyMode: \"off\" | \"lenient\" | \"strict\" =\n\t\tverify === false ? \"off\" : verify === undefined ? \"lenient\" : \"strict\";\n\t// Strict mode promises the response came from the holder of a known key.\n\t// A key fetched over plain http from a host off the box is whatever the\n\t// path served, so the promise only holds with a pinned PEM there.\n\tif (\n\t\tverify === true &&\n\t\tbaseUrl.startsWith(\"http:\") &&\n\t\t!isLoopbackUrl(baseUrl)\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`verify: true over plain http to ${baseUrl} fetches the signing key from the same unprotected path it verifies. Pin the key with verify: { publicKey } (see GET /public/streams/signing-key), or use https.`,\n\t\t\t400,\n\t\t);\n\t}\n\n\t// Lazily resolve and cache the verification key alongside its id, so a\n\t// rotation (signalled by a changed `X-Signature-KeyId`) can be detected.\n\ttype VerificationKey = {\n\t\tkeyId: string;\n\t\tpublicKeyPem: string;\n\t\tpublicKey: ReturnType<typeof ed25519.loadEd25519PublicKey>;\n\t};\n\t// Only a successful fetch stays cached. A 5xx or a dropped socket on the\n\t// key endpoint used to park a rejected promise here for the life of the\n\t// client; now it surfaces as a retryable error and the next call refetches.\n\tlet keyPromise: Promise<VerificationKey> | null = null;\n\tfunction loadKey(): Promise<VerificationKey> {\n\t\tif (keyPromise) return keyPromise;\n\t\tconst pending = (async () => {\n\t\t\tif (typeof verify === \"object\") {\n\t\t\t\treturn {\n\t\t\t\t\tkeyId: ed25519.ed25519KeyId(verify.publicKey),\n\t\t\t\t\tpublicKeyPem: verify.publicKey,\n\t\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(verify.publicKey),\n\t\t\t\t};\n\t\t\t}\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetchImpl(`${baseUrl}/public/streams/signing-key`);\n\t\t\t} catch {\n\t\t\t\tthrow new StreamsServerError(\n\t\t\t\t\t`Could not reach the signing key at ${baseUrl}/public/streams/signing-key. Retryable.`,\n\t\t\t\t\t0,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"SIGNING_KEY_UNAVAILABLE\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (res.status >= 500 || res.status === 429) {\n\t\t\t\t\tthrow new StreamsServerError(\n\t\t\t\t\t\t`Could not fetch signing key (${res.status}). Retryable.`,\n\t\t\t\t\t\tres.status,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\"SIGNING_KEY_UNAVAILABLE\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t`Could not fetch signing key (${res.status}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst body = (await res.json()) as {\n\t\t\t\tpublic_key_pem?: string;\n\t\t\t\tkey_id?: string;\n\t\t\t};\n\t\t\tif (!body.public_key_pem) {\n\t\t\t\tthrow new StreamsSignatureError(\"Signing key response missing key.\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkeyId: body.key_id ?? ed25519.ed25519KeyId(body.public_key_pem),\n\t\t\t\tpublicKeyPem: body.public_key_pem,\n\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(body.public_key_pem),\n\t\t\t};\n\t\t})();\n\t\tkeyPromise = pending;\n\t\tpending.catch(() => {\n\t\t\tif (keyPromise === pending) keyPromise = null;\n\t\t});\n\t\treturn pending;\n\t}\n\t/** Resolve the key a response claims to be signed with. A fetched key\n\t * refreshes once on an unknown id; a pinned key never changes, so an\n\t * unknown id is a failure either way. Shared by REST reads and SSE frames. */\n\tasync function loadKeyFor(\n\t\tresponseKeyId: string | null | undefined,\n\t): Promise<VerificationKey> {\n\t\tlet key = await loadKey();\n\t\tif (!responseKeyId || responseKeyId === key.keyId) return key;\n\t\tif (typeof verify === \"object\") {\n\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t`Response signed with key '${responseKeyId}', expected pinned key '${key.keyId}'.`,\n\t\t\t);\n\t\t}\n\t\t// Refresh once. A still-mismatched id (no re-loop) means the endpoint\n\t\t// does not serve the signing key: fail closed.\n\t\tkeyPromise = null;\n\t\tkey = await loadKey();\n\t\tif (responseKeyId !== key.keyId) {\n\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t`Response signed with key '${responseKeyId}' not served by the signing-key endpoint.`,\n\t\t\t);\n\t\t}\n\t\treturn key;\n\t}\n\n\tconst dumps = createStreamsDumps({\n\t\tbaseUrl: options.dumpsBaseUrl,\n\t\tfetchImpl,\n\t\tverifyManifest: options.verifyDumpsManifest ?? true,\n\t\tloadPublicKeyPem: async () => (await loadKey()).publicKeyPem,\n\t});\n\n\tasync function request<T>(path: string): Promise<T> {\n\t\tconst response = await fetchImpl(`${baseUrl}${path}`, {\n\t\t\theaders: authHeaders(),\n\t\t});\n\t\tif (!response.ok) await mapStreamsError(response);\n\t\tconst text = await response.text();\n\t\tif (verifyMode !== \"off\") {\n\t\t\tconst signature = response.headers.get(\"X-Signature\");\n\t\t\tif (!signature) {\n\t\t\t\t// Strict requires a signature; lenient (default) lets an unsigned\n\t\t\t\t// response through — e.g. self-host with no signing key configured.\n\t\t\t\tif (verifyMode === \"strict\") {\n\t\t\t\t\tthrow new StreamsSignatureError(\"Response is missing X-Signature.\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst key = await loadKeyFor(response.headers.get(\"X-Signature-KeyId\"));\n\t\t\t\t// A signature is present, so verify it regardless of strict/lenient —\n\t\t\t\t// an invalid signature always fails closed.\n\t\t\t\tif (!ed25519.verifyEd25519(text, signature, key.publicKey)) {\n\t\t\t\t\tthrow new StreamsSignatureError();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn JSON.parse(text) as T;\n\t}\n\n\t// StreamsEventsFetchParams was a strict subset of StreamsEventsListParams\n\t// pre-059; `chain: \"bitcoin\"` narrows `types` to RuneEventType there, so a\n\t// plain cast replaces the old structural assignment for this one generic\n\t// entry point shared by consume/stream (untyped across chains — see\n\t// `StreamsEventsStreamParams.chain`'s doc comment).\n\tconst fetchEvents: StreamsEventsFetcher = (params) =>\n\t\tlistEvents(params as StreamsEventsListParams);\n\n\tfunction byTxId(txId: string, opts?: { chain?: \"stacks\" | \"bitcoin\" }) {\n\t\treturn request<StreamsEventsListEnvelope>(\n\t\t\t`/v1/streams/events/${encodeURIComponent(txId)}${buildQuery({\n\t\t\t\tchain: opts?.chain === \"bitcoin\" ? \"bitcoin\" : undefined,\n\t\t\t})}`,\n\t\t);\n\t}\n\n\tfunction listReorgs(\n\t\tparams: StreamsReorgsListParams & { chain?: \"stacks\" | \"bitcoin\" },\n\t) {\n\t\treturn request<StreamsReorgsListEnvelope>(\n\t\t\t`/v1/streams/reorgs${buildQuery({\n\t\t\t\tchain: params.chain === \"bitcoin\" ? \"bitcoin\" : undefined,\n\t\t\t\tsince: params.since,\n\t\t\t\tlimit: params.limit,\n\t\t\t})}`,\n\t\t);\n\t}\n\t// Idle-tip reorg detection for the consume loop (one request per empty\n\t// page); the public `reorgs.list` is the same call.\n\tconst fetchReorgs = (params: { since: string }) => listReorgs(params);\n\n\tfunction encodeFilters(filters: StreamsFilterMap | undefined) {\n\t\treturn filters ? JSON.stringify(filters) : undefined;\n\t}\n\n\tasync function listEvents(\n\t\tparams: StreamsEventsListParams = {},\n\t): Promise<StreamsEventsEnvelope> {\n\t\tif (params.chain === \"bitcoin\") {\n\t\t\treturn request<StreamsEventsEnvelope>(\n\t\t\t\t`/v1/streams/events${buildQuery({\n\t\t\t\t\tchain: \"bitcoin\",\n\t\t\t\t\tcursor: params.cursor,\n\t\t\t\t\tfrom_height: params.fromHeight,\n\t\t\t\t\tto_height: params.toHeight,\n\t\t\t\t\tlimit: params.limit,\n\t\t\t\t\ttypes: params.types,\n\t\t\t\t\tnot_types: params.notTypes,\n\t\t\t\t\trune: params.rune,\n\t\t\t\t\taddress: params.address,\n\t\t\t\t})}`,\n\t\t\t);\n\t\t}\n\t\treturn request<StreamsEventsEnvelope>(\n\t\t\t`/v1/streams/events${buildQuery({\n\t\t\t\tcursor: params.cursor,\n\t\t\t\tfrom_height: params.fromHeight,\n\t\t\t\tto_height: params.toHeight,\n\t\t\t\tlimit: params.limit,\n\t\t\t\tcontract_id: params.contractId,\n\t\t\t\tsender: params.sender,\n\t\t\t\trecipient: params.recipient,\n\t\t\t\tasset_identifier: params.assetIdentifier,\n\t\t\t\ttypes: params.types,\n\t\t\t\tnot_types: params.notTypes,\n\t\t\t\t// `vm` reads ordinal; omitted = Streams 1.0 (server default).\n\t\t\t\tclock: params.clock === \"vm\" ? \"vm\" : undefined,\n\t\t\t\tfilters: encodeFilters(params.filters),\n\t\t\t})}`,\n\t\t);\n\t}\n\n\t/**\n\t * One signature, two shapes: a flat filter with `onBatch`, or a labelled\n\t * `filters` map with a handler per label (or both). Deliberately NOT\n\t * overloaded — an overloaded interface member strips contextual typing from\n\t * every stub and alternate implementation of `StreamsClient`.\n\t */\n\tfunction consumeEvents<\n\t\tconst F extends StreamsFilterMap = Record<never, never>,\n\t\tTTx = never,\n\t\tD extends boolean = false,\n\t>(\n\t\t// Redundant `sink` member: direct TTx inference site (inference\n\t\t// does not traverse the params alias).\n\t\tparams: StreamsEventsConsumeParams<TTx, D, F> & {\n\t\t\tsink?: ConsumerSink<TTx>;\n\t\t},\n\t): Promise<StreamsEventsConsumeResult> {\n\t\tconst labels = params.filters ? Object.keys(params.filters) : [];\n\t\t// The \"at least one handler\" rule is conditional on `filters`, so it\n\t\t// can't live in the type without making `F` uninferrable. Fail loudly\n\t\t// instead of consuming pages into nothing.\n\t\tif (labels.length === 0 && !params.onBatch) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"consume requires onBatch, or filters + on handlers.\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tif (labels.length > 0 && !params.on && !params.onBatch) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t\"consume with filters requires on handlers (or onBatch).\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst dispatch = params.on as\n\t\t\t| Record<\n\t\t\t\t\tstring,\n\t\t\t\t\t(\n\t\t\t\t\t\tevents: StreamsEvent[] | IndexEvent[],\n\t\t\t\t\t\tctx: Parameters<\n\t\t\t\t\t\t\tNonNullable<StreamsEventsConsumeParams<TTx>[\"onBatch\"]>\n\t\t\t\t\t\t>[2],\n\t\t\t\t\t) => void | Promise<void>\n\t\t\t >\n\t\t\t| undefined;\n\n\t\t// With `decoded: true`, events arrive as the flat Index-shaped rows —\n\t\t// decoding never appears in the handler.\n\t\tconst project = (events: StreamsEvent[]): StreamsEvent[] | IndexEvent[] =>\n\t\t\tparams.decoded ? events.map(decode) : events;\n\n\t\tconst onBatch: StreamsEventsConsumeParams<TTx>[\"onBatch\"] = async (\n\t\t\tevents,\n\t\t\tenvelope,\n\t\t\tctx,\n\t\t) => {\n\t\t\t// Label dispatch reads the wire `matched` array, so it has to run\n\t\t\t// BEFORE decode — the decoded row shape does not carry it.\n\t\t\tfor (const label of labels) {\n\t\t\t\tconst forLabel = events.filter((event) =>\n\t\t\t\t\tevent.matched?.includes(label),\n\t\t\t\t);\n\t\t\t\tif (forLabel.length === 0) continue;\n\t\t\t\tawait dispatch?.[label]?.(project(forLabel), ctx);\n\t\t\t}\n\t\t\t// The `decoded` flag is a runtime value here, so `project`'s return\n\t\t\t// can't be narrowed to the D-conditional the declared handler wants.\n\t\t\tconst userOnBatch = params.onBatch as StreamsEventsConsumeParams<\n\t\t\t\tTTx,\n\t\t\t\tboolean\n\t\t\t>[\"onBatch\"];\n\t\t\t// `onBatch`'s several legal return shapes collapse to one here: the\n\t\t\t// consume loop only ever reads a cursor string or nothing.\n\t\t\treturn (await userOnBatch?.(project(events), envelope, ctx)) as\n\t\t\t\t| string\n\t\t\t\t| null\n\t\t\t\t| undefined;\n\t\t};\n\n\t\treturn consumeStreamsEvents<TTx>({\n\t\t\tfromCursor: params.fromCursor,\n\t\t\tsink: params.sink,\n\t\t\tonProgress: params.onProgress,\n\t\t\tmode: params.mode,\n\t\t\tfinalizedOnly: params.finalizedOnly,\n\t\t\t...streamsFilters(params),\n\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\tfetchEvents,\n\t\t\tfetchReorgs,\n\t\t\tonBatch,\n\t\t\tonReorg: params.onReorg,\n\t\t\tmaxRollbackDepth: params.maxRollbackDepth,\n\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\tmaxPages: params.maxPages,\n\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\tsignal: params.signal,\n\t\t\tretryCount: params.retryCount,\n\t\t\tretryDelay: params.retryDelay,\n\t\t\tonError: params.onError,\n\t\t\twake: params.wake,\n\t\t});\n\t}\n\n\t// Top-level `consume` (page-batch iterator). One implementation shared by\n\t// both chains — `iterateStreamsBatches` isn't generic over the event type\n\t// (it just forwards whatever the wire returns), so this returns the wide\n\t// `AsyncGenerator<StreamsBatch>` and the public field below casts it to\n\t// `StreamsClient[\"consume\"]`'s richer, chain-narrowed overloads. Same\n\t// bridging pattern `listEvents` uses for `events.list`.\n\tfunction consumeBatches(\n\t\tparams: StreamsConsumeParams = {},\n\t): AsyncGenerator<StreamsBatch> {\n\t\treturn iterateStreamsBatches({\n\t\t\tfromCursor: params.cursor,\n\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\tintervalMs: params.intervalMs ?? 2000,\n\t\t\t...streamsFilters(params),\n\t\t\tsignal: params.signal,\n\t\t\tfetchEvents,\n\t\t});\n\t}\n\n\tfunction streamEvents(\n\t\tparams: StreamsEventsStreamParams = {},\n\t): AsyncIterable<StreamsEvent> {\n\t\treturn streamStreamsEvents({\n\t\t\tfromCursor: params.fromCursor,\n\t\t\t// Includes the labelled OR-groups: dropping them here silently\n\t\t\t// widened the stream to the FULL firehose (billed per row).\n\t\t\t...streamsFilters(params),\n\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\tmaxPages: params.maxPages,\n\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\tsignal: params.signal,\n\t\t\tfetchEvents,\n\t\t});\n\t}\n\n\tfunction subscribeEvents(\n\t\tparams: StreamsEventsSubscribeParams,\n\t): StreamsSubscription {\n\t\treturn subscribeStreamsEvents({\n\t\t\tbaseUrl,\n\t\t\theaders: authHeaders(),\n\t\t\tfetchImpl,\n\t\t\tverify: verifyMode,\n\t\t\tloadKey: loadKeyFor,\n\t\t\treconnectDelayMs: params.reconnectDelayMs,\n\t\t\tstaleAfterMs: params.staleAfterMs,\n\t\t\t// `StreamsEventsSubscribeParams` (Stacks | Bitcoin) narrows `onEvent`'s\n\t\t\t// parameter type per branch; the loop below reads every field off one\n\t\t\t// flat wire shape regardless of chain — see\n\t\t\t// `StreamsEventsSubscribeWireParams`'s doc comment.\n\t\t\tparams: params as unknown as StreamsEventsSubscribeWireParams,\n\t\t});\n\t}\n\n\t/**\n\t * `events.consume`'s bitcoin branch: a separate, simpler implementation\n\t * (no `filters`/`on`/`decoded`) rather than widening `consumeEvents`'s\n\t * generics — see {@link StreamsEventsConsumeBitcoinParams}'s doc comment.\n\t * Runtime loop is `consumeStreamsEvents`, same as the Stacks branch.\n\t */\n\tfunction consumeBitcoinEvents<TTx = never>(\n\t\tparams: StreamsEventsConsumeBitcoinParams<TTx> & {\n\t\t\tsink?: ConsumerSink<TTx>;\n\t\t},\n\t): Promise<StreamsEventsConsumeResult> {\n\t\treturn consumeStreamsEvents<TTx>({\n\t\t\tfromCursor: params.fromCursor,\n\t\t\tsink: params.sink,\n\t\t\tonProgress: params.onProgress,\n\t\t\tmode: params.mode,\n\t\t\tfinalizedOnly: params.finalizedOnly,\n\t\t\tchain: \"bitcoin\",\n\t\t\ttypes: params.types,\n\t\t\tnotTypes: params.notTypes,\n\t\t\trune: params.rune,\n\t\t\taddress: params.address,\n\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\tfetchEvents,\n\t\t\tfetchReorgs,\n\t\t\tonBatch: params.onBatch as unknown as NonNullable<\n\t\t\t\tStreamsEventsConsumeParams<TTx>[\"onBatch\"]\n\t\t\t>,\n\t\t\tonReorg: params.onReorg,\n\t\t\tmaxRollbackDepth: params.maxRollbackDepth,\n\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\tmaxPages: params.maxPages,\n\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\tsignal: params.signal,\n\t\t\tretryCount: params.retryCount,\n\t\t\tretryDelay: params.retryDelay,\n\t\t\tonError: params.onError,\n\t\t\twake: params.wake,\n\t\t});\n\t}\n\n\t/** Dispatches `events.consume` by `chain` to the Stacks (`consumeEvents`,\n\t * filters/on/decoded-capable) or Bitcoin (`consumeBitcoinEvents`, plain\n\t * `onBatch` only) implementation. Cast to the public overloaded type at\n\t * the field assignment below, same as every other chain-narrowed field. */\n\tfunction dispatchEventsConsume<TTx = never>(\n\t\tparams:\n\t\t\t| (StreamsEventsConsumeBitcoinParams<TTx> & { sink?: ConsumerSink<TTx> })\n\t\t\t| (StreamsEventsConsumeParams<TTx, boolean, StreamsFilterMap> & {\n\t\t\t\t\tsink?: ConsumerSink<TTx>;\n\t\t\t }),\n\t): Promise<StreamsEventsConsumeResult> {\n\t\tif (params.chain === \"bitcoin\") return consumeBitcoinEvents(params);\n\t\treturn consumeEvents(params);\n\t}\n\n\treturn {\n\t\tconsume: consumeBatches as StreamsClient[\"consume\"],\n\t\tevents: {\n\t\t\t// One wire call; the overloads narrow the row type by `clock`/`types`.\n\t\t\tlist: listEvents as StreamsClient[\"events\"][\"list\"],\n\t\t\tbyTxId: byTxId as StreamsClient[\"events\"][\"byTxId\"],\n\t\t\tconsume: dispatchEventsConsume as StreamsClient[\"events\"][\"consume\"],\n\t\t\tstream: streamEvents as StreamsClient[\"events\"][\"stream\"],\n\t\t\tsubscribe: subscribeEvents as StreamsClient[\"events\"][\"subscribe\"],\n\t\t\tasync replay(params: StreamsEventsReplayParams) {\n\t\t\t\tconst fromCursor =\n\t\t\t\t\tparams.from === \"genesis\" ? null : (params.from ?? null);\n\t\t\t\tconst fromBlock = fromCursor ? cursorTuple(fromCursor)[0] : 0;\n\t\t\t\tconst manifest = await dumps.list();\n\n\t\t\t\t// Hydrate finalized history from dumps, in block order. Files\n\t\t\t\t// ending at or below `from` carry nothing new; a file straddling\n\t\t\t\t// it is handed over whole, with `from` so the handler can skip\n\t\t\t\t// the rows at or below the checkpoint (file-granular delivery).\n\t\t\t\tconst files = manifest.files\n\t\t\t\t\t.filter((file) => file.to_block >= fromBlock)\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(file) =>\n\t\t\t\t\t\t\tfromCursor === null ||\n\t\t\t\t\t\t\tfile.max_cursor === null ||\n\t\t\t\t\t\t\tmaxCursor(fromCursor, file.max_cursor) !== fromCursor,\n\t\t\t\t\t)\n\t\t\t\t\t.sort(\n\t\t\t\t\t\t(a, b) => a.from_block - b.from_block || a.to_block - b.to_block,\n\t\t\t\t\t);\n\t\t\t\tfor (const file of files) {\n\t\t\t\t\tif (params.signal?.aborted) break;\n\t\t\t\t\tawait params.onDumpFile(file, { from: fromCursor });\n\t\t\t\t}\n\n\t\t\t\t// Seam: tail live from just past the dumped coverage. Cursor input is\n\t\t\t\t// exclusive, so the first live event is strictly after the last dump.\n\t\t\t\tconst seam = maxCursor(fromCursor, manifest.latest_finalized_cursor);\n\t\t\t\treturn consumeStreamsEvents({\n\t\t\t\t\tfromCursor: seam,\n\t\t\t\t\tmode: params.mode ?? \"tail\",\n\t\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\t\t// Live-tail narrowing only — the dump phase above hands over\n\t\t\t\t\t// whole all-type files by design.\n\t\t\t\t\ttypes: params.types,\n\t\t\t\t\tnotTypes: params.notTypes,\n\t\t\t\t\tfilters: params.filters,\n\t\t\t\t\tfetchEvents,\n\t\t\t\t\tonBatch: params.onBatch,\n\t\t\t\t\tonReorg: params.onReorg,\n\t\t\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\t\t\tmaxPages: params.maxPages,\n\t\t\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\t\t\tsignal: params.signal,\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tblocks: {\n\t\t\tevents: ((\n\t\t\t\theightOrHash: number | string,\n\t\t\t\topts?: { chain?: \"stacks\" | \"bitcoin\" },\n\t\t\t) =>\n\t\t\t\trequest<StreamsEventsListEnvelope>(\n\t\t\t\t\t`/v1/streams/blocks/${encodeURIComponent(String(heightOrHash))}/events${buildQuery(\n\t\t\t\t\t\t{ chain: opts?.chain === \"bitcoin\" ? \"bitcoin\" : undefined },\n\t\t\t\t\t)}`,\n\t\t\t\t)) as StreamsClient[\"blocks\"][\"events\"],\n\t\t},\n\t\treorgs: { list: listReorgs as StreamsClient[\"reorgs\"][\"list\"] },\n\t\tdumps,\n\t\tcanonical: ((height: number, opts?: { chain?: \"stacks\" | \"bitcoin\" }) =>\n\t\t\trequest<StreamsCanonicalBlock>(\n\t\t\t\t`/v1/streams/canonical/${height}${buildQuery({\n\t\t\t\t\tchain: opts?.chain === \"bitcoin\" ? \"bitcoin\" : undefined,\n\t\t\t\t})}`,\n\t\t\t)) as StreamsClient[\"canonical\"],\n\t\ttip: ((opts?: { chain?: \"stacks\" | \"bitcoin\" }) =>\n\t\t\trequest<StreamsTip>(\n\t\t\t\t`/v1/streams/tip${buildQuery({\n\t\t\t\t\tchain: opts?.chain === \"bitcoin\" ? \"bitcoin\" : undefined,\n\t\t\t\t})}`,\n\t\t\t)) as StreamsClient[\"tip\"],\n\t};\n}\n",
6
6
  "const DOCS_BASE = \"https://www.secondlayer.tools\";\n\n/** Options accepted by every error in the family. */\nexport interface SecondLayerErrorOptions {\n\tcause?: Error;\n\tdetails?: string;\n\t/** Stable machine-readable code (e.g. `UPGRADE_REQUIRED`). */\n\tcode?: string;\n\t/** Docs page that explains this failure and its fix. */\n\tdocsUrl?: string;\n\t/** Extra context lines appended to the message (DDL to run, next steps). */\n\tmetaMessages?: string[];\n\t/** Whether retrying the SAME request can succeed (429/5xx/network). */\n\tretryable?: boolean;\n\t/** Parsed `Retry-After`, in seconds — set on rate limits that carry it. */\n\tretryAfterSeconds?: number;\n}\n\n/**\n * Root of the SDK error family. Implements the same protocol as `BaseError`\n * in `@secondlayer/stacks` (`shortMessage`, `cause`, `toJSON`) so a failed\n * chain read and a failed platform read serialize and introspect identically.\n * It intentionally does NOT extend that class: cross-package `instanceof` is\n * unreliable under per-package bundling anyway (match on `code`/`name` across\n * packages).\n *\n * `retryable` is the signal the consume loops act on: 429/5xx/network are\n * retryable, 4xx and body-serialization failures are not.\n */\nexport class SecondLayerError extends Error {\n\toverride name = \"SecondLayerError\";\n\t/** The one-line failure, without the appended context blocks. */\n\tshortMessage: string;\n\tcode?: string;\n\tdocsUrl?: string;\n\tmetaMessages?: string[];\n\tretryable: boolean;\n\tretryAfterSeconds?: number;\n\n\tconstructor(shortMessage: string, options: SecondLayerErrorOptions = {}) {\n\t\tconst detailBlocks = [\n\t\t\t...(options.metaMessages ?? []),\n\t\t\t...(options.details ? [options.details] : []),\n\t\t\t...(options.docsUrl ? [`Docs: ${options.docsUrl}`] : []),\n\t\t];\n\t\tconst message = [\n\t\t\tshortMessage,\n\t\t\tdetailBlocks.length > 0 ? `\\n${detailBlocks.join(\"\\n\")}` : \"\",\n\t\t].join(\"\");\n\t\tsuper(message, options.cause ? { cause: options.cause } : undefined);\n\t\tthis.shortMessage = shortMessage;\n\t\tthis.code = options.code;\n\t\tthis.docsUrl = options.docsUrl;\n\t\tthis.metaMessages = options.metaMessages;\n\t\tthis.retryable = options.retryable ?? false;\n\t\tthis.retryAfterSeconds = options.retryAfterSeconds;\n\t}\n\n\t/**\n\t * Walk the cause chain. With a predicate, returns the first error matching\n\t * it (or `null`); without one, returns the deepest cause. Mirrors viem's\n\t * `error.walk()` so cross-library error handling reads the same.\n\t */\n\twalk(fn?: (err: unknown) => boolean): unknown {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: cause chains are untyped by nature\n\t\tlet err: any = this;\n\t\tlet last: unknown = this;\n\t\twhile (err != null) {\n\t\t\tif (fn?.(err)) return err;\n\t\t\tlast = err;\n\t\t\terr = err.cause;\n\t\t}\n\t\treturn fn ? null : last;\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tmessage: string;\n\t\tshortMessage: string;\n\t\tcause: string | undefined;\n\t\tcode: string | undefined;\n\t\tdocsUrl: string | undefined;\n\t\tretryable: boolean;\n\t\tretryAfterSeconds: number | undefined;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tshortMessage: this.shortMessage,\n\t\t\tcause: this.cause instanceof Error ? this.cause.message : undefined,\n\t\t\tcode: this.code,\n\t\t\tdocsUrl: this.docsUrl,\n\t\t\tretryable: this.retryable,\n\t\t\tretryAfterSeconds: this.retryAfterSeconds,\n\t\t};\n\t}\n}\n\n/** Retryability of an HTTP status: 429 and 5xx are transient. */\nfunction statusRetryable(status: number): boolean {\n\treturn status === 429 || status >= 500;\n}\n\n/** Docs page for a status/code pair, when one exists. */\nfunction docsFor(status: number, code?: string): string | undefined {\n\tif (code === \"UPGRADE_REQUIRED\" || status === 402)\n\t\treturn `${DOCS_BASE}/docs/authentication#pay-as-you-go-credits`;\n\tif (status === 429 || status === 401)\n\t\treturn `${DOCS_BASE}/docs/authentication`;\n\treturn undefined;\n}\n\n/**\n * Error thrown by {@link SecondLayer} when an API request fails.\n * Includes the HTTP status code for programmatic error handling.\n *\n * @example\n * ```ts\n * try {\n * await client.subgraphs.status(\"my-subgraph\");\n * } catch (err) {\n * if (err instanceof ApiError && err.status === 404) {\n * console.log(\"Subgraph not found\");\n * }\n * }\n * ```\n */\nexport class ApiError extends SecondLayerError {\n\tconstructor(\n\t\t/** HTTP status code (0 for network errors). */\n\t\tpublic status: number,\n\t\tmessage: string,\n\t\t/** Raw response body (parsed JSON if possible) — preserved for callers that need error details. */\n\t\tpublic body?: unknown,\n\t\t/** Stable machine-readable code from the API's `{error, code}` error envelope. */\n\t\tcode?: string,\n\t\toptions: SecondLayerErrorOptions = {},\n\t) {\n\t\tsuper(message, {\n\t\t\tcode,\n\t\t\tretryable: options.retryable ?? statusRetryable(status),\n\t\t\tdocsUrl: options.docsUrl ?? docsFor(status, code),\n\t\t\t...(options.cause ? { cause: options.cause } : {}),\n\t\t\t...(options.details ? { details: options.details } : {}),\n\t\t\t...(options.metaMessages ? { metaMessages: options.metaMessages } : {}),\n\t\t\t...(options.retryAfterSeconds !== undefined\n\t\t\t\t? { retryAfterSeconds: options.retryAfterSeconds }\n\t\t\t\t: {}),\n\t\t});\n\t\tthis.name = \"ApiError\";\n\t}\n}\n\n/** Thrown on a 401 by both the instance clients and Streams. Carries the\n * server's `{error, code}` envelope when it sent one, so a revoked token reads\n * differently from a missing one. */\nexport class AuthError extends ApiError {\n\toverride readonly status = 401 as const;\n\n\tconstructor(\n\t\tmessage = \"API key invalid or expired.\",\n\t\tbody?: unknown,\n\t\tcode?: string,\n\t) {\n\t\tsuper(401, message, body, code);\n\t\tthis.name = \"AuthError\";\n\t}\n}\n\n/** Thrown on a 429 by both the instance clients and Streams. `retryable`,\n * with `retryAfterSeconds` parsed from the `Retry-After` header when sent. */\nexport class RateLimitError extends ApiError {\n\toverride readonly status = 429 as const;\n\n\tconstructor(\n\t\tmessage = \"Rate limited. Try again later.\",\n\t\t/** Raw `Retry-After` header value (seconds or HTTP-date). */\n\t\treadonly retryAfter?: string,\n\t\tbody?: unknown,\n\t\tcode?: string,\n\t) {\n\t\tsuper(429, message, body, code, {\n\t\t\tretryable: true,\n\t\t\tretryAfterSeconds: parseRetryAfter(retryAfter),\n\t\t});\n\t\tthis.name = \"RateLimitError\";\n\t}\n}\n\n/** Thrown on a 4xx the caller can fix (bad cursor, bad params). Never retried.\n * `code` is the server's machine-readable code when the envelope carried one. */\nexport class ValidationError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown, code?: string) {\n\t\tsuper(status, message, body, code, { retryable: false });\n\t\tthis.name = \"ValidationError\";\n\t}\n}\n\n/** Thrown when an archive manifest signature is missing or does not verify. */\nexport class ArchiveSignatureError extends SecondLayerError {\n\tconstructor(message = \"Archive manifest signature is missing or invalid.\") {\n\t\tsuper(message, { code: \"ARCHIVE_SIGNATURE\", retryable: false });\n\t\tthis.name = \"ArchiveSignatureError\";\n\t}\n}\n\n/** Thrown on a 401 from the archive ops host (quote/fetch/credits). */\nexport class ArchiveAuthError extends SecondLayerError {\n\tconstructor(message = \"Archive ops request was not authenticated.\") {\n\t\tsuper(message, { code: \"ARCHIVE_AUTH\", retryable: false });\n\t\tthis.name = \"ArchiveAuthError\";\n\t}\n}\n\n/** Thrown on a 402 from archive fetch — prepaid credits do not cover the quote. */\nexport class InsufficientArchiveCreditsError extends SecondLayerError {\n\tshortfallUsdMicros?: number;\n\tconstructor(\n\t\tmessage = \"Insufficient archive credits.\",\n\t\tshortfallUsdMicros?: number,\n\t) {\n\t\tsuper(message, {\n\t\t\tcode: \"INSUFFICIENT_ARCHIVE_CREDITS\",\n\t\t\tretryable: false,\n\t\t});\n\t\tthis.name = \"InsufficientArchiveCreditsError\";\n\t\tthis.shortfallUsdMicros = shortfallUsdMicros;\n\t}\n}\n\n/** Thrown on a 503 when the archive fetch gate is unconfigured. */\nexport class ArchiveGateNotConfiguredError extends SecondLayerError {\n\tconstructor(message = \"The archive gate is not configured on the server.\") {\n\t\tsuper(message, { code: \"ARCHIVE_GATE_NOT_CONFIGURED\", retryable: false });\n\t\tthis.name = \"ArchiveGateNotConfiguredError\";\n\t}\n}\n\n/** Parse a `Retry-After` header: delta-seconds or an HTTP-date. */\nexport function parseRetryAfter(value?: string | null): number | undefined {\n\tif (!value) return undefined;\n\tconst seconds = Number(value);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds;\n\tconst date = Date.parse(value);\n\tif (!Number.isNaN(date)) return Math.max(0, (date - Date.now()) / 1000);\n\treturn undefined;\n}\n",
7
- "import {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tparseRetryAfter,\n} from \"./errors.ts\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport interface SecondLayerOptions {\n\t/** Base URL of the instance API (trailing slashes are stripped). */\n\tbaseUrl: string;\n\t/** Bearer token for authenticated instance requests (`INSTANCE_TOKEN`). */\n\tapiKey?: string;\n\t/** Hosted account key (`sk-sl_*`). Env `SECONDLAYER_API_KEY`. Used by\n\t * `sl.archive` quote/fetch/credits, never by instance `/v1` or `/api`. */\n\taccountKey?: string;\n\t/** Fetch implementation. Tests and edge runtimes can provide their own. */\n\tfetchImpl?: FetchLike;\n\t/** Public base URL for Streams bulk parquet dumps (the cold backfill plane).\n\t * Required for `streams.dumps.*`; without it the dumps client falls back to\n\t * its built-in default. */\n\tdumpsBaseUrl?: string;\n\t/** Public base URL for the signed canonical archive tree. Defaults to\n\t * `https://archive.secondlayer.tools`. Reaches `sl.archive`. */\n\tarchiveBaseUrl?: string;\n\t/** Credits and fetch-gate API. Defaults to `https://api.secondlayer.tools`,\n\t * not `baseUrl`. Reaches `sl.archive` quote/fetch/credits. */\n\tarchiveOpsUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\t/** Check the ed25519 signature on every Streams read. Omit for lenient\n\t * (verify when signed, pass through unsigned self-host responses), `true`\n\t * or `{ publicKey }` for strict, `false` for off. Reaches `sl.streams`. */\n\tverify?: boolean | { publicKey: string };\n\t/** Check the dumps manifest signature before trusting any file hash\n\t * (default on). Reaches `sl.streams.dumps`. */\n\tverifyDumpsManifest?: boolean;\n\t/** How long one request may take, headers and body, before it fails with a\n\t * retryable `ApiError` (default 30 000 ms). A hung socket then trips the\n\t * retry policy instead of stalling a walk or consume loop forever. `0`\n\t * disables the timeout. */\n\trequestTimeoutMs?: number;\n\t/** Where GET responses carrying an `ETag` are kept, so a repeat read sends\n\t * `If-None-Match` and a finalized page comes back as a free `304`.\n\t * Defaults to an in-memory store of the last 64 pages. Pass your own to\n\t * keep it across processes (a file, a KV), or `false` to turn it off. */\n\tetagCache?: EtagCache | false;\n}\n\n/** One cached GET response: its validator and the body it validated. */\nexport type EtagEntry = { etag: string; body: string };\n\n/** Storage for `etagCache`. Keys are full request URLs. Either method may be\n * async, so a disk or KV store works as well as a Map. */\nexport interface EtagCache {\n\tget(key: string): EtagEntry | undefined | Promise<EtagEntry | undefined>;\n\tset(key: string, entry: EtagEntry): void | Promise<void>;\n}\n\n/** Bounded in-memory `EtagCache`. Evicts the least recently used page, so a\n * long walk can't hold more than `limit` page bodies. */\nexport class MemoryEtagCache implements EtagCache {\n\tprivate entries = new Map<string, EtagEntry>();\n\tconstructor(private readonly limit = 64) {}\n\n\tget(key: string): EtagEntry | undefined {\n\t\tconst entry = this.entries.get(key);\n\t\tif (entry) {\n\t\t\tthis.entries.delete(key);\n\t\t\tthis.entries.set(key, entry);\n\t\t}\n\t\treturn entry;\n\t}\n\n\tset(key: string, entry: EtagEntry): void {\n\t\tthis.entries.delete(key);\n\t\tthis.entries.set(key, entry);\n\t\tif (this.entries.size > this.limit) {\n\t\t\tconst oldest = this.entries.keys().next().value;\n\t\t\tif (oldest !== undefined) this.entries.delete(oldest);\n\t\t}\n\t}\n}\n\n/** Default per-request budget. Long enough for a 1000-row filtered page on a\n * cold cache, short enough that a half-open connection surfaces as a retry. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** Per-call options every `request*` method accepts. */\nexport type RequestOptions = {\n\t/** Cancels the in-flight request (and its body read). The rejection is the\n\t * signal's reason, an `AbortError` by default, never an `ApiError`. */\n\tsignal?: AbortSignal;\n};\n\n/** The rejection a caller abort produces when the signal carries no reason. */\nexport function abortError(): Error {\n\treturn new DOMException(\"This operation was aborted\", \"AbortError\");\n}\n\n/** Reject as soon as `signal` aborts, even when `promise` is a fetch\n * implementation that ignores its `signal` argument. */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) return Promise.reject(signal.reason ?? abortError());\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason ?? abortError());\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t});\n\t});\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or\n * `SECONDLAYER_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\n/** Instance credential. `secondlayer init` writes this. */\nexport const INSTANCE_TOKEN_ENV = \"INSTANCE_TOKEN\";\n\n/** Hosted account key (`sk-sl_*`) for api.secondlayer.tools. */\nexport const ACCOUNT_KEY_ENV = \"SECONDLAYER_API_KEY\";\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst primary = process.env?.SECONDLAYER_API_URL || undefined;\n\t\tif (primary) return primary.replace(/\\/+$/, \"\");\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Resolve the instance credential. Precedence: explicit `apiKey` (including\n * `\"\"` for keyless) → `INSTANCE_TOKEN`. Does not read the hosted account key\n * env vars. Guarded for browsers and edge runtimes. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst token = process.env?.INSTANCE_TOKEN || undefined;\n\treturn token;\n}\n\n/** Resolve the hosted account key for archive quote/fetch/credits.\n * Precedence: explicit `accountKey` → `SECONDLAYER_API_KEY`. Does not read\n * `INSTANCE_TOKEN`. */\nexport function resolveAccountKey(accountKey?: string): string | undefined {\n\tif (accountKey !== undefined) return accountKey;\n\tif (typeof process === \"undefined\") return undefined;\n\treturn process.env?.SECONDLAYER_API_KEY || undefined;\n}\n\n/** Percent-encode one URL path segment. Every caller-supplied identifier\n * (subgraph name, table, webhook id) goes through this before it is\n * interpolated into a path, so `..`, `/`, `?` and `#` in an id cannot\n * retarget the authenticated request at a different route. */\nexport function seg(value: string | number): string {\n\treturn encodeURIComponent(String(value));\n}\n\n/** Build a query-string suffix from name→value pairs. Skips null/undefined and\n * empty values; arrays are comma-joined. Returns \"\" (never a dangling \"?\") or\n * \"?a=1&b=2\" — the one canonical builder every list endpoint shares, so the\n * empty-query guard can't be forgotten per call site. */\nexport function buildQuery(\n\tparams: Record<\n\t\tstring,\n\t\tnumber | string | boolean | readonly string[] | null | undefined\n\t>,\n): string {\n\tconst search = new URLSearchParams();\n\tfor (const [name, value] of Object.entries(params)) {\n\t\tif (value === undefined || value === null) continue;\n\t\tconst serialized = Array.isArray(value) ? value.join(\",\") : String(value);\n\t\tif (serialized.length === 0) continue;\n\t\tsearch.set(name, serialized);\n\t}\n\tconst query = search.toString();\n\treturn query ? `?${query}` : \"\";\n}\n\n/** Pull the message and code out of an API error body. The API answers every\n * failure with `{error, code}`; a proxy in front of it may answer with plain\n * text or nothing, so the body is kept whichever shape it took and the\n * message is left undefined when there is none worth surfacing. */\nexport function parseErrorEnvelope(text: string): {\n\tmessage?: string;\n\tcode?: string;\n\tbody: unknown;\n} {\n\tif (text.length === 0) return { body: undefined };\n\ttry {\n\t\tconst json = JSON.parse(text);\n\t\tlet message: string | undefined;\n\t\tlet code: string | undefined;\n\t\tif (json && typeof json === \"object\") {\n\t\t\tconst err = json.error ?? json.message;\n\t\t\tif (typeof err === \"string\" && err.length > 0) message = err;\n\t\t\telse if (err && typeof err === \"object\") message = JSON.stringify(err);\n\t\t\tif (typeof json.code === \"string\") code = json.code;\n\t\t}\n\t\treturn { message, code, body: json };\n\t} catch {\n\t\treturn { message: text, body: text };\n\t}\n}\n\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\n\tprotected requestTimeoutMs: number;\n\tprotected etagCache: EtagCache | null;\n\n\tconstructor(options: Partial<SecondLayerOptions> = {}) {\n\t\tthis.baseUrl = resolveBaseUrl(options.baseUrl);\n\t\tthis.apiKey = resolveApiKey(options.apiKey);\n\t\tthis.origin = options.origin ?? \"cli\";\n\t\tthis.requestTimeoutMs =\n\t\t\toptions.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n\t\t// Bind the global so a bare `fetch` reference doesn't lose its Request\n\t\t// context on runtimes where fetch is a method (workerd, older Node).\n\t\tthis.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));\n\t\tthis.etagCache =\n\t\t\toptions.etagCache === false\n\t\t\t\t? null\n\t\t\t\t: (options.etagCache ?? new MemoryEtagCache());\n\t}\n\n\tstatic authHeaders(apiKey?: string): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t};\n\t\tif (apiKey) {\n\t\t\theaders.Authorization = `Bearer ${apiKey}`;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprotected async request<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\t// Only GETs are revalidated: a write's response is never a copy of\n\t\t\t// something the caller already holds.\n\t\t\tconst cacheKey =\n\t\t\t\tmethod === \"GET\" && this.etagCache ? `${this.baseUrl}${path}` : null;\n\t\t\tconst cached = cacheKey ? await this.etagCache?.get(cacheKey) : undefined;\n\t\t\tconst response = await this.fetchResponse(\n\t\t\t\tmethod,\n\t\t\t\tpath,\n\t\t\t\tbody,\n\t\t\t\tsignal,\n\t\t\t\tcached ? { \"If-None-Match\": cached.etag } : undefined,\n\t\t\t);\n\t\t\tif (response.status === 204) {\n\t\t\t\treturn undefined as T;\n\t\t\t}\n\t\t\tif (response.status === 304) {\n\t\t\t\t// The server only answers 304 to a validator we sent, and it meters\n\t\t\t\t// nothing for it. The page is the one we already hold; its `tip`\n\t\t\t\t// field is as of the first read, since the ETag excludes the tip.\n\t\t\t\tif (!cached) {\n\t\t\t\t\tthrow new ApiError(304, \"Not Modified without a cached copy\");\n\t\t\t\t}\n\t\t\t\treturn JSON.parse(cached.body) as T;\n\t\t\t}\n\t\t\tconst etag = cacheKey ? response.headers.get(\"ETag\") : null;\n\t\t\tif (!cacheKey || !etag) {\n\t\t\t\treturn (await raceAbort(response.json(), signal)) as T;\n\t\t\t}\n\t\t\tconst text = await raceAbort(response.text(), signal);\n\t\t\tawait this.etagCache?.set(cacheKey, { etag, body: text });\n\t\t\treturn JSON.parse(text) as T;\n\t\t});\n\t}\n\n\t/** Like `request`, but maps a 404 to `null` instead of throwing — the one\n\t * place that owns the \"absent resource\" rule for `get*` accessors. */\n\tprotected async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body, opts);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.status === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprotected async requestText(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<string> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\treturn raceAbort(response.text(), signal);\n\t\t});\n\t}\n\n\t/** Run one request under the caller's signal plus the per-request timeout.\n\t * One combined signal covers the fetch and the body read, so a socket that\n\t * stalls mid-body times out the same way one that never answers does. A\n\t * timeout rejects with a retryable `ApiError`; a caller abort rejects with\n\t * the signal's reason so loops can tell \"stop\" from \"try again\". */\n\tprivate async withRequestBudget<T>(\n\t\tcallerSignal: AbortSignal | undefined,\n\t\trun: (signal: AbortSignal) => Promise<T>,\n\t): Promise<T> {\n\t\tconst controller = new AbortController();\n\t\tlet timedOut = false;\n\t\tconst forward = () =>\n\t\t\tcontroller.abort(callerSignal?.reason ?? abortError());\n\t\tif (callerSignal?.aborted) forward();\n\t\telse callerSignal?.addEventListener(\"abort\", forward, { once: true });\n\t\tconst timer =\n\t\t\tthis.requestTimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tcontroller.abort(abortError());\n\t\t\t\t\t}, this.requestTimeoutMs)\n\t\t\t\t: undefined;\n\t\ttry {\n\t\t\treturn await run(controller.signal);\n\t\t} catch (err) {\n\t\t\tif (timedOut && !callerSignal?.aborted) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`No response from ${this.baseUrl} within ${this.requestTimeoutMs}ms. Retryable. Raise requestTimeoutMs for slow filtered reads.`,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"REQUEST_TIMEOUT\",\n\t\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tcallerSignal?.removeEventListener(\"abort\", forward);\n\t\t}\n\t}\n\n\t/** Issue the HTTP request and map non-2xx statuses onto the error family.\n\t * `signal` is the combined caller-plus-timeout signal from `request*`;\n\t * subclasses that stream a body call this directly and read it themselves. */\n\tprotected async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\tsignal?: AbortSignal,\n\t\textraHeaders?: Record<string, string>,\n\t): Promise<Response> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst headers = {\n\t\t\t...BaseClient.authHeaders(this.apiKey),\n\t\t\t...extraHeaders,\n\t\t};\n\t\theaders[\"x-sl-origin\"] = this.origin;\n\n\t\t// Serialize the body BEFORE the network try so a body-encoding error\n\t\t// (e.g. unsupported BigInt) isn't misreported as \"Cannot reach API\".\n\t\t// BigInts are stringified — server schemas accept jsonb so the value\n\t\t// reaches the server intact, and any field that needs an actual bigint\n\t\t// at runtime is rehydrated by the consuming module (subgraph handler\n\t\t// code preserves the literal). See packages/subgraphs source-matcher\n\t\t// for the post-load shape.\n\t\tlet serializedBody: string | undefined;\n\t\tif (body !== undefined && body !== null) {\n\t\t\ttry {\n\t\t\t\tserializedBody = JSON.stringify(body, (_key, value) =>\n\t\t\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tconst detail = err instanceof Error ? err.message : String(err);\n\t\t\t\t// Not retryable: the same body will fail to serialize again.\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`Failed to serialize request body: ${detail}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t{ retryable: false },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tconst pending = this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tresponse = signal ? await raceAbort(pending, signal) : await pending;\n\t\t} catch (err) {\n\t\t\t// An abort (caller or timeout) is not a network failure; let the\n\t\t\t// budget wrapper decide what it means.\n\t\t\tif (signal?.aborted) throw err;\n\t\t\tthrow new ApiError(\n\t\t\t\t0,\n\t\t\t\t`Cannot reach API at ${this.baseUrl}. Check your connection or try again.`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t);\n\t\t}\n\n\t\t// A 304 is an answer to our own If-None-Match, not a failure.\n\t\tif (response.status === 304) return response;\n\n\t\tif (!response.ok) {\n\t\t\t// Read the envelope once for every failure status. The API answers\n\t\t\t// 401 and 503 with `{error, code}` too (a revoked token, an index\n\t\t\t// still catching up), and that code is what a caller branches on.\n\t\t\tconst errorBody = signal\n\t\t\t\t? await raceAbort(response.text(), signal)\n\t\t\t\t: await response.text();\n\t\t\tconst envelope = parseErrorEnvelope(errorBody);\n\t\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError(\n\t\t\t\t\tenvelope.message ?? \"API key invalid or expired.\",\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status === 429) {\n\t\t\t\t// The header is preserved as `retryAfterSeconds` (not just prose) so\n\t\t\t\t// the consume loops can honor it.\n\t\t\t\tconst fallback = retryAfter\n\t\t\t\t\t? `Rate limited. Wait ${retryAfter} seconds.`\n\t\t\t\t\t: \"Rate limited. Try again later.\";\n\t\t\t\tthrow new RateLimitError(\n\t\t\t\t\tenvelope.message ?? fallback,\n\t\t\t\t\tretryAfter,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tconst retryAfterSeconds = parseRetryAfter(retryAfter);\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\tenvelope.message ??\n\t\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t\tretryAfterSeconds !== undefined ? { retryAfterSeconds } : {},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new ApiError(\n\t\t\t\tresponse.status,\n\t\t\t\tenvelope.message ?? `HTTP ${response.status}`,\n\t\t\t\tenvelope.body,\n\t\t\t\tenvelope.code,\n\t\t\t);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
7
+ "import {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tparseRetryAfter,\n} from \"./errors.ts\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport interface SecondLayerOptions {\n\t/** Base URL of the instance API (trailing slashes are stripped). */\n\tbaseUrl: string;\n\t/** Bearer token for authenticated instance requests (`INSTANCE_TOKEN`). */\n\tapiKey?: string;\n\t/** Hosted account key (`sk-sl_*`). Env `SECONDLAYER_API_KEY`. Used by\n\t * `sl.archive` quote/fetch/credits, never by instance `/v1` or `/api`. */\n\taccountKey?: string;\n\t/** Fetch implementation. Tests and edge runtimes can provide their own. */\n\tfetchImpl?: FetchLike;\n\t/** Public base URL for Streams bulk parquet dumps (the cold backfill plane).\n\t * Required for `streams.dumps.*`; without it the dumps client falls back to\n\t * its built-in default. */\n\tdumpsBaseUrl?: string;\n\t/** Public base URL for the signed canonical archive tree. Defaults to\n\t * `https://archive.secondlayer.tools`. Reaches `sl.archive`. */\n\tarchiveBaseUrl?: string;\n\t/** Credits and fetch-gate API. Defaults to `https://api.secondlayer.tools`,\n\t * not `baseUrl`. Reaches `sl.archive` quote/fetch/credits. */\n\tarchiveOpsUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\t/** Check the ed25519 signature on every Streams read. Omit for lenient\n\t * (verify when signed, pass through unsigned self-host responses), `true`\n\t * or `{ publicKey }` for strict, `false` for off. Reaches `sl.streams`. */\n\tverify?: boolean | { publicKey: string };\n\t/** Check the dumps manifest signature before trusting any file hash\n\t * (default on). Reaches `sl.streams.dumps`. */\n\tverifyDumpsManifest?: boolean;\n\t/** How long one request may take, headers and body, before it fails with a\n\t * retryable `ApiError` (default 30 000 ms). A hung socket then trips the\n\t * retry policy instead of stalling a walk or consume loop forever. `0`\n\t * disables the timeout. */\n\trequestTimeoutMs?: number;\n\t/** Where GET responses carrying an `ETag` are kept, so a repeat read sends\n\t * `If-None-Match` and a finalized page comes back as a free `304`.\n\t * Defaults to an in-memory store of the last 64 pages. Pass your own to\n\t * keep it across processes (a file, a KV), or `false` to turn it off. */\n\tetagCache?: EtagCache | false;\n}\n\n/** One cached GET response: its validator and the body it validated. */\nexport type EtagEntry = { etag: string; body: string };\n\n/** Storage for `etagCache`. Keys are full request URLs. Either method may be\n * async, so a disk or KV store works as well as a Map. */\nexport interface EtagCache {\n\tget(key: string): EtagEntry | undefined | Promise<EtagEntry | undefined>;\n\tset(key: string, entry: EtagEntry): void | Promise<void>;\n}\n\n/** Bounded in-memory `EtagCache`. Evicts the least recently used page, so a\n * long walk can't hold more than `limit` page bodies. */\nexport class MemoryEtagCache implements EtagCache {\n\tprivate entries = new Map<string, EtagEntry>();\n\tconstructor(private readonly limit = 64) {}\n\n\tget(key: string): EtagEntry | undefined {\n\t\tconst entry = this.entries.get(key);\n\t\tif (entry) {\n\t\t\tthis.entries.delete(key);\n\t\t\tthis.entries.set(key, entry);\n\t\t}\n\t\treturn entry;\n\t}\n\n\tset(key: string, entry: EtagEntry): void {\n\t\tthis.entries.delete(key);\n\t\tthis.entries.set(key, entry);\n\t\tif (this.entries.size > this.limit) {\n\t\t\tconst oldest = this.entries.keys().next().value;\n\t\t\tif (oldest !== undefined) this.entries.delete(oldest);\n\t\t}\n\t}\n}\n\n/** Default per-request budget. Long enough for a 1000-row filtered page on a\n * cold cache, short enough that a half-open connection surfaces as a retry. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** Per-call options every `request*` method accepts. */\nexport type RequestOptions = {\n\t/** Cancels the in-flight request (and its body read). The rejection is the\n\t * signal's reason, an `AbortError` by default, never an `ApiError`. */\n\tsignal?: AbortSignal;\n};\n\n/** The rejection a caller abort produces when the signal carries no reason. */\nexport function abortError(): Error {\n\treturn new DOMException(\"This operation was aborted\", \"AbortError\");\n}\n\n/** Reject as soon as `signal` aborts, even when `promise` is a fetch\n * implementation that ignores its `signal` argument. */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) return Promise.reject(signal.reason ?? abortError());\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason ?? abortError());\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t});\n\t});\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or\n * `SECONDLAYER_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\n/** Instance credential. `secondlayer init` writes this. */\nexport const INSTANCE_TOKEN_ENV = \"INSTANCE_TOKEN\";\n\n/** Hosted account key (`sk-sl_*`) for api.secondlayer.tools. */\nexport const ACCOUNT_KEY_ENV = \"SECONDLAYER_API_KEY\";\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst primary = process.env?.SECONDLAYER_API_URL || undefined;\n\t\tif (primary) return primary.replace(/\\/+$/, \"\");\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Resolve the instance credential. Precedence: explicit `apiKey` (including\n * `\"\"` for keyless) → `INSTANCE_TOKEN`. Does not read the hosted account key\n * env vars. Guarded for browsers and edge runtimes. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst token = process.env?.INSTANCE_TOKEN || undefined;\n\treturn token;\n}\n\n/** Resolve the hosted account key for archive quote/fetch/credits.\n * Precedence: explicit `accountKey` → `SECONDLAYER_API_KEY`. Does not read\n * `INSTANCE_TOKEN`. */\nexport function resolveAccountKey(accountKey?: string): string | undefined {\n\tif (accountKey !== undefined) return accountKey;\n\tif (typeof process === \"undefined\") return undefined;\n\treturn process.env?.SECONDLAYER_API_KEY || undefined;\n}\n\n/** Percent-encode one URL path segment. Every caller-supplied identifier\n * (subgraph name, table, webhook id) goes through this before it is\n * interpolated into a path, so `..`, `/`, `?` and `#` in an id cannot\n * retarget the authenticated request at a different route. */\nexport function seg(value: string | number): string {\n\treturn encodeURIComponent(String(value));\n}\n\n/** Build a query-string suffix from name→value pairs. Skips null/undefined and\n * empty values; arrays are comma-joined. Returns \"\" (never a dangling \"?\") or\n * \"?a=1&b=2\" — the one canonical builder every list endpoint shares, so the\n * empty-query guard can't be forgotten per call site. */\nexport function buildQuery(\n\tparams: Record<\n\t\tstring,\n\t\tnumber | string | boolean | readonly string[] | null | undefined\n\t>,\n): string {\n\tconst search = new URLSearchParams();\n\tfor (const [name, value] of Object.entries(params)) {\n\t\tif (value === undefined || value === null) continue;\n\t\tconst serialized = Array.isArray(value) ? value.join(\",\") : String(value);\n\t\tif (serialized.length === 0) continue;\n\t\tsearch.set(name, serialized);\n\t}\n\tconst query = search.toString();\n\treturn query ? `?${query}` : \"\";\n}\n\n/** Pull the message and code out of an API error body. The API answers most\n * failures with `{error, code}`, where `error` IS the human text (e.g.\n * `{error: \"Unauthorized\"}`) — a proxy in front of it may answer with plain\n * text or nothing, so the body is kept whichever shape it took and the\n * message is left undefined when there is none worth surfacing. A few\n * bodies (e.g. `spend_cap_reached`) instead use `error` as a machine code\n * and carry the human text in its own `message` field — when both a string\n * `error` and a string `message` are present, `message` wins. */\nexport function parseErrorEnvelope(text: string): {\n\tmessage?: string;\n\tcode?: string;\n\tbody: unknown;\n} {\n\tif (text.length === 0) return { body: undefined };\n\ttry {\n\t\tconst json = JSON.parse(text);\n\t\tlet message: string | undefined;\n\t\tlet code: string | undefined;\n\t\tif (json && typeof json === \"object\") {\n\t\t\tconst err = json.error ?? json.message;\n\t\t\tif (\n\t\t\t\ttypeof err === \"string\" &&\n\t\t\t\ttypeof json.message === \"string\" &&\n\t\t\t\tjson.message.length > 0\n\t\t\t) {\n\t\t\t\tmessage = json.message;\n\t\t\t} else if (typeof err === \"string\" && err.length > 0) message = err;\n\t\t\telse if (err && typeof err === \"object\") message = JSON.stringify(err);\n\t\t\tif (typeof json.code === \"string\") code = json.code;\n\t\t}\n\t\treturn { message, code, body: json };\n\t} catch {\n\t\treturn { message: text, body: text };\n\t}\n}\n\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\n\tprotected requestTimeoutMs: number;\n\tprotected etagCache: EtagCache | null;\n\n\tconstructor(options: Partial<SecondLayerOptions> = {}) {\n\t\tthis.baseUrl = resolveBaseUrl(options.baseUrl);\n\t\tthis.apiKey = resolveApiKey(options.apiKey);\n\t\tthis.origin = options.origin ?? \"cli\";\n\t\tthis.requestTimeoutMs =\n\t\t\toptions.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n\t\t// Bind the global so a bare `fetch` reference doesn't lose its Request\n\t\t// context on runtimes where fetch is a method (workerd, older Node).\n\t\tthis.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));\n\t\tthis.etagCache =\n\t\t\toptions.etagCache === false\n\t\t\t\t? null\n\t\t\t\t: (options.etagCache ?? new MemoryEtagCache());\n\t}\n\n\tstatic authHeaders(apiKey?: string): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t};\n\t\tif (apiKey) {\n\t\t\theaders.Authorization = `Bearer ${apiKey}`;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprotected async request<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\t// Only GETs are revalidated: a write's response is never a copy of\n\t\t\t// something the caller already holds.\n\t\t\tconst cacheKey =\n\t\t\t\tmethod === \"GET\" && this.etagCache ? `${this.baseUrl}${path}` : null;\n\t\t\tconst cached = cacheKey ? await this.etagCache?.get(cacheKey) : undefined;\n\t\t\tconst response = await this.fetchResponse(\n\t\t\t\tmethod,\n\t\t\t\tpath,\n\t\t\t\tbody,\n\t\t\t\tsignal,\n\t\t\t\tcached ? { \"If-None-Match\": cached.etag } : undefined,\n\t\t\t);\n\t\t\tif (response.status === 204) {\n\t\t\t\treturn undefined as T;\n\t\t\t}\n\t\t\tif (response.status === 304) {\n\t\t\t\t// The server only answers 304 to a validator we sent, and it meters\n\t\t\t\t// nothing for it. The page is the one we already hold; its `tip`\n\t\t\t\t// field is as of the first read, since the ETag excludes the tip.\n\t\t\t\tif (!cached) {\n\t\t\t\t\tthrow new ApiError(304, \"Not Modified without a cached copy\");\n\t\t\t\t}\n\t\t\t\treturn JSON.parse(cached.body) as T;\n\t\t\t}\n\t\t\tconst etag = cacheKey ? response.headers.get(\"ETag\") : null;\n\t\t\tif (!cacheKey || !etag) {\n\t\t\t\treturn (await raceAbort(response.json(), signal)) as T;\n\t\t\t}\n\t\t\tconst text = await raceAbort(response.text(), signal);\n\t\t\tawait this.etagCache?.set(cacheKey, { etag, body: text });\n\t\t\treturn JSON.parse(text) as T;\n\t\t});\n\t}\n\n\t/** Like `request`, but maps a 404 to `null` instead of throwing — the one\n\t * place that owns the \"absent resource\" rule for `get*` accessors. */\n\tprotected async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body, opts);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.status === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprotected async requestText(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<string> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\treturn raceAbort(response.text(), signal);\n\t\t});\n\t}\n\n\t/** Run one request under the caller's signal plus the per-request timeout.\n\t * One combined signal covers the fetch and the body read, so a socket that\n\t * stalls mid-body times out the same way one that never answers does. A\n\t * timeout rejects with a retryable `ApiError`; a caller abort rejects with\n\t * the signal's reason so loops can tell \"stop\" from \"try again\". */\n\tprivate async withRequestBudget<T>(\n\t\tcallerSignal: AbortSignal | undefined,\n\t\trun: (signal: AbortSignal) => Promise<T>,\n\t): Promise<T> {\n\t\tconst controller = new AbortController();\n\t\tlet timedOut = false;\n\t\tconst forward = () =>\n\t\t\tcontroller.abort(callerSignal?.reason ?? abortError());\n\t\tif (callerSignal?.aborted) forward();\n\t\telse callerSignal?.addEventListener(\"abort\", forward, { once: true });\n\t\tconst timer =\n\t\t\tthis.requestTimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tcontroller.abort(abortError());\n\t\t\t\t\t}, this.requestTimeoutMs)\n\t\t\t\t: undefined;\n\t\ttry {\n\t\t\treturn await run(controller.signal);\n\t\t} catch (err) {\n\t\t\tif (timedOut && !callerSignal?.aborted) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`No response from ${this.baseUrl} within ${this.requestTimeoutMs}ms. Retryable. Raise requestTimeoutMs for slow filtered reads.`,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"REQUEST_TIMEOUT\",\n\t\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tcallerSignal?.removeEventListener(\"abort\", forward);\n\t\t}\n\t}\n\n\t/** Issue the HTTP request and map non-2xx statuses onto the error family.\n\t * `signal` is the combined caller-plus-timeout signal from `request*`;\n\t * subclasses that stream a body call this directly and read it themselves. */\n\tprotected async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\tsignal?: AbortSignal,\n\t\textraHeaders?: Record<string, string>,\n\t): Promise<Response> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst headers = {\n\t\t\t...BaseClient.authHeaders(this.apiKey),\n\t\t\t...extraHeaders,\n\t\t};\n\t\theaders[\"x-sl-origin\"] = this.origin;\n\n\t\t// Serialize the body BEFORE the network try so a body-encoding error\n\t\t// (e.g. unsupported BigInt) isn't misreported as \"Cannot reach API\".\n\t\t// BigInts are stringified — server schemas accept jsonb so the value\n\t\t// reaches the server intact, and any field that needs an actual bigint\n\t\t// at runtime is rehydrated by the consuming module (subgraph handler\n\t\t// code preserves the literal). See packages/subgraphs source-matcher\n\t\t// for the post-load shape.\n\t\tlet serializedBody: string | undefined;\n\t\tif (body !== undefined && body !== null) {\n\t\t\ttry {\n\t\t\t\tserializedBody = JSON.stringify(body, (_key, value) =>\n\t\t\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tconst detail = err instanceof Error ? err.message : String(err);\n\t\t\t\t// Not retryable: the same body will fail to serialize again.\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`Failed to serialize request body: ${detail}`,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t{ retryable: false },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tconst pending = this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tresponse = signal ? await raceAbort(pending, signal) : await pending;\n\t\t} catch (err) {\n\t\t\t// An abort (caller or timeout) is not a network failure; let the\n\t\t\t// budget wrapper decide what it means.\n\t\t\tif (signal?.aborted) throw err;\n\t\t\tthrow new ApiError(\n\t\t\t\t0,\n\t\t\t\t`Cannot reach API at ${this.baseUrl}. Check your connection or try again.`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t);\n\t\t}\n\n\t\t// A 304 is an answer to our own If-None-Match, not a failure.\n\t\tif (response.status === 304) return response;\n\n\t\tif (!response.ok) {\n\t\t\t// Read the envelope once for every failure status. The API answers\n\t\t\t// 401 and 503 with `{error, code}` too (a revoked token, an index\n\t\t\t// still catching up), and that code is what a caller branches on.\n\t\t\tconst errorBody = signal\n\t\t\t\t? await raceAbort(response.text(), signal)\n\t\t\t\t: await response.text();\n\t\t\tconst envelope = parseErrorEnvelope(errorBody);\n\t\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError(\n\t\t\t\t\tenvelope.message ?? \"API key invalid or expired.\",\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status === 429) {\n\t\t\t\t// The header is preserved as `retryAfterSeconds` (not just prose) so\n\t\t\t\t// the consume loops can honor it.\n\t\t\t\tconst fallback = retryAfter\n\t\t\t\t\t? `Rate limited. Wait ${retryAfter} seconds.`\n\t\t\t\t\t: \"Rate limited. Try again later.\";\n\t\t\t\tthrow new RateLimitError(\n\t\t\t\t\tenvelope.message ?? fallback,\n\t\t\t\t\tretryAfter,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tconst retryAfterSeconds = parseRetryAfter(retryAfter);\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\tenvelope.message ??\n\t\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t\tretryAfterSeconds !== undefined ? { retryAfterSeconds } : {},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new ApiError(\n\t\t\t\tresponse.status,\n\t\t\t\tenvelope.message ?? `HTTP ${response.status}`,\n\t\t\t\tenvelope.body,\n\t\t\t\tenvelope.code,\n\t\t\t);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
8
8
  "import {\n\tblockEndCursor,\n\tdecodeStreamsCursor,\n\tencodeStreamsCursor,\n} from \"@secondlayer/shared\";\nimport { ValidationError } from \"./errors.ts\";\n\n/**\n * Helpers for Streams cursors. A cursor is the opaque `<block>:<index>` string\n * that marks a position in the event stream; treat the format as an\n * implementation detail and go through these helpers instead of string-building\n * it at call sites. Encode/decode and the rewind sentinel come from the\n * canonical codec in `@secondlayer/shared` so the SDK cannot accept a spelling\n * the server would 400, or rewind to a different foot than Index/Streams.\n */\nexport const Cursor = {\n\t/**\n\t * Cursor at the foot of `height` — a position that sorts strictly below the\n\t * first event of block `height` (`height:0`) and strictly above every event\n\t * of block `height - 1`. Cursors are exclusive (`(bh,ei) > after`), so\n\t * resuming from it re-reads the entire canonical run starting at `height:0`\n\t * inclusive. This is the position to rewind to after a reorg whose fork point\n\t * is `height`: the new canonical block at `height` carries a fresh first\n\t * event at `(height, 0)` that the consumer MUST re-read.\n\t *\n\t * Encoded as `blockEndCursor(height - 1)` rather than the seemingly-natural\n\t * `${height}:0` — that earlier form was an off-by-one: being exclusive, it\n\t * skipped `(height, 0)`, silently dropping the fork block's first row on\n\t * every reorg. The sentinel is int4 max (the `event_index`/`tx_index` column\n\t * type), larger than any real index, so nothing at `height - 1` survives the\n\t * keyset and the next returned row is exactly `(height, 0)`.\n\t *\n\t * `atHeight(0)` is `null`: the pre-genesis position both consume loops\n\t * accept as \"read everything from the first event\". There is no string\n\t * cursor below `0:0`, and `0:0` itself is exclusive, so returning it here\n\t * skipped the genesis event.\n\t */\n\tatHeight(height: number): string | null {\n\t\tif (height <= 0) return null;\n\t\treturn encodeStreamsCursor(blockEndCursor(height - 1));\n\t},\n\n\t/** Parse a `<block>:<index>` cursor. Throws `ValidationError` if malformed. */\n\tparse(cursor: string): { blockHeight: number; eventIndex: number } {\n\t\ttry {\n\t\t\tconst decoded = decodeStreamsCursor(cursor);\n\t\t\treturn {\n\t\t\t\tblockHeight: decoded.block_height,\n\t\t\t\teventIndex: decoded.event_index,\n\t\t\t};\n\t\t} catch {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`Invalid stream cursor \"${cursor}\"; expected \"<block>:<index>\" (e.g. \"951475:3\").`,\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t},\n};\n",
9
9
  "// AuthError / RateLimitError / ValidationError are shared across the whole SDK\n// (Index and the platform clients throw them too) and live in ../errors.ts —\n// re-exported here so `@secondlayer/sdk/streams` imports keep working.\nimport { parseErrorEnvelope } from \"../base.ts\";\nimport {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tSecondLayerError,\n\tValidationError,\n} from \"../errors.ts\";\n\nexport { AuthError, RateLimitError, ValidationError } from \"../errors.ts\";\n\n/** Thrown on a 5xx from the Streams API, and on a failed signing-key fetch.\n * `retryable`: the page retry policy tries again. */\nexport class StreamsServerError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown, code?: string) {\n\t\tsuper(status, message, body, code, { retryable: true });\n\t\tthis.name = \"StreamsServerError\";\n\t}\n}\n\n/** Thrown when response signature verification is enabled and fails. */\nexport class StreamsSignatureError extends SecondLayerError {\n\tconstructor(message = \"Streams response signature verification failed.\") {\n\t\tsuper(message);\n\t\tthis.name = \"StreamsSignatureError\";\n\t}\n}\n\n/** Map a non-OK Streams response onto the SDK error family. The server's\n * `{error, code}` envelope survives on `message`/`code`/`body`, the same way\n * it does on Index reads, so `err.code === \"CURSOR_INVALID\"` branches the\n * same whichever client raised it. */\nexport async function mapStreamsError(response: Response): Promise<never> {\n\tconst { message, code, body } = parseErrorEnvelope(await response.text());\n\n\tif (response.status === 401) {\n\t\tthrow new AuthError(message ?? \"API key invalid or expired.\", body, code);\n\t}\n\n\tif (response.status === 429) {\n\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\t\tthrow new RateLimitError(\n\t\t\tmessage ?? \"Rate limited. Try again later.\",\n\t\t\tretryAfter,\n\t\t\tbody,\n\t\t\tcode,\n\t\t);\n\t}\n\n\tif (response.status >= 500) {\n\t\tthrow new StreamsServerError(\n\t\t\tmessage ?? `Streams server returned ${response.status}.`,\n\t\t\tresponse.status,\n\t\t\tbody,\n\t\t\tcode,\n\t\t);\n\t}\n\n\tthrow new ValidationError(\n\t\tmessage ?? `Streams request returned ${response.status}.`,\n\t\tresponse.status,\n\t\tbody,\n\t\tcode,\n\t);\n}\n",
10
10
  "import type { ConsumerSink, WithSinkTx } from \"../sinks/types.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { ValidationError } from \"./errors.ts\";\nimport type {\n\tConsumerBatchContext,\n\tStreamsBatch,\n\tStreamsEvent,\n\tStreamsEventsEnvelope,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorg,\n\tStreamsReorgsListEnvelope,\n} from \"./types.ts\";\n\n/** Stable identity of a reorg, for in-memory dedup across re-reported pages. */\nfunction reorgKey(reorg: StreamsReorg): string {\n\treturn `${reorg.detected_at}|${reorg.fork_point_height}|${reorg.new_canonical_tip}`;\n}\n\n/** Default ceiling on how far below the checkpoint one reorg may rewind. */\nexport const DEFAULT_MAX_ROLLBACK_DEPTH = 1000;\n\n/** What one call to {@link applyReorgs} did. `null` when nothing rewound. */\nexport type ReorgRewind = {\n\t/** Lowest fork point rolled back. */\n\tforkPoint: number;\n\t/** Cursor to resume from: the foot of `forkPoint`, or `null` (pre-genesis). */\n\tcursor: string | null;\n};\n\n/**\n * Apply a page's (or the reorg list's) reorgs against the consumer's position.\n * Shared by the Streams and Index loops so the two cannot drift on the one\n * rule that decides data loss: NEVER rewind forward.\n *\n * A reorg is only actionable when its fork point is at or below the height\n * the cursor has reached (`fork_point_height <= resumeHeight(cursor)`).\n * Servers attach every reorg whose orphaned span intersects the page span, so\n * a page read from below the fork carries a reorg the consumer has not\n * written past yet. Rewinding to it would move the cursor FORWARD and skip\n * every row between the checkpoint and the fork, durably once a sink commits\n * the rewound cursor. Those reorgs are marked handled and left alone: the\n * page itself is already the canonical chain.\n *\n * Every fresh reorg is validated BEFORE the sink sees any of them: the fork\n * point must be a non-negative safe integer, and the rewind may not reach\n * more than `maxRollbackDepth` blocks below the checkpoint unless the caller\n * raised the ceiling. `fork_point_height` drives a `DELETE ... >= fork` on\n * every declared table, so a malformed or hostile value is refused loudly\n * rather than executed.\n */\nexport async function applyReorgs<\n\tTReorg extends { fork_point_height: number },\n>(opts: {\n\treorgs: readonly TReorg[];\n\tcursor: string | null;\n\t/** In-memory dedup across re-reported pages; mutated. */\n\thandled: Set<string>;\n\tkeyOf: (reorg: TReorg) => string;\n\tsink?: Pick<ConsumerSink<unknown>, \"rollback\">;\n\tonReorg?: (\n\t\treorg: TReorg,\n\t\tctx: { cursor: string | null },\n\t) => Promise<void> | void;\n\tmaxRollbackDepth?: number;\n}): Promise<ReorgRewind | null> {\n\tconst fresh = opts.reorgs.filter(\n\t\t(reorg) => !opts.handled.has(opts.keyOf(reorg)),\n\t);\n\tif (fresh.length === 0) return null;\n\n\tfor (const reorg of fresh) {\n\t\tconst fork = reorg.fork_point_height;\n\t\tif (!Number.isSafeInteger(fork) || fork < 0) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`Reorg fork_point_height ${String(fork)} is not a non-negative integer. Rollback deletes every row at or above the fork from every declared table, so a malformed fork point is refused before the sink runs.`,\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst position = resumeHeight(opts.cursor);\n\tconst applicable = fresh\n\t\t.filter((reorg) => position !== null && reorg.fork_point_height <= position)\n\t\t.sort((a, b) => a.fork_point_height - b.fork_point_height);\n\t// Fork above the checkpoint: nothing at or past it has been written, and\n\t// the page being read is already the new chain. Remember it, do not move.\n\tfor (const reorg of fresh) {\n\t\tif (!applicable.includes(reorg)) opts.handled.add(opts.keyOf(reorg));\n\t}\n\tif (applicable.length === 0 || position === null) return null;\n\n\tconst forkPoint = applicable[0]?.fork_point_height ?? position;\n\tconst depth = position - forkPoint;\n\tconst maxDepth = opts.maxRollbackDepth ?? DEFAULT_MAX_ROLLBACK_DEPTH;\n\tif (depth > maxDepth) {\n\t\tthrow new ValidationError(\n\t\t\t`Reorg at fork ${forkPoint} rewinds ${depth} blocks below the checkpoint at height ${position}, past maxRollbackDepth (${maxDepth}). A rollback this deep deletes every row at or above the fork from every declared table. Confirm the source is trusted, then pass maxRollbackDepth: ${depth} or higher to allow it.`,\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst rewind = Cursor.atHeight(forkPoint);\n\tfor (const reorg of applicable) {\n\t\t// Sink first: rollback + rewound cursor commit atomically. A user\n\t\t// onReorg (if any) runs after, for observability.\n\t\tawait opts.sink?.rollback(reorg.fork_point_height, rewind);\n\t\tawait opts.onReorg?.(reorg, { cursor: rewind });\n\t\topts.handled.add(opts.keyOf(reorg));\n\t}\n\treturn { forkPoint, cursor: rewind };\n}\n\ntype StreamsEventsFetchParams = {\n\tcursor?: string | null;\n\tlimit: number;\n\t/** `bitcoin` reads Runes events instead of the Stacks default (plan 059).\n\t * See {@link StreamsEventsStreamParams.chain}'s untyped-events caveat. */\n\tchain?: \"stacks\" | \"bitcoin\";\n\ttypes?: readonly string[];\n\tnotTypes?: readonly string[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** `chain: \"bitcoin\"` only — a RuneRef (id or name). */\n\trune?: string;\n\t/** `chain: \"bitcoin\"` only — a mainnet address. */\n\taddress?: string;\n\t/** Labelled filter groups, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n};\n\nexport type StreamsEventsFetcher = (\n\tparams: StreamsEventsFetchParams,\n) => Promise<StreamsEventsEnvelope>;\n\nexport type Sleep = (ms: number, signal?: AbortSignal) => Promise<void>;\n\n/**\n * Guard the `finalizedOnly` checkpoint contract. Shared by both loops.\n *\n * In `finalizedOnly` mode the unfinalized tail is filtered OUT of the batch\n * and re-read next poll — and `onReorg` is skipped entirely, so nothing ever\n * re-reads a range the cursor has passed. Returning a cursor above the last\n * delivered finalized event (e.g. `envelope.next_cursor`, which points past\n * the filtered tail) therefore drops those events permanently and silently.\n * Throw instead: this is the one wrong return the loop can detect.\n */\nexport function assertFinalizedCheckpoint(\n\t// biome-ignore lint/suspicious/noConfusingVoidType: mirrors the onBatch return union it validates\n\treturned: string | null | undefined | void,\n\tcheckpoint: string | null,\n): void {\n\tif (returned === null || returned === undefined) return;\n\tif (returned === checkpoint) return;\n\tconst r = Cursor.parse(returned);\n\tconst c = checkpoint === null ? null : Cursor.parse(checkpoint);\n\tconst above =\n\t\tc === null ||\n\t\tr.blockHeight > c.blockHeight ||\n\t\t(r.blockHeight === c.blockHeight && r.eventIndex > c.eventIndex);\n\tif (above) {\n\t\tconst boundary = c ? ` (\"${checkpoint}\")` : \" (none delivered yet)\";\n\t\tthrow new ValidationError(\n\t\t\t`onBatch returned cursor \"${returned}\", above the last delivered finalized event${boundary}. With finalizedOnly, events past that point were filtered out and will be re-read once finalized — committing beyond it skips them permanently. Return ctx.cursor (or nothing); never envelope.next_cursor.`,\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/**\n * Fail fast on an impossible sink/mode pairing. Shared by both loops, checked\n * BEFORE the first fetch and before `loadCursor`: a `finalizedOnly` sink\n * (append-only store — cannot undo committed rows) following the unfinalized\n * tip would corrupt on the first fork, and the corruption is silent until the\n * fork happens. Throwing at startup is the only loud moment available.\n */\nexport function assertSinkModeCompatible(\n\tsink: Pick<ConsumerSink, \"capabilities\"> | undefined,\n\tfinalizedOnly: boolean,\n): void {\n\tif (sink?.capabilities?.finalizedOnly && !finalizedOnly) {\n\t\tthrow new ValidationError(\n\t\t\t\"This sink declares capabilities.finalizedOnly — it cannot roll back reorged rows, and following the unfinalized tip would corrupt it at the first fork. Pass finalizedOnly: true to consume(), or use a sink that implements rollback.\",\n\t\t\t400,\n\t\t);\n\t}\n}\n\n/**\n * The height a resume cursor implies — seeds the loop's \"highest block\n * reached\" so a consumer restarted into a quiet tail reports its true\n * position (`checkpoint`, `height`, `blocksBehind`) instead of `null`s\n * until the first delivered row. Lenient: an unparseable cursor seeds\n * nothing and is left for the server to reject.\n */\nexport function resumeHeight(cursor: string | null): number | null {\n\tif (cursor === null) return null;\n\ttry {\n\t\treturn Cursor.parse(cursor).blockHeight;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Build the ctx handed to `onBatch`. Shared by the Streams and Index loops so\n * the two can't drift on what \"progress\" means. `blocksBehind` measures the\n * consumer's BACKLOG (`tip - scannedHeight`), not the age of the last\n * delivered event — a caught-up tail on a quiet contract is 0 behind. */\nexport function batchContext<TTip extends { block_height: number }, TReorg>(\n\tcursor: string | null,\n\theight: number | null,\n\ttip: TTip,\n\treorgs: readonly TReorg[] = [],\n\tscannedHeight: number | null = null,\n): ConsumerBatchContext<TTip, TReorg> {\n\tconst tipHeight = tip.block_height;\n\tconst position = scannedHeight ?? height;\n\treturn {\n\t\tcursor,\n\t\theight,\n\t\tscannedHeight: position,\n\t\ttipHeight,\n\t\tblocksBehind: position === null ? null : Math.max(0, tipHeight - position),\n\t\ttip,\n\t\treorgs,\n\t};\n}\n\n/** Options shared by both consume loops' page-fetch retry. Vocabulary matches\n * `@secondlayer/stacks` transports (`retryCount`/`retryDelay`) — one retry\n * language across the family, not a third. */\nexport type PageRetryOptions = {\n\t/** Retries after the first failure. Default 3; `0` disables. */\n\tretryCount?: number;\n\t/** Base delay in ms; the n-th retry waits `retryDelay * n` (matches the\n\t * stacks transport). A server `Retry-After` overrides it. Default 1000. */\n\tretryDelay?: number;\n\t/** Void observer, called before each retry sleep (metrics/logging). The\n\t * retry policy owns the decision; this cannot change it. */\n\tonError?: (\n\t\terr: unknown,\n\t\tctx: { attempt: number; retriesLeft: number; delayMs: number },\n\t) => void;\n};\n\n/** Sleep clamp for a server `Retry-After`: the loop honors the header up to\n * five minutes per attempt and keeps retrying within `retryCount`. It never\n * gives up early on a long Retry-After; the tradeoff is a long wait, not a\n * dropped loop. Set `retryCount: 0` to surface the 429 immediately instead. */\nconst MAX_RETRY_AFTER_MS = 300_000;\n\nfunction errRetryable(err: unknown): boolean {\n\t// SecondLayerError family carries an explicit signal; a bare TypeError is\n\t// the raw fetch network failure (Streams' fetchImpl isn't wrapped).\n\tif (err && typeof err === \"object\" && \"retryable\" in err) {\n\t\treturn (err as { retryable: unknown }).retryable === true;\n\t}\n\treturn err instanceof TypeError;\n}\n\nfunction errRetryAfterMs(err: unknown): number | undefined {\n\tif (err && typeof err === \"object\" && \"retryAfterSeconds\" in err) {\n\t\tconst seconds = (err as { retryAfterSeconds: unknown }).retryAfterSeconds;\n\t\tif (typeof seconds === \"number\" && Number.isFinite(seconds)) {\n\t\t\treturn Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Run one page fetch with retries. Scoped to the FETCH only — never the loop\n * body: retrying after an `onReorg`/`onBatch` throw would re-enter with\n * `handledReorgs` partially mutated and skip a rollback silently. `onBatch`\n * and `onReorg` throws always propagate to the caller.\n */\nexport async function fetchPageWithRetry<T>(\n\tfetchPage: () => Promise<T>,\n\topts: PageRetryOptions & { sleep: Sleep; signal?: AbortSignal },\n): Promise<T> {\n\tconst retryCount = opts.retryCount ?? 3;\n\tconst retryDelay = opts.retryDelay ?? 1000;\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await fetchPage();\n\t\t} catch (err) {\n\t\t\tconst retriesLeft = retryCount - attempt;\n\t\t\tif (retriesLeft <= 0 || !errRetryable(err) || opts.signal?.aborted) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tconst delayMs = errRetryAfterMs(err) ?? retryDelay * (attempt + 1);\n\t\t\topts.onError?.(err, { attempt, retriesLeft, delayMs });\n\t\t\tawait opts.sleep(delayMs, opts.signal);\n\t\t\t// Aborted mid-sleep: surface the original failure, not a fresh fetch.\n\t\t\tif (opts.signal?.aborted) throw err;\n\t\t}\n\t}\n}\n\nexport async function defaultSleep(\n\tms: number,\n\tsignal?: AbortSignal,\n): Promise<void> {\n\tif (signal?.aborted) return;\n\n\tawait new Promise<void>((resolve) => {\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve();\n\t\t};\n\t\t// Detach on the timer path too: a tail at the tip sleeps once per\n\t\t// empty poll, and each sleep that left its listener behind pinned a\n\t\t// closure on the caller's long-lived signal until the process exited.\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nexport async function consumeStreamsEvents<TTx = never>(opts: {\n\tfromCursor?: string | null;\n\tmode?: \"tail\" | \"bounded\";\n\tfinalizedOnly?: boolean;\n\tbatchSize: number;\n\tchain?: \"stacks\" | \"bitcoin\";\n\ttypes?: readonly string[];\n\tnotTypes?: readonly string[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\trune?: string;\n\taddress?: string;\n\t/** Labelled filter groups, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\t/** `GET /v1/streams/reorgs`, polled on idle (empty) pages so a reorg\n\t * that lands while the consumer sits at the tip is still rolled back.\n\t * Pages only carry reorgs overlapping their own span. */\n\tfetchReorgs?: (params: {\n\t\tsince: string;\n\t}) => Promise<StreamsReorgsListEnvelope>;\n\t/** Destination adapter owning checkpoint + rollback (see IndexConsumeOptions.sink). */\n\tsink?: ConsumerSink<TTx>;\n\t/** Fires once per page, before `onBatch` and any early return. */\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tonBatch: (\n\t\tevents: StreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope,\n\t\tctx: ConsumerBatchContext & WithSinkTx<TTx>,\n\t) =>\n\t\t| void\n\t\t| string\n\t\t| null\n\t\t| undefined\n\t\t| Promise<void>\n\t\t| Promise<string | null | undefined>;\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: { cursor: string | null },\n\t) => Promise<void> | void;\n\t/** Deepest rewind one reorg may make below the checkpoint. Default 1000. */\n\tmaxRollbackDepth?: number;\n\tsleep?: Sleep;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tretryCount?: number;\n\tretryDelay?: number;\n\tonError?: PageRetryOptions[\"onError\"];\n\tsignal?: AbortSignal;\n\t/** Cuts the empty-poll backoff short — see the field doc on\n\t * {@link StreamsEventsConsumeParams.wake} (same contract). */\n\twake?: () => Promise<void>;\n}): Promise<{ cursor: string | null; pages: number; emptyPolls: number }> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tconst mode = opts.mode ?? \"tail\";\n\tconst finalizedOnly = opts.finalizedOnly ?? false;\n\tconst emptyBackoffMs = opts.emptyBackoffMs ?? 500;\n\tconst maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;\n\tconst maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;\n\tassertSinkModeCompatible(opts.sink, finalizedOnly);\n\t// Resume order: explicit fromCursor, then the sink's committed checkpoint.\n\t// `loadCursor` is also the sink's INIT — it creates the checkpoint table and\n\t// validates the rollback precondition. Short-circuiting it on an explicit\n\t// `fromCursor` meant a replay-from-cursor run crashed on its first commit,\n\t// and skipped the height-column check that keeps reorg rollback from being\n\t// a silent no-op. Always initialize; `fromCursor` still wins as the resume\n\t// position.\n\tconst committedCursor = (await opts.sink?.loadCursor()) ?? null;\n\tlet cursor = opts.fromCursor ?? committedCursor;\n\t// In-memory only: rollback is idempotent, so a crash before the rewind is\n\t// re-detected and re-applied harmlessly on restart — no need to persist.\n\tconst handledReorgs = new Set<string>();\n\t// Resume token for the idle-tip reorg list; `null` until the first idle\n\t// poll with a checkpoint to seed it from.\n\tlet reorgSince: string | null = null;\n\tlet pages = 0;\n\tlet emptyPolls = 0;\n\t// Highest block reached, carried across empty pages so a caught-up tail\n\t// keeps reporting its position instead of dropping to null. Seeded from\n\t// the resume cursor: a restart into a quiet tail knows where it stands\n\t// before the first row lands.\n\tlet height: number | null = resumeHeight(cursor);\n\t// Highest block VERIFIED — how far the sweep is actually caught up, as\n\t// opposed to `height` (last delivered row). Starts at the resume position;\n\t// each page moves it (see below).\n\tlet scanned: number | null = height;\n\n\twhile (\n\t\tpages < maxPages &&\n\t\temptyPolls < maxEmptyPolls &&\n\t\t!opts.signal?.aborted\n\t) {\n\t\t// Retry wraps ONLY the page fetch: one transient 429/5xx must not kill\n\t\t// an hours-long backfill, and handler throws must never be re-entered.\n\t\tconst envelope = await fetchPageWithRetry(\n\t\t\t() =>\n\t\t\t\topts.fetchEvents({\n\t\t\t\t\tcursor,\n\t\t\t\t\tlimit: opts.batchSize,\n\t\t\t\t\tchain: opts.chain,\n\t\t\t\t\ttypes: opts.types,\n\t\t\t\t\tnotTypes: opts.notTypes,\n\t\t\t\t\tcontractId: opts.contractId,\n\t\t\t\t\tsender: opts.sender,\n\t\t\t\t\trecipient: opts.recipient,\n\t\t\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\t\t\trune: opts.rune,\n\t\t\t\t\taddress: opts.address,\n\t\t\t\t\tfilters: opts.filters,\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tretryCount: opts.retryCount,\n\t\t\t\tretryDelay: opts.retryDelay,\n\t\t\t\tonError: opts.onError,\n\t\t\t\tsleep,\n\t\t\t\tsignal: opts.signal,\n\t\t\t},\n\t\t);\n\t\tpages++;\n\n\t\t// Reorgs: roll back each new fork at or below the checkpoint, then\n\t\t// rewind to the lowest fork point and re-read the now-canonical run.\n\t\t// Finalized data never reorgs, so `finalizedOnly` skips this entirely.\n\t\t// A sink makes rollback UNCONDITIONAL: omitting `onReorg` used to skip\n\t\t// reorgs silently.\n\t\tconst reorgsOn = !finalizedOnly && Boolean(opts.onReorg || opts.sink);\n\t\tif (reorgsOn) {\n\t\t\tconst rewound = await applyReorgs({\n\t\t\t\treorgs: envelope.reorgs,\n\t\t\t\tcursor,\n\t\t\t\thandled: handledReorgs,\n\t\t\t\tkeyOf: reorgKey,\n\t\t\t\tsink: opts.sink,\n\t\t\t\tonReorg: opts.onReorg,\n\t\t\t\tmaxRollbackDepth: opts.maxRollbackDepth,\n\t\t\t});\n\t\t\tif (rewound) {\n\t\t\t\tcursor = rewound.cursor;\n\t\t\t\t// Everything at and above the fork is no longer canonical, so the\n\t\t\t\t// reached height rolls back with it — including the verified\n\t\t\t\t// position: the new chain above the fork is unread.\n\t\t\t\theight = rewound.forkPoint > 0 ? rewound.forkPoint - 1 : null;\n\t\t\t\tscanned = height;\n\t\t\t\temptyPolls = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Idle tip: a page only reports reorgs overlapping its own span, so a\n\t\t// fork that lands while the consumer sits at the tip (orphaning rows\n\t\t// BELOW the next non-empty page) is never on a page. On an empty page\n\t\t// ask the reorg list instead: one extra request per idle poll. Seeded\n\t\t// from the checkpoint cursor (the API reads a cursor as \"reorgs that\n\t\t// orphaned anything at or above this position\"), then advanced by the\n\t\t// list's own `next_since` token.\n\t\tif (reorgsOn && opts.fetchReorgs && envelope.events.length === 0) {\n\t\t\treorgSince ??= cursor;\n\t\t\tif (reorgSince !== null) {\n\t\t\t\tconst since: string = reorgSince;\n\t\t\t\tconst fetchReorgs = opts.fetchReorgs;\n\t\t\t\tconst listed: StreamsReorgsListEnvelope = await fetchPageWithRetry(\n\t\t\t\t\t() => fetchReorgs({ since }),\n\t\t\t\t\t{\n\t\t\t\t\t\tretryCount: opts.retryCount,\n\t\t\t\t\t\tretryDelay: opts.retryDelay,\n\t\t\t\t\t\tonError: opts.onError,\n\t\t\t\t\t\tsleep,\n\t\t\t\t\t\tsignal: opts.signal,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (listed.next_since !== null) reorgSince = listed.next_since;\n\t\t\t\tconst rewound = await applyReorgs({\n\t\t\t\t\treorgs: listed.reorgs,\n\t\t\t\t\tcursor,\n\t\t\t\t\thandled: handledReorgs,\n\t\t\t\t\tkeyOf: reorgKey,\n\t\t\t\t\tsink: opts.sink,\n\t\t\t\t\tonReorg: opts.onReorg,\n\t\t\t\t\tmaxRollbackDepth: opts.maxRollbackDepth,\n\t\t\t\t});\n\t\t\t\tif (rewound) {\n\t\t\t\t\tcursor = rewound.cursor;\n\t\t\t\t\theight = rewound.forkPoint > 0 ? rewound.forkPoint - 1 : null;\n\t\t\t\t\tscanned = height;\n\t\t\t\t\temptyPolls = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst emitted = finalizedOnly\n\t\t\t? envelope.events.filter((event) => event.finalized)\n\t\t\t: envelope.events;\n\t\t// Only advance to the last finalized event in finalizedOnly mode; the\n\t\t// unfinalized tail is re-read next poll until it settles.\n\t\tconst checkpoint = finalizedOnly\n\t\t\t? (emitted.at(-1)?.cursor ?? cursor)\n\t\t\t: envelope.next_cursor;\n\t\t// Ascending cursor order, so the last row is the highest block this page\n\t\t// reached; an empty page keeps the previous value.\n\t\theight = emitted.at(-1)?.block_height ?? height;\n\t\t// Verified position. Rows delivered → through the last row (the page\n\t\t// limit hides what's above it). Empty page with an ADVANCED cursor →\n\t\t// through that cursor only (a server may cap an expensive filtered\n\t\t// scan; claiming the tip would overstate). Truly empty page → the\n\t\t// server confirmed nothing matches up to the tip. Non-empty raw page\n\t\t// fully filtered (unfinalized tail) → position unchanged.\n\t\tif (emitted.length > 0) {\n\t\t\tscanned = height;\n\t\t} else if (checkpoint !== null && checkpoint !== cursor) {\n\t\t\tscanned = resumeHeight(checkpoint) ?? scanned;\n\t\t} else if (envelope.events.length === 0) {\n\t\t\tscanned = envelope.tip.block_height;\n\t\t}\n\n\t\t// An empty page reports the STANDING cursor, not null: the committed\n\t\t// checkpoint is still this consumer's position while it idles.\n\t\tconst ctx = batchContext(\n\t\t\tcheckpoint ?? cursor,\n\t\t\theight,\n\t\t\tenvelope.tip,\n\t\t\tenvelope.reorgs,\n\t\t\tscanned,\n\t\t);\n\t\t// Before any early return: an empty page still proves the loop is alive.\n\t\topts.onProgress?.(ctx);\n\n\t\tlet nextCursor: string | null;\n\t\tif (opts.sink) {\n\t\t\tconst sink = opts.sink;\n\t\t\t// Rows and cursor commit in ONE transaction; a handler throw aborts\n\t\t\t// both. Nothing moved → nothing to commit, handler not invoked.\n\t\t\tif (\n\t\t\t\tcheckpoint !== null &&\n\t\t\t\t(checkpoint !== cursor || emitted.length > 0)\n\t\t\t) {\n\t\t\t\tawait sink.commitBatch(checkpoint, async (tx) => {\n\t\t\t\t\t// The cast is sound exactly as far as the sink's own typing:\n\t\t\t\t\t// `sink: ConsumerSink<TTx>` binds TTx, and `tx` here is what its\n\t\t\t\t\t// commitBatch lends. Nothing verifies it at runtime — a sink whose\n\t\t\t\t\t// declared Tx lies about what it lends fails inside the handler.\n\t\t\t\t\tawait opts.onBatch(emitted, envelope, {\n\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\ttx,\n\t\t\t\t\t} as ConsumerBatchContext & WithSinkTx<TTx>);\n\t\t\t\t});\n\t\t\t}\n\t\t\tnextCursor = checkpoint;\n\t\t} else {\n\t\t\tconst returnedCursor = await opts.onBatch(\n\t\t\t\temitted,\n\t\t\t\tenvelope,\n\t\t\t\tctx as ConsumerBatchContext & WithSinkTx<TTx>,\n\t\t\t);\n\t\t\tif (finalizedOnly) assertFinalizedCheckpoint(returnedCursor, checkpoint);\n\t\t\tnextCursor = returnedCursor ?? checkpoint;\n\t\t}\n\n\t\tif (nextCursor && nextCursor !== cursor) {\n\t\t\tcursor = nextCursor;\n\t\t\temptyPolls = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (emitted.length === 0) {\n\t\t\temptyPolls++;\n\t\t\tif (mode === \"bounded\") {\n\t\t\t\treturn { cursor, pages, emptyPolls };\n\t\t\t}\n\t\t\t// The backoff timer always runs underneath — a `wake` that never\n\t\t\t// resolves, rejects (e.g. a dropped LISTEN connection), or isn't\n\t\t\t// supplied at all falls back to exactly the old poll-only behavior.\n\t\t\t// Racing (not replacing) it means a broken wake source degrades to\n\t\t\t// plain polling, never a stall. A rejection must NOT resolve the\n\t\t\t// race early — swallowing it into a promise that never settles (not\n\t\t\t// `.catch(() => {})`, which would resolve immediately and defeat the\n\t\t\t// backoff entirely) is what makes \"wake is broken\" behave exactly\n\t\t\t// like \"no wake at all\".\n\t\t\tawait (opts.wake\n\t\t\t\t? Promise.race([\n\t\t\t\t\t\tsleep(emptyBackoffMs, opts.signal),\n\t\t\t\t\t\topts.wake().catch(() => new Promise<never>(() => {})),\n\t\t\t\t\t])\n\t\t\t\t: sleep(emptyBackoffMs, opts.signal));\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn { cursor, pages, emptyPolls };\n\t}\n\n\treturn { cursor, pages, emptyPolls };\n}\n\n/**\n * Async-iterator form of the Streams pull loop, yielding one {@link StreamsBatch}\n * per fetched page. Each yield maps 1:1 onto a `GET /v1/streams/events` envelope\n * (`{ events, next_cursor, tip, reorgs }` → `{ events, cursor, tip, reorgs }`) —\n * no extra API calls, no regrouping. Pages with no events and no reorgs are not\n * yielded; the iterator sleeps `intervalMs` and re-polls the tip instead.\n */\nexport async function* iterateStreamsBatches(opts: {\n\tfromCursor?: string | null;\n\tbatchSize: number;\n\tintervalMs: number;\n\tchain?: \"stacks\" | \"bitcoin\";\n\ttypes?: readonly string[];\n\tnotTypes?: readonly string[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\trune?: string;\n\taddress?: string;\n\t/** Labelled filter groups, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\tsleep?: Sleep;\n\tsignal?: AbortSignal;\n}): AsyncGenerator<StreamsBatch> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tlet cursor = opts.fromCursor ?? null;\n\n\twhile (!opts.signal?.aborted) {\n\t\tconst envelope = await opts.fetchEvents({\n\t\t\tcursor,\n\t\t\tlimit: opts.batchSize,\n\t\t\tchain: opts.chain,\n\t\t\ttypes: opts.types,\n\t\t\tnotTypes: opts.notTypes,\n\t\t\tcontractId: opts.contractId,\n\t\t\tsender: opts.sender,\n\t\t\trecipient: opts.recipient,\n\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\trune: opts.rune,\n\t\t\taddress: opts.address,\n\t\t\tfilters: opts.filters,\n\t\t});\n\n\t\tconst checkpoint = envelope.next_cursor ?? cursor;\n\t\tif (envelope.events.length > 0 || envelope.reorgs.length > 0) {\n\t\t\tyield {\n\t\t\t\tevents: envelope.events,\n\t\t\t\tcursor: checkpoint,\n\t\t\t\ttip: envelope.tip,\n\t\t\t\treorgs: envelope.reorgs,\n\t\t\t};\n\t\t}\n\n\t\tconst advanced = checkpoint !== null && checkpoint !== cursor;\n\t\tcursor = checkpoint;\n\t\t// Caught up at the tip: wait one poll interval before re-reading.\n\t\tif (!advanced && envelope.events.length === 0) {\n\t\t\tif (opts.signal?.aborted) return;\n\t\t\tawait sleep(opts.intervalMs, opts.signal);\n\t\t}\n\t}\n}\n\nexport async function* streamStreamsEvents(opts: {\n\tfromCursor?: string | null;\n\tbatchSize: number;\n\tchain?: \"stacks\" | \"bitcoin\";\n\ttypes?: readonly string[];\n\tnotTypes?: readonly string[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\trune?: string;\n\taddress?: string;\n\t/** Labelled filter groups, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\n\tsleep?: Sleep;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n}): AsyncGenerator<StreamsEvent> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tconst emptyBackoffMs = opts.emptyBackoffMs ?? 500;\n\tconst maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;\n\tconst maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;\n\tlet cursor = opts.fromCursor ?? null;\n\tlet pages = 0;\n\tlet emptyPolls = 0;\n\n\twhile (\n\t\tpages < maxPages &&\n\t\temptyPolls < maxEmptyPolls &&\n\t\t!opts.signal?.aborted\n\t) {\n\t\tconst envelope = await opts.fetchEvents({\n\t\t\tcursor,\n\t\t\tlimit: opts.batchSize,\n\t\t\tchain: opts.chain,\n\t\t\ttypes: opts.types,\n\t\t\tnotTypes: opts.notTypes,\n\t\t\tcontractId: opts.contractId,\n\t\t\tsender: opts.sender,\n\t\t\trecipient: opts.recipient,\n\t\t\tassetIdentifier: opts.assetIdentifier,\n\t\t\trune: opts.rune,\n\t\t\taddress: opts.address,\n\t\t\tfilters: opts.filters,\n\t\t});\n\t\tpages++;\n\n\t\tfor (const event of envelope.events) {\n\t\t\tif (opts.signal?.aborted) return;\n\t\t\tyield event;\n\t\t}\n\n\t\tconst nextCursor = envelope.next_cursor;\n\t\tif (nextCursor && nextCursor !== cursor) {\n\t\t\tcursor = nextCursor;\n\t\t\temptyPolls = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (envelope.events.length === 0) {\n\t\t\temptyPolls++;\n\t\t\tif (emptyPolls >= maxEmptyPolls || pages >= maxPages) return;\n\t\t\tawait sleep(emptyBackoffMs, opts.signal);\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn;\n\t}\n}\n",
@@ -14,7 +14,7 @@
14
14
  "export { createStreamsClient } from \"./client.ts\";\nexport { decode } from \"./decode.ts\";\nexport {\n\tAuthError,\n\tRateLimitError,\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tValidationError,\n} from \"./errors.ts\";\n// ── Per-type guard+decode pairs ─────────────────────────────────────────\n// @deprecated (whole block): these 22 helpers return DB-row shapes\n// (`decoded_payload` nested, `source_cursor`) and force an 11-branch\n// guard+decode dispatch, which is the wrong default for a consumer. Use\n// `decode(event)` — one call, the same flat `event_type`-discriminated row\n// Index serves — or `decoded: true` on `streams.events.consume`.\n//\n// They are NOT going away: building a `decoded_events`-shaped projection is a\n// real use, and it is what our own decoder does. They move to the explicit\n// `@secondlayer/sdk/streams/rows` subpath at the next major, so reaching for\n// the storage shape is a deliberate act rather than the first thing autocomplete\n// offers. Import from there today.\nexport {\n\tdecodeFtTransfer,\n\tisFtTransfer,\n\tdecodeNftTransfer,\n\tisNftTransfer,\n\tdecodeStxBurn,\n\tdecodeStxLock,\n\tdecodeStxMint,\n\tdecodeStxTransfer,\n\tisStxBurn,\n\tisStxLock,\n\tisStxMint,\n\tisStxTransfer,\n\tdecodeFtBurn,\n\tdecodeFtMint,\n\tdecodeNftBurn,\n\tdecodeNftMint,\n\tisFtBurn,\n\tisFtMint,\n\tisNftBurn,\n\tisNftMint,\n\tdecodePrint,\n\tisPrint,\n} from \"@secondlayer/shared/streams-rows\";\nexport type {\n\tDecodedEventColumns,\n\tDecodedEventRow,\n\tDecodedFtBurn,\n\tDecodedFtBurnPayload,\n\tDecodedFtMint,\n\tDecodedFtMintPayload,\n\tDecodedFtTransfer,\n\tDecodedFtTransferPayload,\n\tDecodedNftBurn,\n\tDecodedNftBurnPayload,\n\tDecodedNftMint,\n\tDecodedNftMintPayload,\n\tDecodedNftTransfer,\n\tDecodedNftTransferPayload,\n\tDecodedPrint,\n\tDecodedPrintPayload,\n\tDecodedPrintValue,\n\tDecodedStxBurn,\n\tDecodedStxBurnPayload,\n\tDecodedStxLock,\n\tDecodedStxLockPayload,\n\tDecodedStxMint,\n\tDecodedStxMintPayload,\n\tDecodedStxTransfer,\n\tDecodedStxTransferPayload,\n\tFtTransferEvent,\n\tFtTransferPayload,\n\tNftTransferEvent,\n\tNftTransferPayload,\n} from \"@secondlayer/shared/streams-rows\";\nexport { STREAMS_EVENT_TYPES } from \"./types.ts\";\nexport { Cursor } from \"./cursor.ts\";\nexport type {\n\tConsumerBatchContext,\n\tFetchLike,\n\tRuneEtchEntry,\n\tRuneEventPayload,\n\tRuneEventType,\n\tRuneStreamsEvent,\n\tStreamsBatch,\n\tStreamsBatchContext,\n\tStreamsBitcoinCanonicalBlock,\n\tStreamsBitcoinTip,\n\tStreamsClient,\n\tStreamsConsumeBitcoinParams,\n\tStreamsConsumeParams,\n\tStreamsConsumeStacksParams,\n\tStreamsCanonicalBlock,\n\tStreamsDumpFile,\n\tStreamsDumps,\n\tStreamsDumpsManifest,\n\tStreamsEvent,\n\tStreamsEventPayload,\n\tStreamsWireEvent,\n\tVmStreamsEvent,\n\tStreamsEventsBitcoinListParams,\n\tStreamsEventsConsumeBitcoinParams,\n\tStreamsEventsConsumeParams,\n\tStreamsEventsConsumeResult,\n\tStreamsEventsEnvelope,\n\tStreamsEventsListEnvelope,\n\tStreamsEventsListParams,\n\tStreamsEventsStacksListParams,\n\tStreamsEventsStreamBitcoinParams,\n\tStreamsEventsStreamParams,\n\tStreamsEventsStreamStacksParams,\n\tStreamsEventsSubscribeBitcoinParams,\n\tStreamsEventsSubscribeParams,\n\tStreamsEventsSubscribeStacksParams,\n\tStreamsSubscription,\n\tStreamsEventType,\n\tStreamsReorg,\n\tStreamsReorgContext,\n\tStreamsReorgsListEnvelope,\n\tStreamsReorgsListParams,\n\tStreamsTip,\n} from \"./types.ts\";\n",
15
15
  "// Canonical event primitives (StreamsEvent, payload types, event-type vocab)\n// live in @secondlayer/shared/streams-rows; re-exported here so the public\n// Streams surface is unchanged.\nimport type { VmEventType } from \"@secondlayer/shared\";\nimport {\n\tRUNE_EVENT_TYPES,\n\ttype RuneEventType,\n\ttype RuneStreamsEvent,\n\tSTREAMS_EVENT_TYPES,\n\ttype StreamsEvent,\n\ttype StreamsEventType,\n\ttype StreamsWireEvent,\n\ttype VmStreamsEvent,\n} from \"@secondlayer/shared/streams-rows\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { ConsumerSink, WithSinkTx } from \"../sinks/types.ts\";\n\nexport {\n\tRUNE_EVENT_TYPES,\n\tSTREAMS_EVENT_TYPES,\n\ttype RuneEventType,\n\ttype RuneStreamsEvent,\n\ttype StreamsEvent,\n\ttype StreamsEventType,\n\ttype VmStreamsEvent,\n};\nexport type {\n\tFtBurnPayload,\n\tFtMintPayload,\n\tFtTransferPayload,\n\tMapDeletePayload,\n\tMapWritePayload,\n\tNestedContractCallPayload,\n\tVarSetPayload,\n\tStreamsWireEvent,\n\tNftBurnPayload,\n\tNftMintPayload,\n\tNftTransferPayload,\n\tPrintPayload,\n\tRuneEtchEntry,\n\tRuneEventPayload,\n\tStreamsClarityValue,\n\tStreamsEventBase,\n\tStreamsEventPayload,\n\tStxBurnPayload,\n\tStxLockPayload,\n\tStxMintPayload,\n\tStxTransferPayload,\n} from \"@secondlayer/shared/streams-rows\";\n\nexport type StreamsTip = {\n\tblock_height: number;\n\tblock_hash: string;\n\tburn_block_height: number;\n\t/**\n\t * Highest Stacks block past the burn-confirmation finality boundary.\n\t * Optional for back-compat; the API always sets it.\n\t */\n\tfinalized_height?: number;\n\tlag_seconds: number;\n\t/**\n\t * Oldest height still seekable on the live API for the caller's tier\n\t * (`tip - retention`). `null` = unlimited retention. Older reads must use the\n\t * cold dumps lane. Optional for back-compat.\n\t */\n\toldest_seekable_height?: number | null;\n\t/** Oldest seekable cursor (`<oldest_seekable_height>:0`); `null` = unlimited. */\n\toldest_cursor?: string | null;\n};\n\n/** `chain=bitcoin` tip (plan 059) — no `burn_block_height`/retention fields,\n * since Bitcoin has no burn chain of its own and Runes reads have no\n * retention ladder. Returned by `tip({ chain: \"bitcoin\" })`. */\nexport type StreamsBitcoinTip = {\n\tblock_height: number;\n\tblock_hash: string;\n\tfinalized_height: number;\n\tlag_seconds: number;\n};\n\nexport type StreamsCanonicalBlock = {\n\tblock_height: number;\n\tblock_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\tis_canonical: true;\n};\n\n/** `chain=bitcoin` canonical block (plan 059) — no burn-chain fields. */\nexport type StreamsBitcoinCanonicalBlock = {\n\tblock_height: number;\n\tblock_hash: string;\n\tis_canonical: true;\n};\n\nexport type StreamsReorg = {\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\t/**\n\t * First position of the new canonical chain at the fork, `fork:0`\n\t * (INCLUSIVE). Not an exclusive resume token — resuming directly from it\n\t * skips `fork:0`. The consumer rewinds to the foot of `fork_point_height`\n\t * (`Cursor.atHeight`) to re-read the new run from `fork:0` inclusive.\n\t */\n\tnew_canonical_tip: string;\n};\n\nexport type StreamsEventsEnvelope<TEvent = StreamsEvent, TTip = StreamsTip> = {\n\tevents: TEvent[];\n\tnext_cursor: string | null;\n\ttip: TTip;\n\treorgs: StreamsReorg[];\n};\n\nexport type StreamsEventsListEnvelope<\n\tTEvent = StreamsEvent,\n\tTTip = StreamsTip,\n> = Omit<StreamsEventsEnvelope<TEvent, TTip>, \"next_cursor\">;\n\n/** The StreamsEvent union narrowed to a `types` selection — what a\n * const-generic `types: [\"ft_transfer\"]` buys at the type level. */\nexport type StreamsEventOfTypes<T extends readonly StreamsEventType[]> =\n\tExtract<StreamsEvent, { event_type: T[number] }>;\n\nexport type StreamsReorgsListParams = {\n\tsince: string;\n\tlimit?: number;\n};\n\nexport type StreamsReorgsListEnvelope = {\n\treorgs: StreamsReorg[];\n\tnext_since: string | null;\n};\n\n/** A filter that matches a single value or any value in a list. */\nexport type StreamsFilterValue = string | readonly string[];\n\n/**\n * One labelled filter group. Fields inside a group AND together; groups in a\n * map OR together server-side.\n */\nexport type StreamsLabelledFilter = {\n\ttypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n};\n\n/** A map of label → filter group. Labels are yours; the server echoes them. */\nexport type StreamsFilterMap = Record<string, StreamsLabelledFilter>;\n\n/**\n * The events one label can yield. A group that declares `types` narrows to\n * exactly those variants, so a per-label handler needs no `event_type` guard;\n * a group without `types` keeps the full union.\n */\nexport type StreamsEventForFilter<F, D extends boolean = false> = F extends {\n\ttypes: readonly (infer T extends StreamsEventType)[];\n}\n\t? D extends true\n\t\t? Extract<IndexEvent, { event_type: T }>\n\t\t: Extract<StreamsEvent, { event_type: T }>\n\t: D extends true\n\t\t? IndexEvent\n\t\t: StreamsEvent;\n\ntype StreamsEventsListParamsCommon = {\n\tcursor?: string | null;\n\tfromHeight?: number;\n\ttoHeight?: number;\n\tlimit?: number;\n};\n\n/** `chain: \"stacks\"` (default, omit `chain` entirely) — unchanged since\n * before plan 059. */\nexport type StreamsEventsStacksListParams = StreamsEventsListParamsCommon & {\n\tchain?: \"stacks\";\n\t/** `vm` reads ordinal. Omit for Streams 1.0. */\n\tclock?: \"classic\" | \"vm\";\n\ttypes?: readonly (StreamsEventType | VmEventType)[];\n\t/** Event types to exclude (applied after `types`). */\n\tnotTypes?: readonly (StreamsEventType | VmEventType)[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/**\n\t * Labelled filter groups. The groups OR together in one scan and each\n\t * returned event carries the labels it matched (`event.matched`) — two\n\t * unrelated concerns share one page, one cursor, one checkpoint.\n\t */\n\tfilters?: StreamsFilterMap;\n};\n\n/**\n * `chain: \"bitcoin\"` (plan 059) — Runes events, own cursor space. `types` is\n * restricted to {@link RuneEventType} at the type level, so e.g.\n * `{ chain: \"bitcoin\", types: [\"ft_transfer\"] }` is a compile error rather\n * than a silent 400 at request time. `contractId`/`sender`/`recipient`/\n * `assetIdentifier`/`filters`/`clock` don't exist on this branch — they're\n * Stacks-only (the server 400s on them too).\n */\nexport type StreamsEventsBitcoinListParams = StreamsEventsListParamsCommon & {\n\tchain: \"bitcoin\";\n\ttypes?: readonly RuneEventType[];\n\tnotTypes?: readonly RuneEventType[];\n\t/** A RuneRef: an id (`840000:3`) or a name (`DOG•GO•TO•THE•MOON`). */\n\trune?: string;\n\t/** A mainnet address. */\n\taddress?: string;\n};\n\nexport type StreamsEventsListParams =\n\t| StreamsEventsStacksListParams\n\t| StreamsEventsBitcoinListParams;\n\ntype StreamsEventsStreamCommon = {\n\tfromCursor?: string | null;\n\tbatchSize?: number;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n};\n\n/** `chain: \"stacks\"` (default, omit `chain` entirely) — matches\n * {@link StreamsEventsStacksListParams}. */\nexport type StreamsEventsStreamStacksParams = StreamsEventsStreamCommon & {\n\tchain?: \"stacks\";\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled filter groups; see {@link StreamsEventsListParams.filters}. */\n\tfilters?: StreamsFilterMap;\n};\n\n/** `chain: \"bitcoin\"` (plan 059/061) — Runes events, tailed the same way as\n * the Stacks default. `types` is restricted to {@link RuneEventType} at the\n * type level, matching {@link StreamsEventsBitcoinListParams}.\n * `contractId`/`sender`/`recipient`/`assetIdentifier`/`filters` don't exist\n * on this branch — they're Stacks-only. */\nexport type StreamsEventsStreamBitcoinParams = StreamsEventsStreamCommon & {\n\tchain: \"bitcoin\";\n\ttypes?: readonly RuneEventType[];\n\tnotTypes?: readonly RuneEventType[];\n\t/** A RuneRef: an id (`840000:3`) or a name (`DOG•GO•TO•THE•MOON`). */\n\trune?: string;\n\t/** A mainnet address. */\n\taddress?: string;\n};\n\nexport type StreamsEventsStreamParams =\n\t| StreamsEventsStreamStacksParams\n\t| StreamsEventsStreamBitcoinParams;\n\ntype StreamsEventsSubscribeCommon = {\n\t/** Resume strictly after this cursor; omit to live-tail from the tip. */\n\tfromCursor?: string | null;\n\t/** Abort to unsubscribe (the returned function does the same). */\n\tsignal?: AbortSignal;\n\t/**\n\t * Called on every failure. Transport errors (dropped socket, 5xx, 429, a\n\t * stale connection, a throwing handler) reconnect from the last handled\n\t * cursor with exponential backoff. Errors that a retry cannot fix (401,\n\t * 4xx, a bad signature) end the subscription and reject its `done`.\n\t */\n\tonError?: (err: unknown) => void;\n\t/**\n\t * First reconnect pause in ms (default 1000). Doubles per consecutive\n\t * failure up to 30 s with jitter, resets once a frame arrives, and never\n\t * undercuts a `Retry-After`.\n\t */\n\treconnectDelayMs?: number;\n\t/**\n\t * Reconnect when no frame (pings included) arrives for this long (default\n\t * 60000, three server heartbeats). Catches a half-open socket that never\n\t * errors; set it above your instance's heartbeat interval.\n\t */\n\tstaleAfterMs?: number;\n};\n\n/** `chain: \"stacks\"` (default, omit `chain` entirely). */\nexport type StreamsEventsSubscribeStacksParams =\n\tStreamsEventsSubscribeCommon & {\n\t\tchain?: \"stacks\";\n\t\ttypes?: readonly StreamsEventType[];\n\t\tnotTypes?: readonly StreamsEventType[];\n\t\tcontractId?: StreamsFilterValue;\n\t\tsender?: StreamsFilterValue;\n\t\trecipient?: StreamsFilterValue;\n\t\tassetIdentifier?: string;\n\t\t/** Labelled filter groups; see {@link StreamsEventsListParams.filters}. */\n\t\tfilters?: StreamsFilterMap;\n\t\t/**\n\t\t * Called for each pushed event, in order. The resume cursor advances only\n\t\t * after this resolves, so a handler that throws sees the same event again\n\t\t * on reconnect (at-least-once). Key durable writes by `cursor`.\n\t\t */\n\t\tonEvent: (event: StreamsEvent) => void | Promise<void>;\n\t};\n\n/** `chain: \"bitcoin\"` (plan 059/061) — Runes events pushed live, on their own\n * cursor space. `contractId`/`sender`/`recipient`/`assetIdentifier`/`filters`\n * don't exist on this branch — they're Stacks-only. */\nexport type StreamsEventsSubscribeBitcoinParams =\n\tStreamsEventsSubscribeCommon & {\n\t\tchain: \"bitcoin\";\n\t\ttypes?: readonly RuneEventType[];\n\t\tnotTypes?: readonly RuneEventType[];\n\t\t/** A RuneRef: an id (`840000:3`) or a name (`DOG•GO•TO•THE•MOON`). */\n\t\trune?: string;\n\t\t/** A mainnet address. */\n\t\taddress?: string;\n\t\tonEvent: (event: RuneStreamsEvent) => void | Promise<void>;\n\t};\n\nexport type StreamsEventsSubscribeParams =\n\t| StreamsEventsSubscribeStacksParams\n\t| StreamsEventsSubscribeBitcoinParams;\n\n/**\n * Handle for a live subscription: call it to unsubscribe. `done` resolves\n * after unsubscribe (or the signal aborting) and rejects with the error that\n * ended the loop when a retry could not fix it, so a worker can `await`\n * it instead of polling for silence.\n */\nexport type StreamsSubscription = {\n\t(): void;\n\tdone: Promise<void>;\n};\n\n/**\n * The checkpoint the SDK computes for a batch. Persist `cursor` inside the same\n * transaction as your projection writes, then resume from it via `fromCursor`.\n * It is the position to advance to: `next_cursor` normally, or the last\n * finalized event when `finalizedOnly` is set.\n */\n/**\n * What the loop knows at the end of a page, handed to `onBatch`.\n *\n * `cursor` is the position to commit. The rest answers \"how far along am I,\n * and am I still moving\" — the question every deployed consumer has to expose\n * for a health check.\n *\n * Progress is reported here rather than left to callers because only the loop\n * can get it right: `height` has to survive empty pages (normal at the tip)\n * and has to roll back to `fork_point_height - 1` after a reorg rewind.\n * Deriving it from `cursor` is wrong — `Cursor.atHeight` encodes the foot of a\n * block as `${height - 1}:<sentinel>`, so a rewound cursor parses to a\n * position that was never reached.\n */\nexport type ConsumerBatchContext<TTip = unknown, TReorg = unknown> = {\n\t/** Checkpoint to commit alongside your rows. */\n\tcursor: string | null;\n\t/** Highest canonical block a row was DELIVERED from. `null` before the\n\t * first row of a fresh consume. With a sparse filter this parks at the\n\t * last matching event — it measures event recency, not progress. */\n\theight: number | null;\n\t/** Highest canonical block the sweep has VERIFIED through: an empty page\n\t * is the server confirming nothing matches between the cursor and the\n\t * tip, so a caught-up tail scans to the tip even when `height` is far\n\t * below it. Rolls back with reorg rewinds. */\n\tscannedHeight: number | null;\n\t/** Chain tip as of this page's read. */\n\ttipHeight: number;\n\t/** `tipHeight - scannedHeight`, floored at 0 — the consumer's actual\n\t * backlog. `null` until a position is known. A caught-up consumer on a\n\t * quiet contract reads ~0 here while `tipHeight - height` grows — that\n\t * difference is event age, not lag. */\n\tblocksBehind: number | null;\n\t/**\n\t * The full tip for this page — `StreamsTip` or `IndexTip` depending on the\n\t * surface. Exposed here so a handler never needs the `envelope` parameter,\n\t * which is the only way to reach it today and is also how the worst\n\t * `finalizedOnly` mistake becomes reachable (`return envelope.next_cursor`\n\t * jumps the cursor past events that were filtered out and never delivered).\n\t */\n\ttip: TTip;\n\t/**\n\t * Reorgs reported alongside this page; empty when none. Rollback still\n\t * belongs in `onReorg` — this is for observability inside a batch.\n\t */\n\treorgs: readonly TReorg[];\n};\n\n/** @deprecated Use {@link ConsumerBatchContext} — the Index and Streams loops\n * share one shape now. Kept as an alias so existing annotations compile. */\nexport type StreamsBatchContext = ConsumerBatchContext;\n\n/**\n * The checkpoint for a reorg rollback. Persist `cursor` (the rewind position)\n * inside the same transaction as your rollback so the two commit atomically.\n */\n/** `cursor` is the rewind position the loop resumes from after `onReorg`:\n * the foot of the fork point, or `null` for a fork at genesis. Persist it\n * in the same transaction as the rollback. */\nexport type StreamsReorgContext = { cursor: string | null };\n\nexport type StreamsEventsConsumeParams<\n\tTTx = never,\n\tD extends boolean = false,\n\tF extends StreamsFilterMap = Record<never, never>,\n> = {\n\t/** `chain: \"stacks\"` (default, omit `chain` entirely) — the bitcoin branch\n\t * is {@link StreamsEventsConsumeBitcoinParams}, a separate overload with\n\t * no `filters`/`on`/`decoded` (Stacks-only concepts). */\n\tchain?: \"stacks\";\n\tfromCursor?: string | null;\n\t/**\n\t * Deliver events pre-decoded as the flat, `event_type`-discriminated rows\n\t * Index serves (`IndexEvent`), so Streams consumption reads identically\n\t * to Index consumption — no guard+decode pairs in your handler.\n\t */\n\tdecoded?: D;\n\t/**\n\t * Destination adapter that owns the checkpoint + rollback transaction\n\t * (e.g. `kyselySink` from `@secondlayer/sdk/sinks/kysely`). With a sink:\n\t * the loop resumes from the sink's committed cursor, `onBatch` receives\n\t * `ctx.tx` and must write ONLY through it (rows and cursor commit in one\n\t * transaction), reorg rollback is automatic, and `onBatch`'s return value\n\t * is ignored. Folds (balances) invert in the sink's `onRollback`, not in\n\t * `onReorg`.\n\t */\n\tsink?: ConsumerSink<TTx>;\n\t/** Fires once per page, before `onBatch` and before any early return. */\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tmode?: \"tail\" | \"bounded\";\n\t/**\n\t * Emit only finalized (immutable) events and never surface reorgs. The SDK\n\t * checkpoints at the last finalized event and re-reads the unfinalized tail\n\t * until it settles. Trades finality lag for zero reorg handling; `onReorg` is\n\t * ignored.\n\t */\n\tfinalizedOnly?: boolean;\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/**\n\t * Labelled filter groups. The groups OR together in ONE server-side scan,\n\t * so two unrelated concerns share one page, one cursor, and one checkpoint\n\t * instead of two consume loops. Pair with `on` to handle each label.\n\t */\n\tfilters?: F;\n\t/**\n\t * One handler per label in `filters`. Every label must be handled, so\n\t * adding a label is a compile error until its handler exists.\n\t *\n\t * A label's declared `types` narrows its handler's events, so `payload` is\n\t * typed without an `event_type` guard. Labels are dispatched in declaration\n\t * order: a label's own events stay in cursor order, but events of different\n\t * labels do not interleave within a page — add `onBatch` when you need\n\t * strict global order across labels.\n\t */\n\ton?: {\n\t\t[K in keyof F]: (\n\t\t\tevents: StreamsEventForFilter<F[K], D>[],\n\t\t\tctx: StreamsBatchContext & WithSinkTx<TTx>,\n\t\t) => void | Promise<void>;\n\t};\n\tbatchSize?: number;\n\t/**\n\t * Apply a page of canonical events. Persist `ctx.cursor` in the same\n\t * transaction as your writes. Returning a cursor overrides `ctx.cursor` as\n\t * the resume point (advanced manual control); returning nothing uses it.\n\t *\n\t * Optional only when `on` handles the page instead; a consume call with\n\t * neither throws.\n\t */\n\tonBatch?: (\n\t\tevents: D extends true ? IndexEvent[] : StreamsEvent[],\n\t\t/**\n\t\t * @deprecated Read `ctx.tip` / `ctx.reorgs` instead. The envelope is\n\t\t * also how the worst `finalizedOnly` mistake stays reachable —\n\t\t * returning `envelope.next_cursor` jumps the cursor past unfinalized\n\t\t * events that were filtered out and never delivered. Removed in the\n\t\t * next major.\n\t\t */\n\t\tenvelope: StreamsEventsEnvelope,\n\t\tctx: StreamsBatchContext & WithSinkTx<TTx>,\n\t) =>\n\t\t| void\n\t\t| string\n\t\t| null\n\t\t| undefined\n\t\t| Promise<void>\n\t\t| Promise<string | null | undefined>;\n\t/**\n\t * Roll your projection back to `reorg.fork_point_height`, persisting\n\t * `ctx.cursor` in the same transaction. Called once per *new* reorg at or\n\t * below the checkpoint (deduped in-memory, fork-ascending) before the SDK\n\t * rewinds and re-reads the now-canonical events. A reorg whose fork sits\n\t * above the checkpoint is not a rollback (nothing past it was written) and\n\t * is skipped. Omit it to ignore reorgs (events stay canonical, but stale\n\t * rows from an orphaned fork are left in place).\n\t *\n\t * With `onReorg` or a `sink` attached, every empty page also polls\n\t * `reorgs.list` (one extra request per idle poll) so a fork that lands\n\t * while the consumer idles at the tip is rolled back too.\n\t */\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\n\t/** Deepest rewind one reorg may make below the checkpoint before the loop\n\t * refuses with `ValidationError`. Default 1000 blocks. The fork point is\n\t * server supplied and drives a delete on every declared table, so raise\n\t * this only for a source you trust. */\n\tmaxRollbackDepth?: number;\n\t/** Page-fetch retries after the first failure (429/5xx/network only —\n\t * 4xx and handler throws always propagate). Default 3; `0` disables. */\n\tretryCount?: number;\n\t/** Base retry delay in ms; the n-th retry waits `retryDelay * n`. A server\n\t * `Retry-After` overrides it. Default 1000. */\n\tretryDelay?: number;\n\t/** Void observer, called before each retry sleep (metrics/logging). */\n\tonError?: (\n\t\terr: unknown,\n\t\tctx: { attempt: number; retriesLeft: number; delayMs: number },\n\t) => void;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n\t/**\n\t * Cuts the empty-poll backoff short: on an empty page, the loop races\n\t * `emptyBackoffMs` against this promise instead of sleeping the full\n\t * amount. Pass a function that resolves once when new data MIGHT be\n\t * available (e.g. a Postgres NOTIFY listener) — it is called fresh on\n\t * every empty page, never awaited more than once concurrently per page.\n\t * The backoff timer still runs underneath, so a wake source that never\n\t * resolves (or a `wake` this call omits) degrades to the same polling\n\t * behavior as before.\n\t */\n\twake?: () => Promise<void>;\n};\n\n/**\n * `chain: \"bitcoin\"` (plan 059/061) — the checkpointed sweep over Runes\n * events. A separate, simpler type from {@link StreamsEventsConsumeParams}\n * rather than a widened union member: `filters`/`on`/`decoded` are Stacks-only\n * concepts (labelled OR-groups and Index-shaped projection have no Runes\n * equivalent yet), so `onBatch` is the only way in and is required. Reorg\n * rewind still works the same way (bitcoin reorgs carry the same\n * `fork_point_height` + `new_canonical_tip` shape as Stacks ones).\n */\nexport type StreamsEventsConsumeBitcoinParams<TTx = never> = {\n\tchain: \"bitcoin\";\n\tfromCursor?: string | null;\n\tsink?: ConsumerSink<TTx>;\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tmode?: \"tail\" | \"bounded\";\n\tfinalizedOnly?: boolean;\n\ttypes?: readonly RuneEventType[];\n\tnotTypes?: readonly RuneEventType[];\n\t/** A RuneRef: an id (`840000:3`) or a name (`DOG•GO•TO•THE•MOON`). */\n\trune?: string;\n\t/** A mainnet address. */\n\taddress?: string;\n\tbatchSize?: number;\n\tonBatch: (\n\t\tevents: RuneStreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope<RuneStreamsEvent, StreamsBitcoinTip>,\n\t\tctx: StreamsBatchContext & WithSinkTx<TTx>,\n\t) =>\n\t\t| void\n\t\t| string\n\t\t| null\n\t\t| undefined\n\t\t| Promise<void>\n\t\t| Promise<string | null | undefined>;\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\n\tmaxRollbackDepth?: number;\n\tretryCount?: number;\n\tretryDelay?: number;\n\tonError?: (\n\t\terr: unknown,\n\t\tctx: { attempt: number; retriesLeft: number; delayMs: number },\n\t) => void;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n\twake?: () => Promise<void>;\n};\n\n/**\n * One yielded page from {@link StreamsClient.consume} — the\n * `GET /v1/streams/events` envelope verbatim, with `next_cursor` renamed to\n * `cursor` (the checkpoint to persist and resume from).\n */\nexport type StreamsBatch<TEvent = StreamsEvent, TTip = StreamsTip> = {\n\t/** Canonical events of this page, in cursor order. */\n\tevents: TEvent[];\n\t/** Checkpoint after this page — pass back as `consume({ cursor })` to resume. */\n\tcursor: string | null;\n\ttip: TTip;\n\t/** Chain reorgs reported alongside this page; empty when none. */\n\treorgs: StreamsReorg[];\n};\n\ntype StreamsConsumeCommon = {\n\t/** Resume strictly after this cursor; omit to start from the oldest seekable page. */\n\tcursor?: string | null;\n\t/** Events per page (the `limit` query param). Default 100. */\n\tbatchSize?: number;\n\t/** Poll interval while caught up at the tip, in ms. Default 2000. */\n\tintervalMs?: number;\n\t/** Abort to end the iteration. */\n\tsignal?: AbortSignal;\n};\n\n/** `chain: \"stacks\"` (default, omit `chain` entirely). */\nexport type StreamsConsumeStacksParams = StreamsConsumeCommon & {\n\tchain?: \"stacks\";\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled OR-groups — same semantics as `events.consume`; each returned\n\t * event echoes the labels it matched. */\n\tfilters?: StreamsFilterMap;\n};\n\n/** `chain: \"bitcoin\"` (plan 059/061) — Runes batches, own cursor space.\n * `contractId`/`sender`/`recipient`/`assetIdentifier`/`filters` don't exist\n * on this branch — they're Stacks-only. */\nexport type StreamsConsumeBitcoinParams = StreamsConsumeCommon & {\n\tchain: \"bitcoin\";\n\ttypes?: readonly RuneEventType[];\n\tnotTypes?: readonly RuneEventType[];\n\t/** A RuneRef: an id (`840000:3`) or a name (`DOG•GO•TO•THE•MOON`). */\n\trune?: string;\n\t/** A mainnet address. */\n\taddress?: string;\n};\n\nexport type StreamsConsumeParams =\n\t| StreamsConsumeStacksParams\n\t| StreamsConsumeBitcoinParams;\n\nexport type StreamsEventsConsumeResult = {\n\tcursor: string | null;\n\tpages: number;\n\temptyPolls: number;\n};\n\nexport type StreamsEventsReplayParams = {\n\t/** Start point: `\"genesis\"` (default) or a `<block>:<index>` cursor. */\n\tfrom?: \"genesis\" | string;\n\t/**\n\t * Called once per finalized dump file, in block order, before live tailing.\n\t * Process the parquet with your own tooling (e.g. DuckDB) — the SDK does not\n\t * decode parquet. Use `client.dumps.download(file)` to fetch + verify bytes.\n\t *\n\t * Delivery is file-granular and at-least-once: a file whose range straddles\n\t * `from` is handed over whole. `ctx.from` is that cursor (`null` from\n\t * genesis); skip rows at or below it, or key rows by `cursor` so a re-run\n\t * is an idempotent no-op. Files ending at or below `from` are not handed\n\t * over at all.\n\t */\n\tonDumpFile: (\n\t\tfile: StreamsDumpFile,\n\t\tctx: { from: string | null },\n\t) => Promise<void> | void;\n\t/** Called per live page after the dump phase, like `consume`. */\n\tonBatch: (\n\t\tevents: StreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope,\n\t) => Promise<string | null | undefined> | string | null | undefined;\n\t/**\n\t * Called when the live-tail phase (after the dump backfill) crosses a reorg,\n\t * before the cursor rewinds and re-reads the now-canonical events — same\n\t * contract as `consume`. The dump-backfill phase is finalized and never\n\t * reorgs; omit this to leave stale rows from an orphaned fork in place.\n\t */\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: StreamsReorgContext,\n\t) => Promise<void> | void;\n\tmode?: \"tail\" | \"bounded\";\n\tbatchSize?: number;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tsignal?: AbortSignal;\n\t/** Narrow the LIVE TAIL after the dump phase. The dump files themselves are\n\t * always all-type (block-partitioned parquet) — filter those in your own\n\t * tooling while processing each file. */\n\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\t/** Labelled OR-groups for the live tail, like `consume`. */\n\tfilters?: StreamsFilterMap;\n};\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\n/** One bulk parquet file in the dumps manifest. `path` is the object key under\n * the dumps base URL. */\nexport type StreamsDumpFile = {\n\tpath: string;\n\tfrom_block: number;\n\tto_block: number;\n\tmin_cursor: string | null;\n\tmax_cursor: string | null;\n\trow_count: number;\n\tbyte_size: number;\n\tsha256: string;\n\tschema_version: number;\n\tcreated_at: string;\n};\n\nexport type StreamsDumpsManifest = {\n\tdataset: string;\n\tnetwork: string;\n\tversion: string;\n\tschema_version: number;\n\tgenerated_at: string;\n\tproducer_version: string;\n\tfinality_lag_blocks: number;\n\t/** Cursor at the end of the finalized bulk coverage — hand to live tailing. */\n\tlatest_finalized_cursor: string | null;\n\tcoverage: { from_block: number; to_block: number };\n\tfiles: StreamsDumpFile[];\n\t/** ed25519 signature over the manifest's canonical bytes. Absent on legacy\n\t * unsigned manifests. Verified by `list()` when `verifyDumpsManifest` is on. */\n\tsignature?: string;\n\t/** Short id of the signing public key. */\n\tkey_id?: string;\n};\n\nexport type StreamsDumps = {\n\t/** Fetch and parse the latest dumps manifest. */\n\tlist(): Promise<StreamsDumpsManifest>;\n\t/** Absolute URL for a manifest file. */\n\tfileUrl(file: StreamsDumpFile): string;\n\t/** Download a parquet file and verify its sha256 against the manifest. */\n\tdownload(file: StreamsDumpFile): Promise<Uint8Array>;\n};\n\nexport type StreamsClient = {\n\t/**\n\t * Follow Streams as an async iterator of page batches.\n\t *\n\t * Yields one {@link StreamsBatch} per `GET /v1/streams/events` page — the\n\t * existing envelope (`events`, `next_cursor` → `cursor`, `tip`, `reorgs`)\n\t * with zero extra API calls. Batches are chosen over per-block groupings\n\t * because the envelope is page-keyed, so every yield is exactly one fetch.\n\t * Empty pages are skipped; at the tip the iterator re-polls every\n\t * `intervalMs` (default 2000) until aborted via `signal`.\n\t *\n\t * Reorgs are surfaced on the batch (`batch.reorgs`) but the cursor is not\n\t * rewound automatically — use `events.consume` with `onReorg` for managed\n\t * rollback semantics.\n\t */\n\t/** `chain: \"bitcoin\"` — batches carry Runes rows only, on the bitcoin tip\n\t * shape (plan 059/061). */\n\tconsume(\n\t\tparams: StreamsConsumeBitcoinParams,\n\t): AsyncIterableIterator<StreamsBatch<RuneStreamsEvent, StreamsBitcoinTip>>;\n\t/** Narrowing overload: a literal `types` array narrows every batch's\n\t * event union to exactly those members. */\n\tconsume<const T extends readonly StreamsEventType[]>(\n\t\tparams: StreamsConsumeStacksParams & { types: T },\n\t): AsyncIterableIterator<StreamsBatch<StreamsEventOfTypes<T>>>;\n\tconsume(params?: StreamsConsumeParams): AsyncIterableIterator<StreamsBatch>;\n\tevents: {\n\t\t/** `clock: \"vm\"` pages carry vm rows only (a parallel vocabulary,\n\t\t * `event_index` = `ordinal`). Never `StreamsEvent`. Stacks-only —\n\t\t * `chain: \"bitcoin\"` has no `clock`. */\n\t\tlist(\n\t\t\tparams: StreamsEventsStacksListParams & { clock: \"vm\" },\n\t\t): Promise<StreamsEventsEnvelope<VmStreamsEvent>>;\n\t\t/** Narrowing overload, matching `consume`. Classic clock only —\n\t\t * `clock: \"vm\"` is overload 1, and a general `StreamsEventsListParams`\n\t\t * variable (clock unresolved) is the wire-union fallback. */\n\t\tlist<const T extends readonly StreamsEventType[]>(\n\t\t\tparams: Omit<\n\t\t\t\tStreamsEventsStacksListParams,\n\t\t\t\t\"clock\" | \"types\" | \"notTypes\"\n\t\t\t> & {\n\t\t\t\ttypes: T;\n\t\t\t\tnotTypes?: readonly StreamsEventType[];\n\t\t\t\tclock?: \"classic\";\n\t\t\t},\n\t\t): Promise<StreamsEventsEnvelope<StreamsEventOfTypes<T>>>;\n\t\tlist(\n\t\t\tparams?: Omit<\n\t\t\t\tStreamsEventsStacksListParams,\n\t\t\t\t\"clock\" | \"types\" | \"notTypes\"\n\t\t\t> & {\n\t\t\t\ttypes?: readonly StreamsEventType[];\n\t\t\t\tnotTypes?: readonly StreamsEventType[];\n\t\t\t\tclock?: \"classic\";\n\t\t\t},\n\t\t): Promise<StreamsEventsEnvelope>;\n\t\t/** `chain: \"bitcoin\"` pages carry Runes rows only, on the bitcoin tip\n\t\t * shape (plan 059). */\n\t\tlist(\n\t\t\tparams: StreamsEventsBitcoinListParams,\n\t\t): Promise<StreamsEventsEnvelope<RuneStreamsEvent, StreamsBitcoinTip>>;\n\t\t/** Unresolved `chain`/`clock` on a general params variable: the wire union. */\n\t\tlist(\n\t\t\tparams: StreamsEventsListParams,\n\t\t): Promise<StreamsEventsEnvelope<StreamsWireEvent>>;\n\t\t/** `chain: \"bitcoin\"` — Runes events for one transaction. */\n\t\tbyTxId(\n\t\t\ttxId: string,\n\t\t\topts: { chain: \"bitcoin\" },\n\t\t): Promise<StreamsEventsListEnvelope<RuneStreamsEvent, StreamsBitcoinTip>>;\n\t\tbyTxId(txId: string): Promise<StreamsEventsListEnvelope>;\n\t\t/**\n\t\t * Pull pages from Streams and call `onBatch` after each page.\n\t\t *\n\t\t * Use `consume` for indexers and ETL jobs that own checkpointing. Return\n\t\t * the checkpoint cursor from `onBatch`. Default `mode: \"tail\"` keeps\n\t\t * polling when caught up; `mode: \"bounded\"` exits on the first empty page.\n\t\t * The consumer also exits when `maxPages`, `maxEmptyPolls`, or `signal`\n\t\t * stops it.\n\t\t */\n\t\t/** `chain: \"bitcoin\"` — the checkpointed sweep over Runes events; see\n\t\t * {@link StreamsEventsConsumeBitcoinParams}. */\n\t\tconsume<TTx = never>(\n\t\t\tparams: StreamsEventsConsumeBitcoinParams<TTx> & {\n\t\t\t\tsink?: ConsumerSink<TTx>;\n\t\t\t},\n\t\t): Promise<StreamsEventsConsumeResult>;\n\t\tconsume<\n\t\t\tconst F extends StreamsFilterMap = Record<never, never>,\n\t\t\tTTx = never,\n\t\t\tD extends boolean = false,\n\t\t>(\n\t\t\t// The redundant `sink` member gives TS a DIRECT inference site for\n\t\t\t// TTx — inference does not reliably traverse the params alias.\n\t\t\tparams: StreamsEventsConsumeParams<TTx, D, F> & {\n\t\t\t\tsink?: ConsumerSink<TTx>;\n\t\t\t},\n\t\t): Promise<StreamsEventsConsumeResult>;\n\t\t/**\n\t\t * Backfill from bulk dumps, then continue live from the dump→live seam in\n\t\t * one call. Iterates finalized dump files (via `onDumpFile`) in block\n\t\t * order, then tails live from the manifest's `latest_finalized_cursor`\n\t\t * (exclusive input → no gap or duplicate at the seam). Requires\n\t\t * `dumpsBaseUrl`.\n\t\t */\n\t\treplay(\n\t\t\tparams: StreamsEventsReplayParams,\n\t\t): Promise<StreamsEventsConsumeResult>;\n\t\t/**\n\t\t * Follow Streams as an async iterator.\n\t\t *\n\t\t * Use `stream` for live processors and watch-style apps. It tails\n\t\t * indefinitely by default and stops when its `AbortSignal`, `maxPages`, or\n\t\t * `maxEmptyPolls` stops it.\n\t\t */\n\t\t/** `chain: \"bitcoin\"` — Runes events only (plan 059/061). */\n\t\tstream(\n\t\t\tparams: StreamsEventsStreamBitcoinParams,\n\t\t): AsyncIterable<RuneStreamsEvent>;\n\t\t/** Narrowing overload, matching `consume`. */\n\t\tstream<const T extends readonly StreamsEventType[]>(\n\t\t\tparams: StreamsEventsStreamStacksParams & { types: T },\n\t\t): AsyncIterable<StreamsEventOfTypes<T>>;\n\t\tstream(params?: StreamsEventsStreamParams): AsyncIterable<StreamsEvent>;\n\t\t/**\n\t\t * Subscribe to the real-time SSE push surface. Calls `onEvent` for each new\n\t\t * canonical event as the server pushes it (chain cadence, not poll-bounded),\n\t\t * and verifies each frame's inline ed25519 signature when the client was\n\t\t * created with `verify`. Returns an unsubscribe function whose `done`\n\t\t * settles when the loop ends. Not reorg-aware: an event delivered then\n\t\t * orphaned is never retracted. Durable writers use `consume()`.\n\t\t */\n\t\t/** `chain: \"bitcoin\"` — `onEvent` receives Runes rows (plan 059/061). */\n\t\tsubscribe(params: StreamsEventsSubscribeBitcoinParams): StreamsSubscription;\n\t\tsubscribe(params: StreamsEventsSubscribeStacksParams): StreamsSubscription;\n\t};\n\tblocks: {\n\t\tevents(\n\t\t\theightOrHash: number | string,\n\t\t\topts: { chain: \"bitcoin\" },\n\t\t): Promise<StreamsEventsListEnvelope<RuneStreamsEvent, StreamsBitcoinTip>>;\n\t\tevents(heightOrHash: number | string): Promise<StreamsEventsListEnvelope>;\n\t};\n\treorgs: {\n\t\tlist(\n\t\t\tparams: StreamsReorgsListParams & { chain: \"bitcoin\" },\n\t\t): Promise<StreamsReorgsListEnvelope>;\n\t\tlist(params: StreamsReorgsListParams): Promise<StreamsReorgsListEnvelope>;\n\t};\n\t/** Bulk parquet dumps. Requires `dumpsBaseUrl` on the client. */\n\tdumps: StreamsDumps;\n\tcanonical(\n\t\theight: number,\n\t\topts: { chain: \"bitcoin\" },\n\t): Promise<StreamsBitcoinCanonicalBlock>;\n\tcanonical(height: number): Promise<StreamsCanonicalBlock>;\n\ttip(opts: { chain: \"bitcoin\" }): Promise<StreamsBitcoinTip>;\n\ttip(): Promise<StreamsTip>;\n};\n"
16
16
  ],
17
- "mappings": ";AAAA,oBAAS;;;ACAT,IAAM,YAAY;AAAA;AA6BX,MAAM,yBAAyB,MAAM;AAAA,EAClC,OAAO;AAAA,EAEhB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,WAAW,CAAC,cAAsB,UAAmC,CAAC,GAAG;AAAA,IACxE,MAAM,eAAe;AAAA,MACpB,GAAI,QAAQ,gBAAgB,CAAC;AAAA,MAC7B,GAAI,QAAQ,UAAU,CAAC,QAAQ,OAAO,IAAI,CAAC;AAAA,MAC3C,GAAI,QAAQ,UAAU,CAAC,SAAS,QAAQ,SAAS,IAAI,CAAC;AAAA,IACvD;AAAA,IACA,MAAM,UAAU;AAAA,MACf;AAAA,MACA,aAAa,SAAS,IAAI;AAAA,EAAK,aAAa,KAAK;AAAA,CAAI,MAAM;AAAA,IAC5D,EAAE,KAAK,EAAE;AAAA,IACT,MAAM,SAAS,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,SAAS;AAAA,IACnE,KAAK,eAAe;AAAA,IACpB,KAAK,OAAO,QAAQ;AAAA,I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AY,SAAS,uBAAuB;AAAA,QACnE,OAAO,qBAAqB;AAAA,UAC3B,YAAY;AAAA,UACZ,MAAM,OAAO,QAAQ;AAAA,UACrB,WAAW,OAAO,aAAa;AAAA,UAG/B,OAAO,OAAO;AAAA,UACd,UAAU,OAAO;AAAA,UACjB,SAAS,OAAO;AAAA,UAChB;AAAA,UACA,SAAS,OAAO;AAAA,UAChB,SAAS,OAAO;AAAA,UAChB,gBAAgB,OAAO;AAAA,UACvB,UAAU,OAAO;AAAA,UACjB,eAAe,OAAO;AAAA,UACtB,QAAQ,OAAO;AAAA,QAChB,CAAC;AAAA;AAAA,IAEH;AAAA,IACA,QAAQ;AAAA,MACP,QAAS,CACR,cACA,SAEA,QACC,sBAAsB,mBAAmB,OAAO,YAAY,CAAC,WAAW,WACvE,EAAE,OAAO,MAAM,UAAU,YAAY,YAAY,UAAU,CAC5D,GACD;AAAA,IACF;AAAA,IACA,QAAQ,EAAE,MAAM,WAA8C;AAAA,IAC9D;AAAA,IACA,WAAY,CAAC,QAAgB,SAC5B,QACC,yBAAyB,SAAS,WAAW;AAAA,MAC5C,OAAO,MAAM,UAAU,YAAY,YAAY;AAAA,IAChD,CAAC,GACF;AAAA,IACD,KAAM,CAAC,SACN,QACC,kBAAkB,WAAW;AAAA,MAC5B,OAAO,MAAM,UAAU,YAAY,YAAY;AAAA,IAChD,CAAC,GACF;AAAA,EACF;AAAA;;;ASxpBD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACjBA;AAAA;AAAA;AAAA;",
18
+ "debugId": "F2E7E752B64FBB0D64756E2164756E21",
19
19
  "names": []
20
20
  }
@@ -248,7 +248,9 @@ function parseErrorEnvelope(text) {
248
248
  let code;
249
249
  if (json && typeof json === "object") {
250
250
  const err = json.error ?? json.message;
251
- if (typeof err === "string" && err.length > 0)
251
+ if (typeof err === "string" && typeof json.message === "string" && json.message.length > 0) {
252
+ message = json.message;
253
+ } else if (typeof err === "string" && err.length > 0)
252
254
  message = err;
253
255
  else if (err && typeof err === "object")
254
256
  message = JSON.stringify(err);
@@ -2797,5 +2799,5 @@ export {
2797
2799
  getSubgraph
2798
2800
  };
2799
2801
 
2800
- //# debugId=4FAC4F02875FC38A64756E2164756E21
2802
+ //# debugId=553F4BC532FBAFDA64756E2164756E21
2801
2803
  //# sourceMappingURL=index.js.map