@secondlayer/sdk 6.54.0 → 6.54.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.
- package/README.md +13 -24
- package/dist/index.d.ts +5 -4
- package/dist/index.js +2 -2
- package/dist/index.js.map +4 -4
- package/dist/streams/index.js.map +1 -1
- package/dist/subgraphs/index.d.ts +1 -1
- package/dist/subgraphs/index.js.map +1 -1
- package/dist/x402.d.ts +4 -3
- package/dist/x402.js +298 -2
- package/dist/x402.js.map +6 -4
- package/package.json +1 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import { ed25519 } from \"@secondlayer/shared\";\nimport { buildQuery, 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 { decode } from \"./decode.ts\";\nimport { createStreamsDumps } from \"./dumps.ts\";\nimport {\n\tAuthError,\n\tRateLimitError,\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tValidationError,\n} from \"./errors.ts\";\nimport { subscribeStreamsEvents } from \"./subscribe.ts\";\nimport type {\n\tFetchLike,\n\tStreamsCanonicalBlock,\n\tStreamsClient,\n\tStreamsConsumeParams,\n\tStreamsEvent,\n\tStreamsEventType,\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\tStreamsTip,\n\tStreamsUsage,\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 parts = cursor.split(\":\");\n\tconst [block, index] = parts.map(Number);\n\tif (\n\t\tparts.length !== 2 ||\n\t\t!Number.isInteger(block) ||\n\t\t!Number.isInteger(index)\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`Invalid stream cursor \"${cursor}\"; expected \"<block>:<index>\" (e.g. \"951475:3\").`,\n\t\t\t400,\n\t\t);\n\t}\n\treturn [block, index];\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\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\tfilters?: StreamsFilterMap;\n}) {\n\treturn {\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\tfilters: params.filters,\n\t};\n}\n\nexport type CreateStreamsClientOptions = {\n\tapiKey: string;\n\tbaseUrl?: string;\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\nasync function responseBody(response: Response): Promise<unknown> {\n\tconst text = await response.text();\n\tif (text.length === 0) return undefined;\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn text;\n\t}\n}\n\nfunction errorMessage(body: unknown, fallback: string): string {\n\tif (body && typeof body === \"object\") {\n\t\tconst record = body as Record<string, unknown>;\n\t\tconst message = record.error ?? record.message;\n\t\tif (typeof message === \"string\" && message.length > 0) return message;\n\t}\n\tif (typeof body === \"string\" && body.length > 0) return body;\n\treturn fallback;\n}\n\nasync function mapStreamsError(response: Response): Promise<never> {\n\tconst body = await responseBody(response);\n\n\tif (response.status === 401) {\n\t\tthrow new AuthError(errorMessage(body, \"API key invalid or expired.\"));\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\terrorMessage(body, \"Rate limited. Try again later.\"),\n\t\t\tretryAfter,\n\t\t);\n\t}\n\n\tif (response.status >= 500) {\n\t\tthrow new StreamsServerError(\n\t\t\terrorMessage(body, `Streams server returned ${response.status}.`),\n\t\t\tresponse.status,\n\t\t\tbody,\n\t\t);\n\t}\n\n\tthrow new ValidationError(\n\t\terrorMessage(body, `Streams request returned ${response.status}.`),\n\t\tresponse.status,\n\t\tbody,\n\t);\n}\n\nexport function createStreamsClient(\n\toptions: CreateStreamsClientOptions,\n): StreamsClient {\n\tconst baseUrl = normalizeBaseUrl(resolveBaseUrl(options.baseUrl));\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\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\tlet keyPromise: Promise<VerificationKey> | null = null;\n\tfunction loadKey(): Promise<VerificationKey> {\n\t\tif (keyPromise) return keyPromise;\n\t\tkeyPromise = (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\tconst res = await fetchImpl(`${baseUrl}/public/streams/signing-key`);\n\t\t\tif (!res.ok) {\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\treturn keyPromise;\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: { Authorization: `Bearer ${options.apiKey}` },\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 responseKeyId = response.headers.get(\"X-Signature-KeyId\");\n\t\t\t\tlet key = await loadKey();\n\t\t\t\t// The server rotated to a key we haven't seen.\n\t\t\t\tif (responseKeyId && responseKeyId !== key.keyId) {\n\t\t\t\t\tif (typeof verify === \"object\") {\n\t\t\t\t\t\t// Pinned key: a different id is never the pinned key — fail closed.\n\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t`Response signed with key '${responseKeyId}', expected pinned key '${key.keyId}'.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// Fetched key: refresh once. A still-mismatched id (no re-loop)\n\t\t\t\t\t// means the endpoint doesn't serve the signing key — fail closed.\n\t\t\t\t\tkeyPromise = null;\n\t\t\t\t\tkey = await loadKey();\n\t\t\t\t\tif (responseKeyId !== key.keyId) {\n\t\t\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t\t\t`Response signed with key '${responseKeyId}' not served by the signing-key endpoint.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\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 is a strict subset of StreamsEventsListParams, so\n\t// this is checked by the compiler rather than by a hand-copied destructure.\n\tconst fetchEvents: StreamsEventsFetcher = listEvents;\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\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\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\tonBatch,\n\t\t\tonReorg: params.onReorg,\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});\n\t}\n\n\treturn {\n\t\tconsume(params: StreamsConsumeParams = {}) {\n\t\t\treturn iterateStreamsBatches({\n\t\t\t\tfromCursor: params.cursor,\n\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\tintervalMs: params.intervalMs ?? 2000,\n\t\t\t\t...streamsFilters(params),\n\t\t\t\tsignal: params.signal,\n\t\t\t\tfetchEvents,\n\t\t\t});\n\t\t},\n\t\tevents: {\n\t\t\tlist: listEvents,\n\t\t\tbyTxId(txId: string) {\n\t\t\t\treturn request<StreamsEventsListEnvelope>(\n\t\t\t\t\t`/v1/streams/events/${encodeURIComponent(txId)}`,\n\t\t\t\t);\n\t\t\t},\n\t\t\tconsume: consumeEvents,\n\t\t\tstream(params: StreamsEventsStreamParams = {}) {\n\t\t\t\treturn streamStreamsEvents({\n\t\t\t\t\tfromCursor: params.fromCursor,\n\t\t\t\t\t// Includes the labelled OR-groups: dropping them here silently\n\t\t\t\t\t// widened the stream to the FULL firehose (billed per row).\n\t\t\t\t\t...streamsFilters(params),\n\t\t\t\t\tbatchSize: params.batchSize ?? 100,\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\tfetchEvents,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsubscribe(params: StreamsEventsSubscribeParams) {\n\t\t\t\treturn subscribeStreamsEvents({\n\t\t\t\t\tbaseUrl,\n\t\t\t\t\tapiKey: options.apiKey,\n\t\t\t\t\tfetchImpl,\n\t\t\t\t\tverify: verifyMode,\n\t\t\t\t\tloadKey,\n\t\t\t\t\tparams,\n\t\t\t\t});\n\t\t\t},\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.\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.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);\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(heightOrHash: number | string) {\n\t\t\t\treturn request<StreamsEventsListEnvelope>(\n\t\t\t\t\t`/v1/streams/blocks/${encodeURIComponent(String(heightOrHash))}/events`,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\treorgs: {\n\t\t\tlist(params: StreamsReorgsListParams) {\n\t\t\t\treturn request<StreamsReorgsListEnvelope>(\n\t\t\t\t\t`/v1/streams/reorgs${buildQuery({\n\t\t\t\t\t\tsince: params.since,\n\t\t\t\t\t\tlimit: params.limit,\n\t\t\t\t\t})}`,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tdumps,\n\t\tcanonical(height: number) {\n\t\t\treturn request<StreamsCanonicalBlock>(`/v1/streams/canonical/${height}`);\n\t\t},\n\t\ttip() {\n\t\t\treturn request<StreamsTip>(\"/v1/streams/tip\");\n\t\t},\n\t\tusage() {\n\t\t\treturn request<StreamsUsage>(\"/v1/streams/usage\");\n\t\t},\n\t};\n}\n",
|
|
6
6
|
"import type { ByoBreakingChangeDetails } from \"@secondlayer/shared/errors\";\n\nexport type { ByoBreakingChangeDetails };\n\nconst 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`, `BYO_BREAKING_CHANGE`). */\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: `BaseError.details` is a\n * `string`, while {@link ByoBreakingChangeError.details} is the documented\n * structured migration plan — and cross-package `instanceof` is unreliable\n * under per-package bundling anyway (match on `code`/`name` across 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\" || code === \"PLAN_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.get(\"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 platform clients and Streams. */\nexport class AuthError extends ApiError {\n\toverride readonly status = 401 as const;\n\n\tconstructor(message = \"API key invalid or expired.\") {\n\t\tsuper(401, message);\n\t\tthis.name = \"AuthError\";\n\t}\n}\n\n/** Thrown on a 429 — by both the platform 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) {\n\t\tsuper(429, message, undefined, undefined, {\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. */\nexport class ValidationError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown) {\n\t\tsuper(status, message, body, undefined, { retryable: false });\n\t\tthis.name = \"ValidationError\";\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\n/**\n * Thrown on optimistic-concurrency conflict when a deploy supplies an\n * `expectedVersion` that no longer matches the server's stored version.\n */\nexport class VersionConflictError extends ApiError {\n\tconstructor(\n\t\tpublic currentVersion: string,\n\t\tpublic expectedVersion: string,\n\t\tmessage = `Version conflict: expected ${expectedVersion}, current ${currentVersion}`,\n\t) {\n\t\tsuper(409, message, { currentVersion, expectedVersion });\n\t\tthis.name = \"VersionConflictError\";\n\t}\n}\n\n/**\n * Thrown when a BYO subgraph deploy is refused for a breaking schema change.\n * The deploy did NOT run — `details.plan` carries the DROP + rebuild DDL to run\n * manually on your own database, plus the breaking `reasons` and the `diff`.\n * The same DDL is surfaced on `metaMessages`, so a bare `console.error(err)`\n * already shows the operator what to run.\n *\n * @example\n * ```ts\n * try {\n * await client.subgraphs.deploy(bundle);\n * } catch (err) {\n * if (err instanceof ByoBreakingChangeError) {\n * console.log(err.details.plan.dropStatement);\n * console.log(err.details.plan.statements.join(\";\\n\"));\n * }\n * }\n * ```\n */\nexport class ByoBreakingChangeError extends ApiError {\n\treadonly details: ByoBreakingChangeDetails;\n\tconstructor(message: string, details: ByoBreakingChangeDetails) {\n\t\tsuper(422, message, details, \"BYO_BREAKING_CHANGE\", {\n\t\t\tmetaMessages: [\n\t\t\t\t\"Review and run manually on your database:\",\n\t\t\t\tdetails.plan.dropStatement,\n\t\t\t\t...details.plan.statements,\n\t\t\t],\n\t\t});\n\t\tthis.name = \"ByoBreakingChangeError\";\n\t\tthis.details = details;\n\t}\n}\n\n/** Narrow an unknown error body's `details` to {@link ByoBreakingChangeDetails}. */\nexport function isByoBreakingDetails(\n\tx: unknown,\n): x is ByoBreakingChangeDetails {\n\tif (!x || typeof x !== \"object\") return false;\n\tconst d = x as Record<string, unknown>;\n\tconst plan = d.plan as Record<string, unknown> | undefined;\n\treturn (\n\t\tArray.isArray(d.reasons) &&\n\t\t!!plan &&\n\t\ttypeof plan === \"object\" &&\n\t\ttypeof plan.dropStatement === \"string\"\n\t);\n}\n",
|
|
7
|
-
"import {\n\tApiError,\n\tAuthError,\n\ttype ByoBreakingChangeDetails,\n\tByoBreakingChangeError,\n\tRateLimitError,\n\tisByoBreakingDetails,\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
|
|
7
|
+
"import {\n\tApiError,\n\tAuthError,\n\ttype ByoBreakingChangeDetails,\n\tByoBreakingChangeError,\n\tRateLimitError,\n\tisByoBreakingDetails,\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 requests. */\n\tapiKey?: 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/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or `SL_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst fromEnv = process.env?.SL_API_URL || process.env?.SECONDLAYER_API_URL;\n\t\tif (fromEnv) return fromEnv.replace(/\\/+$/, \"\");\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Resolve the credential a client should use. An explicit `apiKey` option\n * always wins — including an explicit `\"\"`, which is how you opt a client\n * back into keyless reads on a machine that has a key exported. Otherwise\n * fall back to `SL_API_KEY`, the single credential var shared with the CLI\n * and MCP server, so `new Index()` picks up an already-exported key instead\n * of silently running keyless and 402-ing on the first deep-history read.\n * Guarded for browsers and edge runtimes, where `process` is undefined. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\treturn process.env?.SL_API_KEY || undefined;\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\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\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\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}\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): Promise<T> {\n\t\tconst response = await this.fetchResponse(method, path, body);\n\t\tif (response.status === 204) {\n\t\t\treturn undefined as T;\n\t\t}\n\t\treturn response.json() as Promise<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): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body);\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): Promise<string> {\n\t\tconst response = await this.fetchResponse(method, path, body);\n\t\treturn response.text();\n\t}\n\n\tprivate async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<Response> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst headers = BaseClient.authHeaders(this.apiKey);\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\tresponse = await this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t});\n\t\t} catch (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\tif (!response.ok) {\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError();\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 retryAfter = response.headers.get(\"Retry-After\");\n\t\t\t\tconst msg = 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(msg, retryAfter ?? undefined);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst errorBody = await response.text();\n\t\t\tlet message = `HTTP ${response.status}`;\n\t\t\tlet parsedBody: unknown = errorBody;\n\t\t\tlet code: string | undefined;\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(errorBody);\n\t\t\t\tparsedBody = json;\n\t\t\t\tconst err = json.error ?? json.message;\n\t\t\t\tif (typeof err === \"string\") {\n\t\t\t\t\tmessage = err;\n\t\t\t\t} else if (err && typeof err === \"object\") {\n\t\t\t\t\tmessage = JSON.stringify(err);\n\t\t\t\t}\n\t\t\t\tif (typeof json.code === \"string\") {\n\t\t\t\t\tcode = json.code;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tif (errorBody) message = errorBody;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tresponse.status === 422 &&\n\t\t\t\tcode === \"BYO_BREAKING_CHANGE\" &&\n\t\t\t\tparsedBody &&\n\t\t\t\ttypeof parsedBody === \"object\" &&\n\t\t\t\tisByoBreakingDetails((parsedBody as { details?: unknown }).details)\n\t\t\t) {\n\t\t\t\tthrow new ByoBreakingChangeError(\n\t\t\t\t\tmessage,\n\t\t\t\t\t(parsedBody as { details: ByoBreakingChangeDetails }).details,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new ApiError(response.status, message, parsedBody, code);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
|
|
8
8
|
"// 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 { ApiError, SecondLayerError } from \"../errors.ts\";\n\nexport { AuthError, RateLimitError, ValidationError } from \"../errors.ts\";\n\n/** Thrown on a 5xx from the Streams API. `retryable`. */\nexport class StreamsServerError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown) {\n\t\tsuper(status, message, body, undefined, { 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",
|
|
9
9
|
"import { ValidationError } from \"./errors.ts\";\n\n/**\n * Largest value the `event_index` / `tx_index` cursor component can take —\n * Postgres int4 max. Used as the foot-of-block sentinel in {@link Cursor.atHeight}\n * so a rewind cursor sorts just below `height:0`. Mirrors the same int4-max\n * sentinel the server uses for reorg height-range scans and empty-range advance.\n */\nconst REWIND_FOOT_INDEX_SENTINEL = 2_147_483_647;\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.\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 `${height-1}:${SENTINEL}` 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\tatHeight(height: number): string {\n\t\t// Genesis can't reorg; degenerate-guard so `height - 1` never goes negative\n\t\t// (the cursor parsers reject negative components).\n\t\tif (height <= 0) return \"0:0\";\n\t\treturn `${height - 1}:${REWIND_FOOT_INDEX_SENTINEL}`;\n\t},\n\n\t/** Parse a `<block>:<index>` cursor. Throws `ValidationError` if malformed. */\n\tparse(cursor: string): { blockHeight: number; eventIndex: number } {\n\t\tconst parts = cursor.split(\":\");\n\t\tconst blockHeight = Number(parts[0]);\n\t\tconst eventIndex = Number(parts[1]);\n\t\tif (\n\t\t\tparts.length !== 2 ||\n\t\t\t!Number.isInteger(blockHeight) ||\n\t\t\t!Number.isInteger(eventIndex)\n\t\t) {\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\treturn { blockHeight, eventIndex };\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\tStreamsEventType,\n\tStreamsEventsEnvelope,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorg,\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\ntype StreamsEventsFetchParams = {\n\tcursor?: string | null;\n\tlimit: number;\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, 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/** Retry-After above this is treated as \"give up now, resume later\". */\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 timeout = setTimeout(resolve, ms);\n\t\tif (!signal) return;\n\t\tsignal.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\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\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: string;\n\t/** Labelled filter groups, forwarded to the server verbatim. */\n\tfilters?: StreamsFilterMap;\n\tfetchEvents: StreamsEventsFetcher;\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 },\n\t) => Promise<void> | void;\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}): 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\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\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\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, then rewind to the lowest fork point\n\t\t// and re-read the now-canonical run. Finalized data never reorgs, so\n\t\t// `finalizedOnly` skips this entirely. A sink makes rollback\n\t\t// UNCONDITIONAL — omitting `onReorg` used to skip reorgs silently.\n\t\tif (!finalizedOnly && (opts.onReorg || opts.sink)) {\n\t\t\tconst fresh = envelope.reorgs\n\t\t\t\t.filter((reorg) => !handledReorgs.has(reorgKey(reorg)))\n\t\t\t\t.sort((a, b) => a.fork_point_height - b.fork_point_height);\n\t\t\tif (fresh.length > 0) {\n\t\t\t\tconst forkPoint = Math.min(\n\t\t\t\t\t...fresh.map((reorg) => reorg.fork_point_height),\n\t\t\t\t);\n\t\t\t\tconst rewind = Cursor.atHeight(forkPoint);\n\t\t\t\tfor (const reorg of fresh) {\n\t\t\t\t\tawait opts.sink?.rollback(reorg.fork_point_height, rewind);\n\t\t\t\t\tawait opts.onReorg?.(reorg, { cursor: rewind });\n\t\t\t\t\thandledReorgs.add(reorgKey(reorg));\n\t\t\t\t}\n\t\t\t\tcursor = rewind;\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 = forkPoint > 0 ? 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\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\tawait 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\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: 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\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\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\ttypes?: readonly StreamsEventType[];\n\tnotTypes?: readonly StreamsEventType[];\n\tcontractId?: StreamsFilterValue;\n\tsender?: StreamsFilterValue;\n\trecipient?: StreamsFilterValue;\n\tassetIdentifier?: 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\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\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",
|
|
@@ -4,7 +4,7 @@ import { SubgraphAgentSchema, SubgraphSpecOptions } from "@secondlayer/shared/su
|
|
|
4
4
|
import { InferSubgraphClient } from "@secondlayer/subgraphs";
|
|
5
5
|
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
6
6
|
interface SecondLayerOptions {
|
|
7
|
-
/** Base URL of the
|
|
7
|
+
/** Base URL of the instance API (trailing slashes are stripped). */
|
|
8
8
|
baseUrl: string;
|
|
9
9
|
/** Bearer token for authenticated requests. */
|
|
10
10
|
apiKey?: string;
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"sources": ["src/errors.ts", "src/base.ts", "src/subgraphs/serialize.ts", "src/subgraphs/client.ts", "src/api-keys/client.ts", "src/contracts/client.ts", "src/streams/errors.ts", "src/streams/cursor.ts", "src/streams/consumer.ts", "src/index-api/consumer.ts", "src/index-api/client.ts", "src/projects/client.ts", "src/streams/client.ts", "src/streams/_payload.ts", "src/streams/decode.ts", "src/streams/dumps.ts", "src/streams/subscribe.ts", "src/subscriptions/client.ts", "src/client.ts", "src/subgraphs/get-subgraph.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import type { ByoBreakingChangeDetails } from \"@secondlayer/shared/errors\";\n\nexport type { ByoBreakingChangeDetails };\n\nconst 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`, `BYO_BREAKING_CHANGE`). */\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: `BaseError.details` is a\n * `string`, while {@link ByoBreakingChangeError.details} is the documented\n * structured migration plan — and cross-package `instanceof` is unreliable\n * under per-package bundling anyway (match on `code`/`name` across 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\" || code === \"PLAN_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.get(\"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 platform clients and Streams. */\nexport class AuthError extends ApiError {\n\toverride readonly status = 401 as const;\n\n\tconstructor(message = \"API key invalid or expired.\") {\n\t\tsuper(401, message);\n\t\tthis.name = \"AuthError\";\n\t}\n}\n\n/** Thrown on a 429 — by both the platform 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) {\n\t\tsuper(429, message, undefined, undefined, {\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. */\nexport class ValidationError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown) {\n\t\tsuper(status, message, body, undefined, { retryable: false });\n\t\tthis.name = \"ValidationError\";\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\n/**\n * Thrown on optimistic-concurrency conflict when a deploy supplies an\n * `expectedVersion` that no longer matches the server's stored version.\n */\nexport class VersionConflictError extends ApiError {\n\tconstructor(\n\t\tpublic currentVersion: string,\n\t\tpublic expectedVersion: string,\n\t\tmessage = `Version conflict: expected ${expectedVersion}, current ${currentVersion}`,\n\t) {\n\t\tsuper(409, message, { currentVersion, expectedVersion });\n\t\tthis.name = \"VersionConflictError\";\n\t}\n}\n\n/**\n * Thrown when a BYO subgraph deploy is refused for a breaking schema change.\n * The deploy did NOT run — `details.plan` carries the DROP + rebuild DDL to run\n * manually on your own database, plus the breaking `reasons` and the `diff`.\n * The same DDL is surfaced on `metaMessages`, so a bare `console.error(err)`\n * already shows the operator what to run.\n *\n * @example\n * ```ts\n * try {\n * await client.subgraphs.deploy(bundle);\n * } catch (err) {\n * if (err instanceof ByoBreakingChangeError) {\n * console.log(err.details.plan.dropStatement);\n * console.log(err.details.plan.statements.join(\";\\n\"));\n * }\n * }\n * ```\n */\nexport class ByoBreakingChangeError extends ApiError {\n\treadonly details: ByoBreakingChangeDetails;\n\tconstructor(message: string, details: ByoBreakingChangeDetails) {\n\t\tsuper(422, message, details, \"BYO_BREAKING_CHANGE\", {\n\t\t\tmetaMessages: [\n\t\t\t\t\"Review and run manually on your database:\",\n\t\t\t\tdetails.plan.dropStatement,\n\t\t\t\t...details.plan.statements,\n\t\t\t],\n\t\t});\n\t\tthis.name = \"ByoBreakingChangeError\";\n\t\tthis.details = details;\n\t}\n}\n\n/** Narrow an unknown error body's `details` to {@link ByoBreakingChangeDetails}. */\nexport function isByoBreakingDetails(\n\tx: unknown,\n): x is ByoBreakingChangeDetails {\n\tif (!x || typeof x !== \"object\") return false;\n\tconst d = x as Record<string, unknown>;\n\tconst plan = d.plan as Record<string, unknown> | undefined;\n\treturn (\n\t\tArray.isArray(d.reasons) &&\n\t\t!!plan &&\n\t\ttypeof plan === \"object\" &&\n\t\ttypeof plan.dropStatement === \"string\"\n\t);\n}\n",
|
|
6
|
-
"import {\n\tApiError,\n\tAuthError,\n\ttype ByoBreakingChangeDetails,\n\tByoBreakingChangeError,\n\tRateLimitError,\n\tisByoBreakingDetails,\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
|
|
6
|
+
"import {\n\tApiError,\n\tAuthError,\n\ttype ByoBreakingChangeDetails,\n\tByoBreakingChangeError,\n\tRateLimitError,\n\tisByoBreakingDetails,\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 requests. */\n\tapiKey?: 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/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or `SL_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst fromEnv = process.env?.SL_API_URL || process.env?.SECONDLAYER_API_URL;\n\t\tif (fromEnv) return fromEnv.replace(/\\/+$/, \"\");\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Resolve the credential a client should use. An explicit `apiKey` option\n * always wins — including an explicit `\"\"`, which is how you opt a client\n * back into keyless reads on a machine that has a key exported. Otherwise\n * fall back to `SL_API_KEY`, the single credential var shared with the CLI\n * and MCP server, so `new Index()` picks up an already-exported key instead\n * of silently running keyless and 402-ing on the first deep-history read.\n * Guarded for browsers and edge runtimes, where `process` is undefined. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\treturn process.env?.SL_API_KEY || undefined;\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\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\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\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}\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): Promise<T> {\n\t\tconst response = await this.fetchResponse(method, path, body);\n\t\tif (response.status === 204) {\n\t\t\treturn undefined as T;\n\t\t}\n\t\treturn response.json() as Promise<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): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body);\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): Promise<string> {\n\t\tconst response = await this.fetchResponse(method, path, body);\n\t\treturn response.text();\n\t}\n\n\tprivate async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<Response> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst headers = BaseClient.authHeaders(this.apiKey);\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\tresponse = await this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t});\n\t\t} catch (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\tif (!response.ok) {\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError();\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 retryAfter = response.headers.get(\"Retry-After\");\n\t\t\t\tconst msg = 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(msg, retryAfter ?? undefined);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst errorBody = await response.text();\n\t\t\tlet message = `HTTP ${response.status}`;\n\t\t\tlet parsedBody: unknown = errorBody;\n\t\t\tlet code: string | undefined;\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(errorBody);\n\t\t\t\tparsedBody = json;\n\t\t\t\tconst err = json.error ?? json.message;\n\t\t\t\tif (typeof err === \"string\") {\n\t\t\t\t\tmessage = err;\n\t\t\t\t} else if (err && typeof err === \"object\") {\n\t\t\t\t\tmessage = JSON.stringify(err);\n\t\t\t\t}\n\t\t\t\tif (typeof json.code === \"string\") {\n\t\t\t\t\tcode = json.code;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tif (errorBody) message = errorBody;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tresponse.status === 422 &&\n\t\t\t\tcode === \"BYO_BREAKING_CHANGE\" &&\n\t\t\t\tparsedBody &&\n\t\t\t\ttypeof parsedBody === \"object\" &&\n\t\t\t\tisByoBreakingDetails((parsedBody as { details?: unknown }).details)\n\t\t\t) {\n\t\t\t\tthrow new ByoBreakingChangeError(\n\t\t\t\t\tmessage,\n\t\t\t\t\t(parsedBody as { details: ByoBreakingChangeDetails }).details,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new ApiError(response.status, message, parsedBody, code);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
|
|
7
7
|
"/**\n * Maps camelCase system column names (with or without `_` prefix) to the\n * actual snake_case DB column names used in query params.\n */\nconst SYSTEM_COLUMN_MAP: Record<string, string> = {\n\t// underscore-prefixed camelCase (canonical row shape)\n\t_blockHeight: \"_block_height\",\n\t_txId: \"_tx_id\",\n\t_createdAt: \"_created_at\",\n\t_id: \"_id\",\n\t// no-prefix aliases\n\tblockHeight: \"_block_height\",\n\ttxId: \"_tx_id\",\n\tcreatedAt: \"_created_at\",\n\tid: \"_id\",\n};\n\nfunction resolveColumn(col: string): string {\n\treturn SYSTEM_COLUMN_MAP[col] ?? col;\n}\n\n/**\n * Serializes a WhereInput object into the flat filter map expected by\n * SubgraphQueryParams.filters (and the REST API query string).\n *\n * Scalar values → `{ column: \"value\" }`\n * Comparison objects → `{ \"column.gte\": \"100\", \"column.lt\": \"200\" }`\n * System column aliases → `blockHeight` / `_blockHeight` both → `_block_height`\n */\nexport function serializeWhere(\n\twhere: Record<string, unknown>,\n): Record<string, string> {\n\tconst filters: Record<string, string> = {};\n\n\tfor (const [column, value] of Object.entries(where)) {\n\t\tif (value === null || value === undefined) continue;\n\n\t\tconst col = resolveColumn(column);\n\n\t\tif (typeof value === \"object\" && !Array.isArray(value)) {\n\t\t\tconst ops = value as Record<string, unknown>;\n\t\t\tfor (const [op, opValue] of Object.entries(ops)) {\n\t\t\t\tif (opValue === null || opValue === undefined) continue;\n\t\t\t\tif (op === \"eq\") {\n\t\t\t\t\tfilters[col] = String(opValue);\n\t\t\t\t} else if (op === \"in\" || op === \"notIn\") {\n\t\t\t\t\t// Array → comma list. Values can't contain commas (principals,\n\t\t\t\t\t// numbers, hashes don't) — the server splits on `,`.\n\t\t\t\t\tconst arr = Array.isArray(opValue) ? opValue : [opValue];\n\t\t\t\t\tfilters[`${col}.${op}`] = arr.map((v) => String(v)).join(\",\");\n\t\t\t\t} else if ([\"neq\", \"gt\", \"gte\", \"lt\", \"lte\", \"like\"].includes(op)) {\n\t\t\t\t\tfilters[`${col}.${op}`] = String(opValue);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfilters[col] = String(value);\n\t\t}\n\t}\n\n\treturn filters;\n}\n\n/**\n * Resolves an orderBy column name (either alias or canonical) to the DB column name.\n */\nexport function resolveOrderByColumn(col: string): string {\n\treturn resolveColumn(col);\n}\n",
|
|
8
8
|
"import type {\n\tReindexResponse,\n\tSubgraphAggregateParams,\n\tSubgraphAggregateResponse,\n\tSubgraphDetail,\n\tSubgraphGapsResponse,\n\tSubgraphQueryParams,\n\tSubgraphSummary,\n} from \"@secondlayer/shared/schemas\";\nimport type {\n\tDeploySubgraphRequest,\n\tDeploySubgraphResponse,\n} from \"@secondlayer/shared/schemas/subgraphs\";\nimport type {\n\tSubgraphAgentSchema,\n\tSubgraphSpecOptions,\n} from \"@secondlayer/shared/subgraphs/spec\";\nimport type {\n\tAggregateResult,\n\tAggregateSpec,\n\tFindManyOptions,\n\tInferSubgraphClient,\n\tSubscribeOptions,\n\tWhereInput,\n} from \"@secondlayer/subgraphs\";\nimport { BaseClient, buildQuery } from \"../base.ts\";\nimport { resolveOrderByColumn, serializeWhere } from \"./serialize.ts\";\n\nexport interface SubgraphSource {\n\tname: string;\n\tversion: string;\n\tsourceCode: string | null;\n\treadOnly: boolean;\n\treason?: string;\n\tupdatedAt: string;\n}\n\n/** Status of a tracked reindex/backfill operation (poll until terminal). */\nexport interface SubgraphOperationStatus {\n\tid: string;\n\tsubgraphName: string;\n\tkind: \"reindex\" | \"backfill\";\n\tstatus: \"queued\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\tfromBlock: number | null;\n\ttoBlock: number | null;\n\tprocessedBlocks: number | null;\n\t/** 0–1 fraction; null when no denominator is known yet. 1 when completed. */\n\tprogress: number | null;\n\terror: string | null;\n\tstartedAt: string | null;\n\tfinishedAt: string | null;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\n/** /v1 cursor envelope for subgraph table reads. */\nexport interface SubgraphRowsEnvelope<T = unknown> {\n\trows: T[];\n\tnext_cursor: string | null;\n\ttip: {\n\t\tblock_height: number;\n\t\tsubgraph_height: number;\n\t\tblocks_behind: number;\n\t};\n}\n\nexport interface BundleSubgraphResponse {\n\tok: true;\n\tname: string;\n\tversion: string | null;\n\tdescription: string | null;\n\tsources: Record<string, Record<string, unknown>>;\n\tschema: Record<string, unknown>;\n\thandlerCode: string;\n\tsourceCode: string;\n\tbundleSize: number;\n}\n\nfunction buildSubgraphQueryString(params: SubgraphQueryParams): string {\n\treturn buildQuery({\n\t\t_sort: params.sort,\n\t\t_order: params.order,\n\t\t_limit: params.limit,\n\t\t_offset: params.offset,\n\t\t_fields: params.fields,\n\t\t...params.filters,\n\t});\n}\n\nfunction buildAggregateQueryString(params: SubgraphAggregateParams): string {\n\treturn buildQuery({\n\t\t...params.filters,\n\t\t_count: params.count ? \"true\" : undefined, // emit only when truthy\n\t\t_countDistinct: params.countDistinct, // empty array → \"\" → skipped\n\t\t_sum: params.sum,\n\t\t_min: params.min,\n\t\t_max: params.max,\n\t});\n}\n\nfunction buildSpecQueryString(options?: SubgraphSpecOptions): string {\n\treturn buildQuery({ server: options?.serverUrl });\n}\n\nexport class Subgraphs extends BaseClient {\n\tasync list(): Promise<{ data: SubgraphSummary[] }> {\n\t\treturn this.request<{ data: SubgraphSummary[] }>(\"GET\", \"/api/subgraphs\");\n\t}\n\n\tasync get(name: string): Promise<SubgraphDetail> {\n\t\treturn this.request<SubgraphDetail>(\"GET\", `/api/subgraphs/${name}`);\n\t}\n\n\tasync openapi(\n\t\tname: string,\n\t\toptions?: SubgraphSpecOptions,\n\t): Promise<Record<string, unknown>> {\n\t\treturn this.request<Record<string, unknown>>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/openapi.json${buildSpecQueryString(options)}`,\n\t\t);\n\t}\n\n\tasync schema(\n\t\tname: string,\n\t\toptions?: SubgraphSpecOptions,\n\t): Promise<SubgraphAgentSchema> {\n\t\treturn this.request<SubgraphAgentSchema>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/schema.json${buildSpecQueryString(options)}`,\n\t\t);\n\t}\n\n\tasync markdown(name: string, options?: SubgraphSpecOptions): Promise<string> {\n\t\treturn this.requestText(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/docs.md${buildSpecQueryString(options)}`,\n\t\t);\n\t}\n\n\t/**\n\t * Reindex always drops and rebuilds the whole subgraph, so it takes no\n\t * block range — the API rejects one with `REINDEX_RANGE_NOT_SUPPORTED`.\n\t * Use {@link backfill} to process a specific range.\n\t */\n\tasync reindex(name: string): Promise<ReindexResponse> {\n\t\treturn this.request<ReindexResponse>(\n\t\t\t\"POST\",\n\t\t\t`/api/subgraphs/${name}/reindex`,\n\t\t);\n\t}\n\n\tasync stop(\n\t\tname: string,\n\t): Promise<{ message: string; operationId?: string; status?: string }> {\n\t\treturn this.request<{\n\t\t\tmessage: string;\n\t\t\toperationId?: string;\n\t\t\tstatus?: string;\n\t\t}>(\"POST\", `/api/subgraphs/${name}/stop`);\n\t}\n\n\tasync backfill(\n\t\tname: string,\n\t\toptions: { fromBlock: number; toBlock: number },\n\t): Promise<ReindexResponse> {\n\t\treturn this.request<ReindexResponse>(\n\t\t\t\"POST\",\n\t\t\t`/api/subgraphs/${name}/backfill`,\n\t\t\toptions,\n\t\t);\n\t}\n\n\tasync gaps(\n\t\tname: string,\n\t\topts?: { limit?: number; offset?: number; resolved?: boolean },\n\t): Promise<SubgraphGapsResponse> {\n\t\tconst qs = buildQuery({\n\t\t\t_limit: opts?.limit,\n\t\t\t_offset: opts?.offset,\n\t\t\tresolved: opts?.resolved,\n\t\t});\n\t\treturn this.request<SubgraphGapsResponse>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/gaps${qs}`,\n\t\t);\n\t}\n\n\tasync delete(\n\t\tname: string,\n\t\toptions?: { force?: boolean },\n\t): Promise<{ message: string }> {\n\t\tconst qs = buildQuery({ force: options?.force ? true : undefined });\n\t\treturn this.request<{ message: string }>(\n\t\t\t\"DELETE\",\n\t\t\t`/api/subgraphs/${name}${qs}`,\n\t\t);\n\t}\n\n\t/**\n\t * Publish: claim the name in the global public namespace and open anon\n\t * reads on /v1/subgraphs/:name. 409 PUBLIC_NAME_TAKEN if another account\n\t * holds the public name.\n\t */\n\tasync publish(\n\t\tname: string,\n\t): Promise<{ name: string; visibility: \"public\"; url: string }> {\n\t\treturn this.request<{ name: string; visibility: \"public\"; url: string }>(\n\t\t\t\"POST\",\n\t\t\t`/api/subgraphs/${name}/publish`,\n\t\t);\n\t}\n\n\t/** Make reads private again (owning account's bearer key required). */\n\tasync unpublish(\n\t\tname: string,\n\t): Promise<{ name: string; visibility: \"private\" }> {\n\t\treturn this.request<{ name: string; visibility: \"private\" }>(\n\t\t\t\"POST\",\n\t\t\t`/api/subgraphs/${name}/unpublish`,\n\t\t);\n\t}\n\n\t/**\n\t * Open /v1 read: cursor-paginated rows. Anon works for public subgraphs;\n\t * pass an apiKey on the client for private ones. Resume with the returned\n\t * `next_cursor`.\n\t */\n\tasync rows<T = unknown>(\n\t\tname: string,\n\t\ttable: string,\n\t\tparams: Omit<SubgraphQueryParams, \"offset\" | \"sort\"> & {\n\t\t\tcursor?: string;\n\t\t} = {},\n\t): Promise<SubgraphRowsEnvelope<T>> {\n\t\tconst { cursor, ...rest } = params;\n\t\tconst qs = buildSubgraphQueryString(rest);\n\t\tconst sep = qs ? \"&\" : \"?\";\n\t\tconst cursorQs = cursor ? `${sep}cursor=${encodeURIComponent(cursor)}` : \"\";\n\t\treturn this.request<SubgraphRowsEnvelope<T>>(\n\t\t\t\"GET\",\n\t\t\t`/v1/subgraphs/${name}/${table}${qs}${cursorQs}`,\n\t\t);\n\t}\n\n\t/** Recent reindex/backfill operations for a subgraph, newest first. */\n\tasync operations(\n\t\tname: string,\n\t): Promise<{ operations: SubgraphOperationStatus[] }> {\n\t\treturn this.request<{ operations: SubgraphOperationStatus[] }>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/operations`,\n\t\t);\n\t}\n\n\t/** Status of a single operation (poll the `operationId` returned by\n\t * reindex/backfill/stop until `status` is terminal). */\n\tasync getOperation(\n\t\tname: string,\n\t\toperationId: string,\n\t): Promise<SubgraphOperationStatus> {\n\t\treturn this.request<SubgraphOperationStatus>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/operations/${operationId}`,\n\t\t);\n\t}\n\n\tasync deploy(data: DeploySubgraphRequest): Promise<DeploySubgraphResponse> {\n\t\treturn this.request<DeploySubgraphResponse>(\"POST\", \"/api/subgraphs\", data);\n\t}\n\n\tasync getSource(name: string): Promise<SubgraphSource> {\n\t\treturn this.request<SubgraphSource>(\"GET\", `/api/subgraphs/${name}/source`);\n\t}\n\n\t/**\n\t * Bundle a TypeScript subgraph source on the server. Used by the web chat\n\t * authoring loop so Vercel's serverless runtime doesn't have to run esbuild.\n\t */\n\tasync bundle(data: { code: string }): Promise<BundleSubgraphResponse> {\n\t\treturn this.request<BundleSubgraphResponse>(\n\t\t\t\"POST\",\n\t\t\t\"/api/subgraphs/bundle\",\n\t\t\tdata,\n\t\t);\n\t}\n\n\tasync queryTable(\n\t\tname: string,\n\t\ttable: string,\n\t\tparams: SubgraphQueryParams = {},\n\t): Promise<unknown[]> {\n\t\tconst result = await this.request<{ data: unknown[] } | unknown[]>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/${table}${buildSubgraphQueryString(params)}`,\n\t\t);\n\t\treturn Array.isArray(result) ? result : result.data;\n\t}\n\n\tasync queryTableCount(\n\t\tname: string,\n\t\ttable: string,\n\t\tparams: SubgraphQueryParams = {},\n\t): Promise<{ count: number }> {\n\t\treturn this.request<{ count: number }>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/${table}/count${buildSubgraphQueryString(params)}`,\n\t\t);\n\t}\n\n\tasync queryTableAggregate(\n\t\tname: string,\n\t\ttable: string,\n\t\tparams: SubgraphAggregateParams = {},\n\t): Promise<SubgraphAggregateResponse> {\n\t\treturn this.request<SubgraphAggregateResponse>(\n\t\t\t\"GET\",\n\t\t\t`/api/subgraphs/${name}/${table}/aggregate${buildAggregateQueryString(params)}`,\n\t\t);\n\t}\n\n\t/**\n\t * Returns a typed client for a subgraph defined with `defineSubgraph()`.\n\t * Row types are inferred from the subgraph's schema literal types.\n\t *\n\t * @example\n\t * ```ts\n\t * import mySubgraph from './subgraphs/my-token-subgraph'\n\t * const client = sl.subgraphs.typed(mySubgraph)\n\t * const rows = await client.transfers.findMany({ where: { sender: 'SP...' } })\n\t * // rows: InferTableRow<typeof mySubgraph.schema.transfers>[]\n\t * ```\n\t */\n\ttyped<T extends { name: string; schema: Record<string, unknown> }>(\n\t\tdef: T,\n\t): InferSubgraphClient<T> {\n\t\tconst result: Record<string, unknown> = {};\n\n\t\tfor (const tableName of Object.keys(def.schema)) {\n\t\t\tresult[tableName] = this.createTableClient(def.name, tableName);\n\t\t}\n\n\t\treturn result as InferSubgraphClient<T>;\n\t}\n\n\tprivate createTableClient(subgraphName: string, tableName: string) {\n\t\tconst self = this;\n\n\t\treturn {\n\t\t\tasync findMany<TRow>(\n\t\t\t\toptions: Omit<FindManyOptions<TRow>, \"fields\"> & {\n\t\t\t\t\tfields?: readonly (keyof TRow & string)[];\n\t\t\t\t} = {},\n\t\t\t): Promise<TRow[]> {\n\t\t\t\tconst filters = options.where\n\t\t\t\t\t? serializeWhere(options.where as Record<string, unknown>)\n\t\t\t\t\t: undefined;\n\n\t\t\t\tlet sort: string | undefined;\n\t\t\t\tlet order: string | undefined;\n\t\t\t\tif (options.orderBy) {\n\t\t\t\t\t// Accept the object form `{ col: \"asc\" }` or the ordered array\n\t\t\t\t\t// form `[[col, \"asc\"], …]` for deterministic multi-column sort.\n\t\t\t\t\tconst entries: [string, \"asc\" | \"desc\"][] = Array.isArray(\n\t\t\t\t\t\toptions.orderBy,\n\t\t\t\t\t)\n\t\t\t\t\t\t? (options.orderBy as [string, \"asc\" | \"desc\"][])\n\t\t\t\t\t\t: (Object.entries(options.orderBy) as [string, \"asc\" | \"desc\"][]);\n\t\t\t\t\tif (entries.length > 0) {\n\t\t\t\t\t\t// Comma-joined parallel lists → `_sort=a,b&_order=asc,desc`.\n\t\t\t\t\t\tsort = entries.map(([col]) => resolveOrderByColumn(col)).join(\",\");\n\t\t\t\t\t\torder = entries.map(([, dir]) => dir ?? \"asc\").join(\",\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst params: SubgraphQueryParams = {\n\t\t\t\t\tsort,\n\t\t\t\t\torder,\n\t\t\t\t\tlimit: options.limit,\n\t\t\t\t\toffset: options.offset,\n\t\t\t\t\tfields: options.fields?.join(\",\"),\n\t\t\t\t\tfilters,\n\t\t\t\t};\n\n\t\t\t\treturn self.queryTable(subgraphName, tableName, params) as Promise<\n\t\t\t\t\tTRow[]\n\t\t\t\t>;\n\t\t\t},\n\n\t\t\tasync count<TRow>(where?: WhereInput<TRow>): Promise<number> {\n\t\t\t\tconst filters = where\n\t\t\t\t\t? serializeWhere(where as Record<string, unknown>)\n\t\t\t\t\t: undefined;\n\n\t\t\t\tconst result = await self.queryTableCount(subgraphName, tableName, {\n\t\t\t\t\tfilters,\n\t\t\t\t});\n\t\t\t\treturn result.count;\n\t\t\t},\n\n\t\t\tasync aggregate<TRow, const A extends AggregateSpec<TRow>>(\n\t\t\t\tspec: A,\n\t\t\t): Promise<AggregateResult<TRow, A>> {\n\t\t\t\tconst filters = spec.where\n\t\t\t\t\t? serializeWhere(spec.where as Record<string, unknown>)\n\t\t\t\t\t: undefined;\n\n\t\t\t\tconst result = await self.queryTableAggregate(subgraphName, tableName, {\n\t\t\t\t\tfilters,\n\t\t\t\t\tcount: spec.count,\n\t\t\t\t\tcountDistinct: spec.countDistinct,\n\t\t\t\t\tsum: spec.sum,\n\t\t\t\t\tmin: spec.min,\n\t\t\t\t\tmax: spec.max,\n\t\t\t\t});\n\t\t\t\treturn result as AggregateResult<TRow, A>;\n\t\t\t},\n\n\t\t\tsubscribe<TRow>(\n\t\t\t\tonRow: (row: TRow) => void,\n\t\t\t\toptions: SubscribeOptions<TRow> = {},\n\t\t\t): () => void {\n\t\t\t\tconst filters = options.where\n\t\t\t\t\t? serializeWhere(options.where as Record<string, unknown>)\n\t\t\t\t\t: {};\n\t\t\t\tconst qs = buildQuery({\n\t\t\t\t\t...filters,\n\t\t\t\t\tsince: options.since ?? undefined,\n\t\t\t\t});\n\t\t\t\tconst url = `${self.baseUrl}/api/subgraphs/${subgraphName}/${tableName}/stream${qs}`;\n\n\t\t\t\ttype EventSourceLike = {\n\t\t\t\t\tonmessage: ((ev: { data: string }) => void) | null;\n\t\t\t\t\tonerror: ((ev: unknown) => void) | null;\n\t\t\t\t\tclose(): void;\n\t\t\t\t};\n\t\t\t\tconst ES = (\n\t\t\t\t\tglobalThis as unknown as {\n\t\t\t\t\t\tEventSource?: new (url: string) => EventSourceLike;\n\t\t\t\t\t}\n\t\t\t\t).EventSource;\n\t\t\t\tif (!ES) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"subscribe() needs a global EventSource (available in browsers and Node >= 22).\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst es = new ES(url);\n\t\t\t\tes.onmessage = (ev) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonRow(JSON.parse(ev.data) as TRow);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// ignore non-JSON frames (e.g. heartbeats)\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tif (options.onError) {\n\t\t\t\t\tconst handler = options.onError;\n\t\t\t\t\tes.onerror = (ev) => handler(ev);\n\t\t\t\t}\n\t\t\t\treturn () => es.close();\n\t\t\t},\n\t\t};\n\t}\n}\n",
|
|
9
9
|
"import { BaseClient, type SecondLayerOptions } from \"../base.ts\";\n\n/**\n * Typed client for the agent-reachable key mint (`POST /v1/api-keys`).\n *\n * Lets a headless agent self-provision a SCOPED `streams`/`index` read key\n * without the dashboard. Requires an owner credential — an account-level API\n * key (or a dashboard session). The minted key is always scoped (never an\n * account/superkey) and inherits the account plan's tier.\n */\n\n/** Scope of a minted read key. */\nexport type ScopedKeyProduct = \"streams\" | \"index\";\n\nexport interface CreateApiKeyParams {\n\t/** Scope of the minted key. Defaults to \"streams\". */\n\tproduct?: ScopedKeyProduct;\n\t/** Optional human-readable label for the key. */\n\tname?: string;\n}\n\nexport interface CreateApiKeyResponse {\n\t/** Plaintext key — returned ONCE. Store it now; only its hash is persisted. */\n\tkey: string;\n\tprefix: string;\n\tid: string;\n\tproduct: string;\n\ttier: string | null;\n\tcreatedAt: string;\n}\n\n/** A key as seen by {@link ApiKeys.list} — metadata only, never the plaintext. */\nexport interface ApiKeySummary {\n\tid: string;\n\tprefix: string;\n\tname: string | null;\n\tstatus: \"active\" | \"revoked\";\n\tproduct: string;\n\ttier: string | null;\n\tcreatedAt: string;\n\tlastUsedAt: string | null;\n}\n\nexport class ApiKeys extends BaseClient {\n\tconstructor(options: Partial<SecondLayerOptions> = {}) {\n\t\tsuper(options);\n\t}\n\n\t/**\n\t * Mint a new scoped read key. The configured `apiKey` must be an\n\t * account-level (owner) key; the plaintext `key` in the response is shown\n\t * only once.\n\t */\n\tcreate(params: CreateApiKeyParams = {}): Promise<CreateApiKeyResponse> {\n\t\treturn this.request<CreateApiKeyResponse>(\"POST\", \"/v1/api-keys\", {\n\t\t\tproduct: params.product,\n\t\t\tname: params.name,\n\t\t});\n\t}\n\n\t/**\n\t * List the account's keys (metadata only — no plaintext). Requires an\n\t * account-level (owner) key or a dashboard session.\n\t */\n\tlist(): Promise<{ keys: ApiKeySummary[] }> {\n\t\treturn this.request<{ keys: ApiKeySummary[] }>(\"GET\", \"/api/keys\");\n\t}\n\n\t/** Revoke a key by id. Existing requests with that key stop working. */\n\trevoke(id: string): Promise<{ revoked: true; id: string }> {\n\t\treturn this.request<{ revoked: true; id: string }>(\n\t\t\t\"DELETE\",\n\t\t\t`/api/keys/${id}`,\n\t\t);\n\t}\n}\n",
|
package/dist/x402.d.ts
CHANGED
|
@@ -113,11 +113,12 @@ type X402Fetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
|
|
|
113
113
|
*
|
|
114
114
|
* @example
|
|
115
115
|
* const x402fetch = withX402(fetch, { account });
|
|
116
|
-
* const res = await x402fetch("
|
|
116
|
+
* const res = await x402fetch("http://127.0.0.1:3800/v1/index/events?event_type=ft_transfer");
|
|
117
117
|
*/
|
|
118
118
|
declare function withX402(baseFetch: typeof fetch, opts: WithX402Options): X402Fetch;
|
|
119
119
|
type X402ClientOptions = WithX402Options & {
|
|
120
|
-
|
|
120
|
+
/** Instance API. Defaults to {@link resolveBaseUrl}. */
|
|
121
|
+
baseUrl?: string;
|
|
121
122
|
/** Override the underlying fetch (tests). */
|
|
122
123
|
fetch?: typeof fetch;
|
|
123
124
|
};
|
|
@@ -140,7 +141,7 @@ type X402Client = {
|
|
|
140
141
|
* parsed JSON plus the settlement receipt.
|
|
141
142
|
*
|
|
142
143
|
* @example
|
|
143
|
-
* const sl = createX402Client({ account, baseUrl: "
|
|
144
|
+
* const sl = createX402Client({ account, baseUrl: "http://127.0.0.1:3800" });
|
|
144
145
|
* const { data, payment } = await sl.get("/v1/index/events", { query: { event_type: "ft_transfer" } });
|
|
145
146
|
*/
|
|
146
147
|
declare function createX402Client(opts: X402ClientOptions): X402Client;
|