@secondlayer/sdk 10.3.0 → 10.4.0
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 +23 -21
- package/dist/index.d.ts +53 -23
- package/dist/index.js +38 -39
- package/dist/index.js.map +8 -8
- package/dist/streams/index.js.map +1 -1
- package/dist/subgraphs/index.d.ts +20 -12
- package/dist/subgraphs/index.js +34 -36
- package/dist/subgraphs/index.js.map +7 -7
- package/package.json +4 -4
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import { ed25519 } from \"@secondlayer/shared\";\nimport { buildQuery, resolveApiKey, resolveBaseUrl } from \"../base.ts\";\nimport type { IndexEvent } from \"../index-api/client.ts\";\nimport type { ConsumerSink } from \"../sinks/types.ts\";\nimport {\n\ttype StreamsEventsFetcher,\n\tconsumeStreamsEvents,\n\titerateStreamsBatches,\n\tstreamStreamsEvents,\n} from \"./consumer.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { decode } from \"./decode.ts\";\nimport { createStreamsDumps } from \"./dumps.ts\";\nimport {\n\tStreamsServerError,\n\tStreamsSignatureError,\n\tValidationError,\n\tmapStreamsError,\n} from \"./errors.ts\";\nimport { 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} from \"./types.ts\";\n\n/** Parse a `<block>:<index>` cursor; null sorts before genesis. */\nfunction cursorTuple(cursor: string | null): [number, number] {\n\tif (!cursor) return [-1, -1];\n\tconst { blockHeight, eventIndex } = Cursor.parse(cursor);\n\treturn [blockHeight, eventIndex];\n}\n\n/** The greater of two cursors (later in the stream). */\nfunction maxCursor(a: string | null, b: string | null): string | null {\n\tconst [ah, ai] = cursorTuple(a);\n\tconst [bh, bi] = cursorTuple(b);\n\treturn ah > bh || (ah === bh && ai >= bi) ? a : b;\n}\n\n/**\n * The narrowing set every Streams read forwards verbatim to the consumer\n * loops. Kept in one place because each field is optional: a forgotten one is\n * a type-checkable object that silently widens the stream toward the full\n * firehose — which is billed per row, and has happened. `events.replay()`\n * deliberately forwards a subset and stays explicit.\n */\nfunction streamsFilters(params: {\n\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\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\tfetchImpl?: FetchLike;\n\t/**\n\t * Public base URL for bulk parquet dumps (the R2/CDN bucket root). Required\n\t * to use `client.dumps`. See `GET /public/streams/dumps/manifest`.\n\t */\n\tdumpsBaseUrl?: string;\n\t/**\n\t * Verify the ed25519 `X-Signature` on every REST response and per-frame SSE\n\t * signature. Three states:\n\t * - **default (omitted)** — *lenient*: verify when the server signs (the\n\t * hosted API signs every response), and pass through when no signature is\n\t * present (e.g. a self-hosted instance with no `STREAMS_SIGNING_PRIVATE_KEY`).\n\t * So verification is on by default against the hosted API without breaking\n\t * unsigned self-host deployments. An *invalid* signature always throws.\n\t * - **`true`** (or `{ publicKey }` to pin a known PEM) — *strict*: a missing\n\t * OR invalid signature throws `StreamsSignatureError`. Use this when you\n\t * require a portable, non-repudiable attestation and won't accept unsigned\n\t * data (it also closes the lenient mode's strip-the-header downgrade).\n\t * - **`false`** — off.\n\t *\n\t * The key is fetched once from `/public/streams/signing-key` (cached; a\n\t * rotated `X-Signature-KeyId` triggers one refresh) unless a PEM is pinned.\n\t */\n\tverify?: boolean | { publicKey: string };\n\t/**\n\t * Verify the bulk dumps manifest's ed25519 signature in `client.dumps.list()`\n\t * before trusting any file sha256 (default ON). Uses the same key source as\n\t * `verify` (fetches `/public/streams/signing-key`, or a pinned PEM). Pass\n\t * `false` to opt out. A missing or invalid signature throws\n\t * `StreamsSignatureError`.\n\t */\n\tverifyDumpsManifest?: boolean;\n};\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\n\n/** Loopback hosts, where plain http carries no more exposure than the box\n * itself. Anywhere else, http means a network hop anyone on the path can\n * rewrite, key endpoint included. */\nfunction isLoopbackUrl(baseUrl: string): boolean {\n\ttry {\n\t\tconst { hostname } = new URL(baseUrl);\n\t\treturn (\n\t\t\thostname === \"localhost\" ||\n\t\t\thostname === \"127.0.0.1\" ||\n\t\t\thostname === \"::1\" ||\n\t\t\thostname === \"[::1]\" ||\n\t\t\thostname.startsWith(\"127.\")\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function createStreamsClient(\n\toptions: CreateStreamsClientOptions,\n): StreamsClient {\n\tconst baseUrl = normalizeBaseUrl(resolveBaseUrl(options.baseUrl));\n\t// Same credential precedence as every other client (explicit option, then\n\t// INSTANCE_TOKEN, then SL_API_KEY), so the same code authenticates the same\n\t// way whether it enters through `new SecondLayer()` or here.\n\tconst apiKey = resolveApiKey(options.apiKey);\n\tconst origin = options.origin ?? \"cli\";\n\tconst authHeaders = (): Record<string, string> => ({\n\t\t\"x-sl-origin\": origin,\n\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t});\n\tconst fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));\n\tconst verify = options.verify;\n\t// On by default, but lenient: the hosted API signs every response, while a\n\t// self-hosted instance without STREAMS_SIGNING_PRIVATE_KEY serves none.\n\t// Lenient verifies when a signature is present and passes through when it is\n\t// absent — so the default neither skips hosted verification nor breaks OSS.\n\t// `verify: true` / `{ publicKey }` is strict (missing signature throws);\n\t// `verify: false` is off. An invalid signature always throws.\n\tconst verifyMode: \"off\" | \"lenient\" | \"strict\" =\n\t\tverify === false ? \"off\" : verify === undefined ? \"lenient\" : \"strict\";\n\t// Strict mode promises the response came from the holder of a known key.\n\t// A key fetched over plain http from a host off the box is whatever the\n\t// path served, so the promise only holds with a pinned PEM there.\n\tif (\n\t\tverify === true &&\n\t\tbaseUrl.startsWith(\"http:\") &&\n\t\t!isLoopbackUrl(baseUrl)\n\t) {\n\t\tthrow new ValidationError(\n\t\t\t`verify: true over plain http to ${baseUrl} fetches the signing key from the same unprotected path it verifies. Pin the key with verify: { publicKey } (see GET /public/streams/signing-key), or use https.`,\n\t\t\t400,\n\t\t);\n\t}\n\n\t// Lazily resolve and cache the verification key alongside its id, so a\n\t// rotation (signalled by a changed `X-Signature-KeyId`) can be detected.\n\ttype VerificationKey = {\n\t\tkeyId: string;\n\t\tpublicKeyPem: string;\n\t\tpublicKey: ReturnType<typeof ed25519.loadEd25519PublicKey>;\n\t};\n\t// Only a successful fetch stays cached. A 5xx or a dropped socket on the\n\t// key endpoint used to park a rejected promise here for the life of the\n\t// client; now it surfaces as a retryable error and the next call refetches.\n\tlet keyPromise: Promise<VerificationKey> | null = null;\n\tfunction loadKey(): Promise<VerificationKey> {\n\t\tif (keyPromise) return keyPromise;\n\t\tconst pending = (async () => {\n\t\t\tif (typeof verify === \"object\") {\n\t\t\t\treturn {\n\t\t\t\t\tkeyId: ed25519.ed25519KeyId(verify.publicKey),\n\t\t\t\t\tpublicKeyPem: verify.publicKey,\n\t\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(verify.publicKey),\n\t\t\t\t};\n\t\t\t}\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetchImpl(`${baseUrl}/public/streams/signing-key`);\n\t\t\t} catch {\n\t\t\t\tthrow new StreamsServerError(\n\t\t\t\t\t`Could not reach the signing key at ${baseUrl}/public/streams/signing-key. Retryable.`,\n\t\t\t\t\t0,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"SIGNING_KEY_UNAVAILABLE\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (res.status >= 500 || res.status === 429) {\n\t\t\t\t\tthrow new StreamsServerError(\n\t\t\t\t\t\t`Could not fetch signing key (${res.status}). Retryable.`,\n\t\t\t\t\t\tres.status,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\"SIGNING_KEY_UNAVAILABLE\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t\t`Could not fetch signing key (${res.status}).`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst body = (await res.json()) as {\n\t\t\t\tpublic_key_pem?: string;\n\t\t\t\tkey_id?: string;\n\t\t\t};\n\t\t\tif (!body.public_key_pem) {\n\t\t\t\tthrow new StreamsSignatureError(\"Signing key response missing key.\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkeyId: body.key_id ?? ed25519.ed25519KeyId(body.public_key_pem),\n\t\t\t\tpublicKeyPem: body.public_key_pem,\n\t\t\t\tpublicKey: ed25519.loadEd25519PublicKey(body.public_key_pem),\n\t\t\t};\n\t\t})();\n\t\tkeyPromise = pending;\n\t\tpending.catch(() => {\n\t\t\tif (keyPromise === pending) keyPromise = null;\n\t\t});\n\t\treturn pending;\n\t}\n\t/** Resolve the key a response claims to be signed with. A fetched key\n\t * refreshes once on an unknown id; a pinned key never changes, so an\n\t * unknown id is a failure either way. Shared by REST reads and SSE frames. */\n\tasync function loadKeyFor(\n\t\tresponseKeyId: string | null | undefined,\n\t): Promise<VerificationKey> {\n\t\tlet key = await loadKey();\n\t\tif (!responseKeyId || responseKeyId === key.keyId) return key;\n\t\tif (typeof verify === \"object\") {\n\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t`Response signed with key '${responseKeyId}', expected pinned key '${key.keyId}'.`,\n\t\t\t);\n\t\t}\n\t\t// Refresh once. A still-mismatched id (no re-loop) means the endpoint\n\t\t// does not serve the signing key: fail closed.\n\t\tkeyPromise = null;\n\t\tkey = await loadKey();\n\t\tif (responseKeyId !== key.keyId) {\n\t\t\tthrow new StreamsSignatureError(\n\t\t\t\t`Response signed with key '${responseKeyId}' not served by the signing-key endpoint.`,\n\t\t\t);\n\t\t}\n\t\treturn key;\n\t}\n\n\tconst dumps = createStreamsDumps({\n\t\tbaseUrl: options.dumpsBaseUrl,\n\t\tfetchImpl,\n\t\tverifyManifest: options.verifyDumpsManifest ?? true,\n\t\tloadPublicKeyPem: async () => (await loadKey()).publicKeyPem,\n\t});\n\n\tasync function request<T>(path: string): Promise<T> {\n\t\tconst response = await fetchImpl(`${baseUrl}${path}`, {\n\t\t\theaders: authHeaders(),\n\t\t});\n\t\tif (!response.ok) await mapStreamsError(response);\n\t\tconst text = await response.text();\n\t\tif (verifyMode !== \"off\") {\n\t\t\tconst signature = response.headers.get(\"X-Signature\");\n\t\t\tif (!signature) {\n\t\t\t\t// Strict requires a signature; lenient (default) lets an unsigned\n\t\t\t\t// response through — e.g. self-host with no signing key configured.\n\t\t\t\tif (verifyMode === \"strict\") {\n\t\t\t\t\tthrow new StreamsSignatureError(\"Response is missing X-Signature.\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst key = await loadKeyFor(response.headers.get(\"X-Signature-KeyId\"));\n\t\t\t\t// A signature is present, so verify it regardless of strict/lenient —\n\t\t\t\t// an invalid signature always fails closed.\n\t\t\t\tif (!ed25519.verifyEd25519(text, signature, key.publicKey)) {\n\t\t\t\t\tthrow new StreamsSignatureError();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn JSON.parse(text) as T;\n\t}\n\n\t// StreamsEventsFetchParams 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 listReorgs(params: StreamsReorgsListParams) {\n\t\treturn request<StreamsReorgsListEnvelope>(\n\t\t\t`/v1/streams/reorgs${buildQuery({\n\t\t\t\tsince: params.since,\n\t\t\t\tlimit: params.limit,\n\t\t\t})}`,\n\t\t);\n\t}\n\t// Idle-tip reorg detection for the consume loop (one request per empty\n\t// page); the public `reorgs.list` is the same call.\n\tconst fetchReorgs = (params: { since: string }) => listReorgs(params);\n\n\tfunction encodeFilters(filters: StreamsFilterMap | undefined) {\n\t\treturn filters ? JSON.stringify(filters) : undefined;\n\t}\n\n\tasync function listEvents(\n\t\tparams: StreamsEventsListParams = {},\n\t): Promise<StreamsEventsEnvelope> {\n\t\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\tfetchReorgs,\n\t\t\tonBatch,\n\t\t\tonReorg: params.onReorg,\n\t\t\tmaxRollbackDepth: params.maxRollbackDepth,\n\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\tmaxPages: params.maxPages,\n\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\tsignal: params.signal,\n\t\t\tretryCount: params.retryCount,\n\t\t\tretryDelay: params.retryDelay,\n\t\t\tonError: params.onError,\n\t\t});\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\theaders: authHeaders(),\n\t\t\t\t\tfetchImpl,\n\t\t\t\t\tverify: verifyMode,\n\t\t\t\t\tloadKey: loadKeyFor,\n\t\t\t\t\treconnectDelayMs: params.reconnectDelayMs,\n\t\t\t\t\tstaleAfterMs: params.staleAfterMs,\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. Files\n\t\t\t\t// ending at or below `from` carry nothing new; a file straddling\n\t\t\t\t// it is handed over whole, with `from` so the handler can skip\n\t\t\t\t// the rows at or below the checkpoint (file-granular delivery).\n\t\t\t\tconst files = manifest.files\n\t\t\t\t\t.filter((file) => file.to_block >= fromBlock)\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(file) =>\n\t\t\t\t\t\t\tfromCursor === null ||\n\t\t\t\t\t\t\tfile.max_cursor === null ||\n\t\t\t\t\t\t\tmaxCursor(fromCursor, file.max_cursor) !== fromCursor,\n\t\t\t\t\t)\n\t\t\t\t\t.sort(\n\t\t\t\t\t\t(a, b) => a.from_block - b.from_block || a.to_block - b.to_block,\n\t\t\t\t\t);\n\t\t\t\tfor (const file of files) {\n\t\t\t\t\tif (params.signal?.aborted) break;\n\t\t\t\t\tawait params.onDumpFile(file, { from: fromCursor });\n\t\t\t\t}\n\n\t\t\t\t// Seam: tail live from just past the dumped coverage. Cursor input is\n\t\t\t\t// exclusive, so the first live event is strictly after the last dump.\n\t\t\t\tconst seam = maxCursor(fromCursor, manifest.latest_finalized_cursor);\n\t\t\t\treturn consumeStreamsEvents({\n\t\t\t\t\tfromCursor: seam,\n\t\t\t\t\tmode: params.mode ?? \"tail\",\n\t\t\t\t\tbatchSize: params.batchSize ?? 100,\n\t\t\t\t\t// Live-tail narrowing only — the dump phase above hands over\n\t\t\t\t\t// whole all-type files by design.\n\t\t\t\t\ttypes: params.types,\n\t\t\t\t\tnotTypes: params.notTypes,\n\t\t\t\t\tfilters: params.filters,\n\t\t\t\t\tfetchEvents,\n\t\t\t\t\tonBatch: params.onBatch,\n\t\t\t\t\tonReorg: params.onReorg,\n\t\t\t\t\temptyBackoffMs: params.emptyBackoffMs,\n\t\t\t\t\tmaxPages: params.maxPages,\n\t\t\t\t\tmaxEmptyPolls: params.maxEmptyPolls,\n\t\t\t\t\tsignal: params.signal,\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tblocks: {\n\t\t\tevents(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: { list: listReorgs },\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};\n}\n",
|
|
6
6
|
"const DOCS_BASE = \"https://www.secondlayer.tools\";\n\n/** Options accepted by every error in the family. */\nexport interface SecondLayerErrorOptions {\n\tcause?: Error;\n\tdetails?: string;\n\t/** Stable machine-readable code (e.g. `UPGRADE_REQUIRED`). */\n\tcode?: string;\n\t/** Docs page that explains this failure and its fix. */\n\tdocsUrl?: string;\n\t/** Extra context lines appended to the message (DDL to run, next steps). */\n\tmetaMessages?: string[];\n\t/** Whether retrying the SAME request can succeed (429/5xx/network). */\n\tretryable?: boolean;\n\t/** Parsed `Retry-After`, in seconds — set on rate limits that carry it. */\n\tretryAfterSeconds?: number;\n}\n\n/**\n * Root of the SDK error family. Implements the same protocol as `BaseError`\n * in `@secondlayer/stacks` (`shortMessage`, `cause`, `toJSON`) so a failed\n * chain read and a failed platform read serialize and introspect identically.\n * It intentionally does NOT extend that class: cross-package `instanceof` is\n * unreliable under per-package bundling anyway (match on `code`/`name` across\n * packages).\n *\n * `retryable` is the signal the consume loops act on: 429/5xx/network are\n * retryable, 4xx and body-serialization failures are not.\n */\nexport class SecondLayerError extends Error {\n\toverride name = \"SecondLayerError\";\n\t/** The one-line failure, without the appended context blocks. */\n\tshortMessage: string;\n\tcode?: string;\n\tdocsUrl?: string;\n\tmetaMessages?: string[];\n\tretryable: boolean;\n\tretryAfterSeconds?: number;\n\n\tconstructor(shortMessage: string, options: SecondLayerErrorOptions = {}) {\n\t\tconst detailBlocks = [\n\t\t\t...(options.metaMessages ?? []),\n\t\t\t...(options.details ? [options.details] : []),\n\t\t\t...(options.docsUrl ? [`Docs: ${options.docsUrl}`] : []),\n\t\t];\n\t\tconst message = [\n\t\t\tshortMessage,\n\t\t\tdetailBlocks.length > 0 ? `\\n${detailBlocks.join(\"\\n\")}` : \"\",\n\t\t].join(\"\");\n\t\tsuper(message, options.cause ? { cause: options.cause } : undefined);\n\t\tthis.shortMessage = shortMessage;\n\t\tthis.code = options.code;\n\t\tthis.docsUrl = options.docsUrl;\n\t\tthis.metaMessages = options.metaMessages;\n\t\tthis.retryable = options.retryable ?? false;\n\t\tthis.retryAfterSeconds = options.retryAfterSeconds;\n\t}\n\n\t/**\n\t * Walk the cause chain. With a predicate, returns the first error matching\n\t * it (or `null`); without one, returns the deepest cause. Mirrors viem's\n\t * `error.walk()` so cross-library error handling reads the same.\n\t */\n\twalk(fn?: (err: unknown) => boolean): unknown {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: cause chains are untyped by nature\n\t\tlet err: any = this;\n\t\tlet last: unknown = this;\n\t\twhile (err != null) {\n\t\t\tif (fn?.(err)) return err;\n\t\t\tlast = err;\n\t\t\terr = err.cause;\n\t\t}\n\t\treturn fn ? null : last;\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tmessage: string;\n\t\tshortMessage: string;\n\t\tcause: string | undefined;\n\t\tcode: string | undefined;\n\t\tdocsUrl: string | undefined;\n\t\tretryable: boolean;\n\t\tretryAfterSeconds: number | undefined;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tshortMessage: this.shortMessage,\n\t\t\tcause: this.cause instanceof Error ? this.cause.message : undefined,\n\t\t\tcode: this.code,\n\t\t\tdocsUrl: this.docsUrl,\n\t\t\tretryable: this.retryable,\n\t\t\tretryAfterSeconds: this.retryAfterSeconds,\n\t\t};\n\t}\n}\n\n/** Retryability of an HTTP status: 429 and 5xx are transient. */\nfunction statusRetryable(status: number): boolean {\n\treturn status === 429 || status >= 500;\n}\n\n/** Docs page for a status/code pair, when one exists. */\nfunction docsFor(status: number, code?: string): string | undefined {\n\tif (code === \"UPGRADE_REQUIRED\" || status === 402)\n\t\treturn `${DOCS_BASE}/docs/authentication#pay-as-you-go-credits`;\n\tif (status === 429 || status === 401)\n\t\treturn `${DOCS_BASE}/docs/authentication`;\n\treturn undefined;\n}\n\n/**\n * Error thrown by {@link SecondLayer} when an API request fails.\n * Includes the HTTP status code for programmatic error handling.\n *\n * @example\n * ```ts\n * try {\n * await client.subgraphs.status(\"my-subgraph\");\n * } catch (err) {\n * if (err instanceof ApiError && err.status === 404) {\n * console.log(\"Subgraph not found\");\n * }\n * }\n * ```\n */\nexport class ApiError extends SecondLayerError {\n\tconstructor(\n\t\t/** HTTP status code (0 for network errors). */\n\t\tpublic status: number,\n\t\tmessage: string,\n\t\t/** Raw response body (parsed JSON if possible) — preserved for callers that need error details. */\n\t\tpublic body?: unknown,\n\t\t/** Stable machine-readable code from the API's `{error, code}` error envelope. */\n\t\tcode?: string,\n\t\toptions: SecondLayerErrorOptions = {},\n\t) {\n\t\tsuper(message, {\n\t\t\tcode,\n\t\t\tretryable: options.retryable ?? statusRetryable(status),\n\t\t\tdocsUrl: options.docsUrl ?? docsFor(status, code),\n\t\t\t...(options.cause ? { cause: options.cause } : {}),\n\t\t\t...(options.details ? { details: options.details } : {}),\n\t\t\t...(options.metaMessages ? { metaMessages: options.metaMessages } : {}),\n\t\t\t...(options.retryAfterSeconds !== undefined\n\t\t\t\t? { retryAfterSeconds: options.retryAfterSeconds }\n\t\t\t\t: {}),\n\t\t});\n\t\tthis.name = \"ApiError\";\n\t}\n}\n\n/** Thrown on a 401 by both the instance clients and Streams. Carries the\n * server's `{error, code}` envelope when it sent one, so a revoked token reads\n * differently from a missing one. */\nexport class AuthError extends ApiError {\n\toverride readonly status = 401 as const;\n\n\tconstructor(\n\t\tmessage = \"API key invalid or expired.\",\n\t\tbody?: unknown,\n\t\tcode?: string,\n\t) {\n\t\tsuper(401, message, body, code);\n\t\tthis.name = \"AuthError\";\n\t}\n}\n\n/** Thrown on a 429 by both the instance clients and Streams. `retryable`,\n * with `retryAfterSeconds` parsed from the `Retry-After` header when sent. */\nexport class RateLimitError extends ApiError {\n\toverride readonly status = 429 as const;\n\n\tconstructor(\n\t\tmessage = \"Rate limited. Try again later.\",\n\t\t/** Raw `Retry-After` header value (seconds or HTTP-date). */\n\t\treadonly retryAfter?: string,\n\t\tbody?: unknown,\n\t\tcode?: string,\n\t) {\n\t\tsuper(429, message, body, code, {\n\t\t\tretryable: true,\n\t\t\tretryAfterSeconds: parseRetryAfter(retryAfter),\n\t\t});\n\t\tthis.name = \"RateLimitError\";\n\t}\n}\n\n/** Thrown on a 4xx the caller can fix (bad cursor, bad params). Never retried.\n * `code` is the server's machine-readable code when the envelope carried one. */\nexport class ValidationError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown, code?: string) {\n\t\tsuper(status, message, body, code, { retryable: false });\n\t\tthis.name = \"ValidationError\";\n\t}\n}\n\n/** Thrown when an archive manifest signature is missing or does not verify. */\nexport class ArchiveSignatureError extends SecondLayerError {\n\tconstructor(message = \"Archive manifest signature is missing or invalid.\") {\n\t\tsuper(message, { code: \"ARCHIVE_SIGNATURE\", retryable: false });\n\t\tthis.name = \"ArchiveSignatureError\";\n\t}\n}\n\n/** Thrown on a 401 from the archive ops host (quote/fetch/credits). */\nexport class ArchiveAuthError extends SecondLayerError {\n\tconstructor(message = \"Archive ops request was not authenticated.\") {\n\t\tsuper(message, { code: \"ARCHIVE_AUTH\", retryable: false });\n\t\tthis.name = \"ArchiveAuthError\";\n\t}\n}\n\n/** Thrown on a 402 from archive fetch — prepaid credits do not cover the quote. */\nexport class InsufficientArchiveCreditsError extends SecondLayerError {\n\tshortfallUsdMicros?: number;\n\tconstructor(\n\t\tmessage = \"Insufficient archive credits.\",\n\t\tshortfallUsdMicros?: number,\n\t) {\n\t\tsuper(message, {\n\t\t\tcode: \"INSUFFICIENT_ARCHIVE_CREDITS\",\n\t\t\tretryable: false,\n\t\t});\n\t\tthis.name = \"InsufficientArchiveCreditsError\";\n\t\tthis.shortfallUsdMicros = shortfallUsdMicros;\n\t}\n}\n\n/** Thrown on a 503 when the archive fetch gate is unconfigured. */\nexport class ArchiveGateNotConfiguredError extends SecondLayerError {\n\tconstructor(message = \"The archive gate is not configured on the server.\") {\n\t\tsuper(message, { code: \"ARCHIVE_GATE_NOT_CONFIGURED\", retryable: false });\n\t\tthis.name = \"ArchiveGateNotConfiguredError\";\n\t}\n}\n\n/** Parse a `Retry-After` header: delta-seconds or an HTTP-date. */\nexport function parseRetryAfter(value?: string | null): number | undefined {\n\tif (!value) return undefined;\n\tconst seconds = Number(value);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds;\n\tconst date = Date.parse(value);\n\tif (!Number.isNaN(date)) return Math.max(0, (date - Date.now()) / 1000);\n\treturn undefined;\n}\n",
|
|
7
|
-
"import {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tparseRetryAfter,\n} from \"./errors.ts\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport interface SecondLayerOptions {\n\t/** Base URL of the instance API (trailing slashes are stripped). */\n\tbaseUrl: string;\n\t/** Bearer token for authenticated instance requests (`INSTANCE_TOKEN`). */\n\tapiKey?: string;\n\t/** Hosted account key (`sk-sl_*`). Env `SECONDLAYER_API_KEY`. Used by\n\t * `sl.archive` quote/fetch/credits, never by instance `/v1` or `/api`. */\n\taccountKey?: string;\n\t/** Fetch implementation. Tests and edge runtimes can provide their own. */\n\tfetchImpl?: FetchLike;\n\t/** Public base URL for Streams bulk parquet dumps (the cold backfill plane).\n\t * Required for `streams.dumps.*`; without it the dumps client falls back to\n\t * its built-in default. */\n\tdumpsBaseUrl?: string;\n\t/** Public base URL for the signed canonical archive tree. Defaults to\n\t * `https://archive.secondlayer.tools`. Reaches `sl.archive`. */\n\tarchiveBaseUrl?: string;\n\t/** Credits and fetch-gate API. Defaults to `https://api.secondlayer.tools`,\n\t * not `baseUrl`. Reaches `sl.archive` quote/fetch/credits. */\n\tarchiveOpsUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\t/** Check the ed25519 signature on every Streams read. Omit for lenient\n\t * (verify when signed, pass through unsigned self-host responses), `true`\n\t * or `{ publicKey }` for strict, `false` for off. Reaches `sl.streams`. */\n\tverify?: boolean | { publicKey: string };\n\t/** Check the dumps manifest signature before trusting any file hash\n\t * (default on). Reaches `sl.streams.dumps`. */\n\tverifyDumpsManifest?: boolean;\n\t/** How long one request may take, headers and body, before it fails with a\n\t * retryable `ApiError` (default 30 000 ms). A hung socket then trips the\n\t * retry policy instead of stalling a walk or consume loop forever. `0`\n\t * disables the timeout. */\n\trequestTimeoutMs?: number;\n}\n\n/** Default per-request budget. Long enough for a 1000-row filtered page on a\n * cold cache, short enough that a half-open connection surfaces as a retry. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** Per-call options every `request*` method accepts. */\nexport type RequestOptions = {\n\t/** Cancels the in-flight request (and its body read). The rejection is the\n\t * signal's reason, an `AbortError` by default, never an `ApiError`. */\n\tsignal?: AbortSignal;\n};\n\n/** The rejection a caller abort produces when the signal carries no reason. */\nexport function abortError(): Error {\n\treturn new DOMException(\"This operation was aborted\", \"AbortError\");\n}\n\n/** Reject as soon as `signal` aborts, even when `promise` is a fetch\n * implementation that ignores its `signal` argument. */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) return Promise.reject(signal.reason ?? abortError());\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason ?? abortError());\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t});\n\t});\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or\n * `SECONDLAYER_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\n/** Instance credential. `secondlayer init` writes this. */\nexport const INSTANCE_TOKEN_ENV = \"INSTANCE_TOKEN\";\n\n/** Hosted account key (`sk-sl_*`) for api.secondlayer.tools. */\nexport const ACCOUNT_KEY_ENV = \"SECONDLAYER_API_KEY\";\n\nlet warnedUrlAlias = false;\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst primary = process.env?.SECONDLAYER_API_URL || undefined;\n\t\tif (primary) return primary.replace(/\\/+$/, \"\");\n\t\tconst legacy = process.env?.SL_API_URL || undefined;\n\t\tif (legacy) {\n\t\t\tif (!warnedUrlAlias) {\n\t\t\t\twarnedUrlAlias = true;\n\t\t\t\tconsole.warn(\n\t\t\t\t\t\"[secondlayer] SL_API_URL is a legacy alias of SECONDLAYER_API_URL; using the alias this once.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn legacy.replace(/\\/+$/, \"\");\n\t\t}\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Resolve the instance credential. Precedence: explicit `apiKey` (including\n * `\"\"` for keyless) → `INSTANCE_TOKEN`. Does not read the hosted account key\n * env vars. Guarded for browsers and edge runtimes. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst token = process.env?.INSTANCE_TOKEN || undefined;\n\treturn token;\n}\n\nlet warnedArchiveAlias = false;\n\n/** Resolve the hosted account key for archive quote/fetch/credits.\n * Precedence: explicit `accountKey` → `SECONDLAYER_API_KEY` → `SL_API_KEY` /\n * `SL_ARCHIVE_API_KEY` (one-release warn-fallbacks). Does not read\n * `INSTANCE_TOKEN`. */\nexport function resolveAccountKey(accountKey?: string): string | undefined {\n\tif (accountKey !== undefined) return accountKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst primary = process.env?.SECONDLAYER_API_KEY || undefined;\n\tconst slAlias = process.env?.SL_API_KEY || undefined;\n\tconst archiveAlias = process.env?.SL_ARCHIVE_API_KEY || undefined;\n\tif (primary) return primary;\n\tconst legacy = slAlias ?? archiveAlias;\n\tif (legacy) {\n\t\tif (!warnedArchiveAlias) {\n\t\t\twarnedArchiveAlias = true;\n\t\t\tconsole.warn(\n\t\t\t\t\"[secondlayer] SL_API_KEY / SL_ARCHIVE_API_KEY are legacy aliases of SECONDLAYER_API_KEY; using the alias this once.\",\n\t\t\t);\n\t\t}\n\t\treturn legacy;\n\t}\n\treturn undefined;\n}\n\n/** Percent-encode one URL path segment. Every caller-supplied identifier\n * (subgraph name, table, subscription id) goes through this before it is\n * interpolated into a path, so `..`, `/`, `?` and `#` in an id cannot\n * retarget the authenticated request at a different route. */\nexport function seg(value: string | number): string {\n\treturn encodeURIComponent(String(value));\n}\n\n/** Build a query-string suffix from name→value pairs. Skips null/undefined and\n * empty values; arrays are comma-joined. Returns \"\" (never a dangling \"?\") or\n * \"?a=1&b=2\" — the one canonical builder every list endpoint shares, so the\n * empty-query guard can't be forgotten per call site. */\nexport function buildQuery(\n\tparams: Record<\n\t\tstring,\n\t\tnumber | string | boolean | readonly string[] | null | undefined\n\t>,\n): string {\n\tconst search = new URLSearchParams();\n\tfor (const [name, value] of Object.entries(params)) {\n\t\tif (value === undefined || value === null) continue;\n\t\tconst serialized = Array.isArray(value) ? value.join(\",\") : String(value);\n\t\tif (serialized.length === 0) continue;\n\t\tsearch.set(name, serialized);\n\t}\n\tconst query = search.toString();\n\treturn query ? `?${query}` : \"\";\n}\n\n/** Pull the message and code out of an API error body. The API answers every\n * failure with `{error, code}`; a proxy in front of it may answer with plain\n * text or nothing, so the body is kept whichever shape it took and the\n * message is left undefined when there is none worth surfacing. */\nexport function parseErrorEnvelope(text: string): {\n\tmessage?: string;\n\tcode?: string;\n\tbody: unknown;\n} {\n\tif (text.length === 0) return { body: undefined };\n\ttry {\n\t\tconst json = JSON.parse(text);\n\t\tlet message: string | undefined;\n\t\tlet code: string | undefined;\n\t\tif (json && typeof json === \"object\") {\n\t\t\tconst err = json.error ?? json.message;\n\t\t\tif (typeof err === \"string\" && err.length > 0) message = err;\n\t\t\telse if (err && typeof err === \"object\") message = JSON.stringify(err);\n\t\t\tif (typeof json.code === \"string\") code = json.code;\n\t\t}\n\t\treturn { message, code, body: json };\n\t} catch {\n\t\treturn { message: text, body: text };\n\t}\n}\n\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\n\tprotected requestTimeoutMs: number;\n\n\tconstructor(options: Partial<SecondLayerOptions> = {}) {\n\t\tthis.baseUrl = resolveBaseUrl(options.baseUrl);\n\t\tthis.apiKey = resolveApiKey(options.apiKey);\n\t\tthis.origin = options.origin ?? \"cli\";\n\t\tthis.requestTimeoutMs =\n\t\t\toptions.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n\t\t// Bind the global so a bare `fetch` reference doesn't lose its Request\n\t\t// context on runtimes where fetch is a method (workerd, older Node).\n\t\tthis.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));\n\t}\n\n\tstatic authHeaders(apiKey?: string): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t};\n\t\tif (apiKey) {\n\t\t\theaders.Authorization = `Bearer ${apiKey}`;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprotected async request<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\tif (response.status === 204) {\n\t\t\t\treturn undefined as T;\n\t\t\t}\n\t\t\treturn (await raceAbort(response.json(), signal)) as T;\n\t\t});\n\t}\n\n\t/** Like `request`, but maps a 404 to `null` instead of throwing — the one\n\t * place that owns the \"absent resource\" rule for `get*` accessors. */\n\tprotected async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body, opts);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.status === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprotected async requestText(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<string> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\treturn raceAbort(response.text(), signal);\n\t\t});\n\t}\n\n\t/** Run one request under the caller's signal plus the per-request timeout.\n\t * One combined signal covers the fetch and the body read, so a socket that\n\t * stalls mid-body times out the same way one that never answers does. A\n\t * timeout rejects with a retryable `ApiError`; a caller abort rejects with\n\t * the signal's reason so loops can tell \"stop\" from \"try again\". */\n\tprivate async withRequestBudget<T>(\n\t\tcallerSignal: AbortSignal | undefined,\n\t\trun: (signal: AbortSignal) => Promise<T>,\n\t): Promise<T> {\n\t\tconst controller = new AbortController();\n\t\tlet timedOut = false;\n\t\tconst forward = () =>\n\t\t\tcontroller.abort(callerSignal?.reason ?? abortError());\n\t\tif (callerSignal?.aborted) forward();\n\t\telse callerSignal?.addEventListener(\"abort\", forward, { once: true });\n\t\tconst timer =\n\t\t\tthis.requestTimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tcontroller.abort(abortError());\n\t\t\t\t\t}, this.requestTimeoutMs)\n\t\t\t\t: undefined;\n\t\ttry {\n\t\t\treturn await run(controller.signal);\n\t\t} catch (err) {\n\t\t\tif (timedOut && !callerSignal?.aborted) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`No response from ${this.baseUrl} within ${this.requestTimeoutMs}ms. Retryable. Raise requestTimeoutMs for slow filtered reads.`,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"REQUEST_TIMEOUT\",\n\t\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tcallerSignal?.removeEventListener(\"abort\", forward);\n\t\t}\n\t}\n\n\t/** Issue the HTTP request and map non-2xx statuses onto the error family.\n\t * `signal` is the combined caller-plus-timeout signal from `request*`;\n\t * subclasses that stream a body call this directly and read it themselves. */\n\tprotected async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\tsignal?: AbortSignal,\n\t): 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\tconst pending = this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tresponse = signal ? await raceAbort(pending, signal) : await pending;\n\t\t} catch (err) {\n\t\t\t// An abort (caller or timeout) is not a network failure; let the\n\t\t\t// budget wrapper decide what it means.\n\t\t\tif (signal?.aborted) throw err;\n\t\t\tthrow new ApiError(\n\t\t\t\t0,\n\t\t\t\t`Cannot reach API at ${this.baseUrl}. Check your connection or try again.`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\t// Read the envelope once for every failure status. The API answers\n\t\t\t// 401 and 503 with `{error, code}` too (a revoked token, an index\n\t\t\t// still catching up), and that code is what a caller branches on.\n\t\t\tconst errorBody = signal\n\t\t\t\t? await raceAbort(response.text(), signal)\n\t\t\t\t: await response.text();\n\t\t\tconst envelope = parseErrorEnvelope(errorBody);\n\t\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError(\n\t\t\t\t\tenvelope.message ?? \"API key invalid or expired.\",\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status === 429) {\n\t\t\t\t// The header is preserved as `retryAfterSeconds` (not just prose) so\n\t\t\t\t// the consume loops can honor it.\n\t\t\t\tconst fallback = retryAfter\n\t\t\t\t\t? `Rate limited. Wait ${retryAfter} seconds.`\n\t\t\t\t\t: \"Rate limited. Try again later.\";\n\t\t\t\tthrow new RateLimitError(\n\t\t\t\t\tenvelope.message ?? fallback,\n\t\t\t\t\tretryAfter,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tconst retryAfterSeconds = parseRetryAfter(retryAfter);\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\tenvelope.message ??\n\t\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t\tretryAfterSeconds !== undefined ? { retryAfterSeconds } : {},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new ApiError(\n\t\t\t\tresponse.status,\n\t\t\t\tenvelope.message ?? `HTTP ${response.status}`,\n\t\t\t\tenvelope.body,\n\t\t\t\tenvelope.code,\n\t\t\t);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
|
|
7
|
+
"import {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tparseRetryAfter,\n} from \"./errors.ts\";\n\nexport type FetchLike = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\n\nexport interface SecondLayerOptions {\n\t/** Base URL of the instance API (trailing slashes are stripped). */\n\tbaseUrl: string;\n\t/** Bearer token for authenticated instance requests (`INSTANCE_TOKEN`). */\n\tapiKey?: string;\n\t/** Hosted account key (`sk-sl_*`). Env `SECONDLAYER_API_KEY`. Used by\n\t * `sl.archive` quote/fetch/credits, never by instance `/v1` or `/api`. */\n\taccountKey?: string;\n\t/** Fetch implementation. Tests and edge runtimes can provide their own. */\n\tfetchImpl?: FetchLike;\n\t/** Public base URL for Streams bulk parquet dumps (the cold backfill plane).\n\t * Required for `streams.dumps.*`; without it the dumps client falls back to\n\t * its built-in default. */\n\tdumpsBaseUrl?: string;\n\t/** Public base URL for the signed canonical archive tree. Defaults to\n\t * `https://archive.secondlayer.tools`. Reaches `sl.archive`. */\n\tarchiveBaseUrl?: string;\n\t/** Credits and fetch-gate API. Defaults to `https://api.secondlayer.tools`,\n\t * not `baseUrl`. Reaches `sl.archive` quote/fetch/credits. */\n\tarchiveOpsUrl?: string;\n\t/** Deploy origin label sent as `x-sl-origin` (telemetry). Defaults to `cli`. */\n\torigin?: \"cli\" | \"mcp\" | \"session\";\n\t/** Check the ed25519 signature on every Streams read. Omit for lenient\n\t * (verify when signed, pass through unsigned self-host responses), `true`\n\t * or `{ publicKey }` for strict, `false` for off. Reaches `sl.streams`. */\n\tverify?: boolean | { publicKey: string };\n\t/** Check the dumps manifest signature before trusting any file hash\n\t * (default on). Reaches `sl.streams.dumps`. */\n\tverifyDumpsManifest?: boolean;\n\t/** How long one request may take, headers and body, before it fails with a\n\t * retryable `ApiError` (default 30 000 ms). A hung socket then trips the\n\t * retry policy instead of stalling a walk or consume loop forever. `0`\n\t * disables the timeout. */\n\trequestTimeoutMs?: number;\n}\n\n/** Default per-request budget. Long enough for a 1000-row filtered page on a\n * cold cache, short enough that a half-open connection surfaces as a retry. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** Per-call options every `request*` method accepts. */\nexport type RequestOptions = {\n\t/** Cancels the in-flight request (and its body read). The rejection is the\n\t * signal's reason, an `AbortError` by default, never an `ApiError`. */\n\tsignal?: AbortSignal;\n};\n\n/** The rejection a caller abort produces when the signal carries no reason. */\nexport function abortError(): Error {\n\treturn new DOMException(\"This operation was aborted\", \"AbortError\");\n}\n\n/** Reject as soon as `signal` aborts, even when `promise` is a fetch\n * implementation that ignores its `signal` argument. */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) return Promise.reject(signal.reason ?? abortError());\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason ?? abortError());\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t});\n\t});\n}\n\n/** Product default: the local one-box API. Override with `baseUrl` or\n * `SECONDLAYER_API_URL`. */\nexport const LOCAL_API_URL = \"http://127.0.0.1:3800\";\n\n/** Instance credential. `secondlayer init` writes this. */\nexport const INSTANCE_TOKEN_ENV = \"INSTANCE_TOKEN\";\n\n/** Hosted account key (`sk-sl_*`) for api.secondlayer.tools. */\nexport const ACCOUNT_KEY_ENV = \"SECONDLAYER_API_KEY\";\n\nlet warnedUrlAlias = false;\n\nexport function resolveBaseUrl(explicit?: string): string {\n\tif (explicit && explicit.length > 0) return explicit.replace(/\\/+$/, \"\");\n\tif (typeof process !== \"undefined\") {\n\t\tconst primary = process.env?.SECONDLAYER_API_URL || undefined;\n\t\tif (primary) return primary.replace(/\\/+$/, \"\");\n\t\tconst legacy = process.env?.SL_API_URL || undefined;\n\t\tif (legacy) {\n\t\t\tif (!warnedUrlAlias) {\n\t\t\t\twarnedUrlAlias = true;\n\t\t\t\tconsole.warn(\n\t\t\t\t\t\"[secondlayer] SL_API_URL is a legacy alias of SECONDLAYER_API_URL; using the alias this once.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn legacy.replace(/\\/+$/, \"\");\n\t\t}\n\t}\n\treturn LOCAL_API_URL;\n}\n\n/** Resolve the instance credential. Precedence: explicit `apiKey` (including\n * `\"\"` for keyless) → `INSTANCE_TOKEN`. Does not read the hosted account key\n * env vars. Guarded for browsers and edge runtimes. */\nexport function resolveApiKey(apiKey?: string): string | undefined {\n\tif (apiKey !== undefined) return apiKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst token = process.env?.INSTANCE_TOKEN || undefined;\n\treturn token;\n}\n\nlet warnedArchiveAlias = false;\n\n/** Resolve the hosted account key for archive quote/fetch/credits.\n * Precedence: explicit `accountKey` → `SECONDLAYER_API_KEY` → `SL_API_KEY` /\n * `SL_ARCHIVE_API_KEY` (one-release warn-fallbacks). Does not read\n * `INSTANCE_TOKEN`. */\nexport function resolveAccountKey(accountKey?: string): string | undefined {\n\tif (accountKey !== undefined) return accountKey;\n\tif (typeof process === \"undefined\") return undefined;\n\tconst primary = process.env?.SECONDLAYER_API_KEY || undefined;\n\tconst slAlias = process.env?.SL_API_KEY || undefined;\n\tconst archiveAlias = process.env?.SL_ARCHIVE_API_KEY || undefined;\n\tif (primary) return primary;\n\tconst legacy = slAlias ?? archiveAlias;\n\tif (legacy) {\n\t\tif (!warnedArchiveAlias) {\n\t\t\twarnedArchiveAlias = true;\n\t\t\tconsole.warn(\n\t\t\t\t\"[secondlayer] SL_API_KEY / SL_ARCHIVE_API_KEY are legacy aliases of SECONDLAYER_API_KEY; using the alias this once.\",\n\t\t\t);\n\t\t}\n\t\treturn legacy;\n\t}\n\treturn undefined;\n}\n\n/** Percent-encode one URL path segment. Every caller-supplied identifier\n * (subgraph name, table, webhook id) goes through this before it is\n * interpolated into a path, so `..`, `/`, `?` and `#` in an id cannot\n * retarget the authenticated request at a different route. */\nexport function seg(value: string | number): string {\n\treturn encodeURIComponent(String(value));\n}\n\n/** Build a query-string suffix from name→value pairs. Skips null/undefined and\n * empty values; arrays are comma-joined. Returns \"\" (never a dangling \"?\") or\n * \"?a=1&b=2\" — the one canonical builder every list endpoint shares, so the\n * empty-query guard can't be forgotten per call site. */\nexport function buildQuery(\n\tparams: Record<\n\t\tstring,\n\t\tnumber | string | boolean | readonly string[] | null | undefined\n\t>,\n): string {\n\tconst search = new URLSearchParams();\n\tfor (const [name, value] of Object.entries(params)) {\n\t\tif (value === undefined || value === null) continue;\n\t\tconst serialized = Array.isArray(value) ? value.join(\",\") : String(value);\n\t\tif (serialized.length === 0) continue;\n\t\tsearch.set(name, serialized);\n\t}\n\tconst query = search.toString();\n\treturn query ? `?${query}` : \"\";\n}\n\n/** Pull the message and code out of an API error body. The API answers every\n * failure with `{error, code}`; a proxy in front of it may answer with plain\n * text or nothing, so the body is kept whichever shape it took and the\n * message is left undefined when there is none worth surfacing. */\nexport function parseErrorEnvelope(text: string): {\n\tmessage?: string;\n\tcode?: string;\n\tbody: unknown;\n} {\n\tif (text.length === 0) return { body: undefined };\n\ttry {\n\t\tconst json = JSON.parse(text);\n\t\tlet message: string | undefined;\n\t\tlet code: string | undefined;\n\t\tif (json && typeof json === \"object\") {\n\t\t\tconst err = json.error ?? json.message;\n\t\t\tif (typeof err === \"string\" && err.length > 0) message = err;\n\t\t\telse if (err && typeof err === \"object\") message = JSON.stringify(err);\n\t\t\tif (typeof json.code === \"string\") code = json.code;\n\t\t}\n\t\treturn { message, code, body: json };\n\t} catch {\n\t\treturn { message: text, body: text };\n\t}\n}\n\nexport abstract class BaseClient {\n\tprotected baseUrl: string;\n\tprotected apiKey?: string;\n\tprotected origin: \"cli\" | \"mcp\" | \"session\";\n\tprotected fetchImpl: FetchLike;\n\tprotected requestTimeoutMs: number;\n\n\tconstructor(options: Partial<SecondLayerOptions> = {}) {\n\t\tthis.baseUrl = resolveBaseUrl(options.baseUrl);\n\t\tthis.apiKey = resolveApiKey(options.apiKey);\n\t\tthis.origin = options.origin ?? \"cli\";\n\t\tthis.requestTimeoutMs =\n\t\t\toptions.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n\t\t// Bind the global so a bare `fetch` reference doesn't lose its Request\n\t\t// context on runtimes where fetch is a method (workerd, older Node).\n\t\tthis.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));\n\t}\n\n\tstatic authHeaders(apiKey?: string): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t};\n\t\tif (apiKey) {\n\t\t\theaders.Authorization = `Bearer ${apiKey}`;\n\t\t}\n\t\treturn headers;\n\t}\n\n\tprotected async request<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\tif (response.status === 204) {\n\t\t\t\treturn undefined as T;\n\t\t\t}\n\t\t\treturn (await raceAbort(response.json(), signal)) as T;\n\t\t});\n\t}\n\n\t/** Like `request`, but maps a 404 to `null` instead of throwing — the one\n\t * place that owns the \"absent resource\" rule for `get*` accessors. */\n\tprotected async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, body, opts);\n\t\t} catch (err) {\n\t\t\tif (err instanceof ApiError && err.status === 404) return null;\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tprotected async requestText(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\topts: RequestOptions = {},\n\t): Promise<string> {\n\t\treturn this.withRequestBudget(opts.signal, async (signal) => {\n\t\t\tconst response = await this.fetchResponse(method, path, body, signal);\n\t\t\treturn raceAbort(response.text(), signal);\n\t\t});\n\t}\n\n\t/** Run one request under the caller's signal plus the per-request timeout.\n\t * One combined signal covers the fetch and the body read, so a socket that\n\t * stalls mid-body times out the same way one that never answers does. A\n\t * timeout rejects with a retryable `ApiError`; a caller abort rejects with\n\t * the signal's reason so loops can tell \"stop\" from \"try again\". */\n\tprivate async withRequestBudget<T>(\n\t\tcallerSignal: AbortSignal | undefined,\n\t\trun: (signal: AbortSignal) => Promise<T>,\n\t): Promise<T> {\n\t\tconst controller = new AbortController();\n\t\tlet timedOut = false;\n\t\tconst forward = () =>\n\t\t\tcontroller.abort(callerSignal?.reason ?? abortError());\n\t\tif (callerSignal?.aborted) forward();\n\t\telse callerSignal?.addEventListener(\"abort\", forward, { once: true });\n\t\tconst timer =\n\t\t\tthis.requestTimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tcontroller.abort(abortError());\n\t\t\t\t\t}, this.requestTimeoutMs)\n\t\t\t\t: undefined;\n\t\ttry {\n\t\t\treturn await run(controller.signal);\n\t\t} catch (err) {\n\t\t\tif (timedOut && !callerSignal?.aborted) {\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\t0,\n\t\t\t\t\t`No response from ${this.baseUrl} within ${this.requestTimeoutMs}ms. Retryable. Raise requestTimeoutMs for slow filtered reads.`,\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"REQUEST_TIMEOUT\",\n\t\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\tcallerSignal?.removeEventListener(\"abort\", forward);\n\t\t}\n\t}\n\n\t/** Issue the HTTP request and map non-2xx statuses onto the error family.\n\t * `signal` is the combined caller-plus-timeout signal from `request*`;\n\t * subclasses that stream a body call this directly and read it themselves. */\n\tprotected async fetchResponse(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\tsignal?: AbortSignal,\n\t): 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\tconst pending = this.fetchImpl(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: serializedBody,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tresponse = signal ? await raceAbort(pending, signal) : await pending;\n\t\t} catch (err) {\n\t\t\t// An abort (caller or timeout) is not a network failure; let the\n\t\t\t// budget wrapper decide what it means.\n\t\t\tif (signal?.aborted) throw err;\n\t\t\tthrow new ApiError(\n\t\t\t\t0,\n\t\t\t\t`Cannot reach API at ${this.baseUrl}. Check your connection or try again.`,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t{ retryable: true, cause: err instanceof Error ? err : undefined },\n\t\t\t);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\t// Read the envelope once for every failure status. The API answers\n\t\t\t// 401 and 503 with `{error, code}` too (a revoked token, an index\n\t\t\t// still catching up), and that code is what a caller branches on.\n\t\t\tconst errorBody = signal\n\t\t\t\t? await raceAbort(response.text(), signal)\n\t\t\t\t: await response.text();\n\t\t\tconst envelope = parseErrorEnvelope(errorBody);\n\t\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\n\t\t\tif (response.status === 401) {\n\t\t\t\tthrow new AuthError(\n\t\t\t\t\tenvelope.message ?? \"API key invalid or expired.\",\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status === 429) {\n\t\t\t\t// The header is preserved as `retryAfterSeconds` (not just prose) so\n\t\t\t\t// the consume loops can honor it.\n\t\t\t\tconst fallback = retryAfter\n\t\t\t\t\t? `Rate limited. Wait ${retryAfter} seconds.`\n\t\t\t\t\t: \"Rate limited. Try again later.\";\n\t\t\t\tthrow new RateLimitError(\n\t\t\t\t\tenvelope.message ?? fallback,\n\t\t\t\t\tretryAfter,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tconst retryAfterSeconds = parseRetryAfter(retryAfter);\n\t\t\t\tthrow new ApiError(\n\t\t\t\t\tresponse.status,\n\t\t\t\t\tenvelope.message ??\n\t\t\t\t\t\t`Server error. Try again or check status at ${this.baseUrl}/health`,\n\t\t\t\t\tenvelope.body,\n\t\t\t\t\tenvelope.code,\n\t\t\t\t\tretryAfterSeconds !== undefined ? { retryAfterSeconds } : {},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new ApiError(\n\t\t\t\tresponse.status,\n\t\t\t\tenvelope.message ?? `HTTP ${response.status}`,\n\t\t\t\tenvelope.body,\n\t\t\t\tenvelope.code,\n\t\t\t);\n\t\t}\n\n\t\treturn response;\n\t}\n}\n",
|
|
8
8
|
"import {\n\tblockEndCursor,\n\tdecodeStreamsCursor,\n\tencodeStreamsCursor,\n} from \"@secondlayer/shared\";\nimport { ValidationError } from \"./errors.ts\";\n\n/**\n * Helpers for Streams cursors. A cursor is the opaque `<block>:<index>` string\n * that marks a position in the event stream; treat the format as an\n * implementation detail and go through these helpers instead of string-building\n * it at call sites. Encode/decode and the rewind sentinel come from the\n * canonical codec in `@secondlayer/shared` so the SDK cannot accept a spelling\n * the server would 400, or rewind to a different foot than Index/Streams.\n */\nexport const Cursor = {\n\t/**\n\t * Cursor at the foot of `height` — a position that sorts strictly below the\n\t * first event of block `height` (`height:0`) and strictly above every event\n\t * of block `height - 1`. Cursors are exclusive (`(bh,ei) > after`), so\n\t * resuming from it re-reads the entire canonical run starting at `height:0`\n\t * inclusive. This is the position to rewind to after a reorg whose fork point\n\t * is `height`: the new canonical block at `height` carries a fresh first\n\t * event at `(height, 0)` that the consumer MUST re-read.\n\t *\n\t * Encoded as `blockEndCursor(height - 1)` rather than the seemingly-natural\n\t * `${height}:0` — that earlier form was an off-by-one: being exclusive, it\n\t * skipped `(height, 0)`, silently dropping the fork block's first row on\n\t * every reorg. The sentinel is int4 max (the `event_index`/`tx_index` column\n\t * type), larger than any real index, so nothing at `height - 1` survives the\n\t * keyset and the next returned row is exactly `(height, 0)`.\n\t *\n\t * `atHeight(0)` is `null`: the pre-genesis position both consume loops\n\t * accept as \"read everything from the first event\". There is no string\n\t * cursor below `0:0`, and `0:0` itself is exclusive, so returning it here\n\t * skipped the genesis event.\n\t */\n\tatHeight(height: number): string | null {\n\t\tif (height <= 0) return null;\n\t\treturn encodeStreamsCursor(blockEndCursor(height - 1));\n\t},\n\n\t/** Parse a `<block>:<index>` cursor. Throws `ValidationError` if malformed. */\n\tparse(cursor: string): { blockHeight: number; eventIndex: number } {\n\t\ttry {\n\t\t\tconst decoded = decodeStreamsCursor(cursor);\n\t\t\treturn {\n\t\t\t\tblockHeight: decoded.block_height,\n\t\t\t\teventIndex: decoded.event_index,\n\t\t\t};\n\t\t} catch {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`Invalid stream cursor \"${cursor}\"; expected \"<block>:<index>\" (e.g. \"951475:3\").`,\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t},\n};\n",
|
|
9
9
|
"// AuthError / RateLimitError / ValidationError are shared across the whole SDK\n// (Index and the platform clients throw them too) and live in ../errors.ts —\n// re-exported here so `@secondlayer/sdk/streams` imports keep working.\nimport { parseErrorEnvelope } from \"../base.ts\";\nimport {\n\tApiError,\n\tAuthError,\n\tRateLimitError,\n\tSecondLayerError,\n\tValidationError,\n} from \"../errors.ts\";\n\nexport { AuthError, RateLimitError, ValidationError } from \"../errors.ts\";\n\n/** Thrown on a 5xx from the Streams API, and on a failed signing-key fetch.\n * `retryable`: the page retry policy tries again. */\nexport class StreamsServerError extends ApiError {\n\tconstructor(message: string, status: number, body?: unknown, code?: string) {\n\t\tsuper(status, message, body, code, { retryable: true });\n\t\tthis.name = \"StreamsServerError\";\n\t}\n}\n\n/** Thrown when response signature verification is enabled and fails. */\nexport class StreamsSignatureError extends SecondLayerError {\n\tconstructor(message = \"Streams response signature verification failed.\") {\n\t\tsuper(message);\n\t\tthis.name = \"StreamsSignatureError\";\n\t}\n}\n\n/** Map a non-OK Streams response onto the SDK error family. The server's\n * `{error, code}` envelope survives on `message`/`code`/`body`, the same way\n * it does on Index reads, so `err.code === \"CURSOR_INVALID\"` branches the\n * same whichever client raised it. */\nexport async function mapStreamsError(response: Response): Promise<never> {\n\tconst { message, code, body } = parseErrorEnvelope(await response.text());\n\n\tif (response.status === 401) {\n\t\tthrow new AuthError(message ?? \"API key invalid or expired.\", body, code);\n\t}\n\n\tif (response.status === 429) {\n\t\tconst retryAfter = response.headers.get(\"Retry-After\") ?? undefined;\n\t\tthrow new RateLimitError(\n\t\t\tmessage ?? \"Rate limited. Try again later.\",\n\t\t\tretryAfter,\n\t\t\tbody,\n\t\t\tcode,\n\t\t);\n\t}\n\n\tif (response.status >= 500) {\n\t\tthrow new StreamsServerError(\n\t\t\tmessage ?? `Streams server returned ${response.status}.`,\n\t\t\tresponse.status,\n\t\t\tbody,\n\t\t\tcode,\n\t\t);\n\t}\n\n\tthrow new ValidationError(\n\t\tmessage ?? `Streams request returned ${response.status}.`,\n\t\tresponse.status,\n\t\tbody,\n\t\tcode,\n\t);\n}\n",
|
|
10
10
|
"import type { ConsumerSink, WithSinkTx } from \"../sinks/types.ts\";\nimport { Cursor } from \"./cursor.ts\";\nimport { ValidationError } from \"./errors.ts\";\nimport type {\n\tConsumerBatchContext,\n\tStreamsBatch,\n\tStreamsEvent,\n\tStreamsEventType,\n\tStreamsEventsEnvelope,\n\tStreamsFilterMap,\n\tStreamsFilterValue,\n\tStreamsReorg,\n\tStreamsReorgsListEnvelope,\n} from \"./types.ts\";\n\n/** Stable identity of a reorg, for in-memory dedup across re-reported pages. */\nfunction reorgKey(reorg: StreamsReorg): string {\n\treturn `${reorg.detected_at}|${reorg.fork_point_height}|${reorg.new_canonical_tip}`;\n}\n\n/** Default ceiling on how far below the checkpoint one reorg may rewind. */\nexport const DEFAULT_MAX_ROLLBACK_DEPTH = 1000;\n\n/** What one call to {@link applyReorgs} did. `null` when nothing rewound. */\nexport type ReorgRewind = {\n\t/** Lowest fork point rolled back. */\n\tforkPoint: number;\n\t/** Cursor to resume from: the foot of `forkPoint`, or `null` (pre-genesis). */\n\tcursor: string | null;\n};\n\n/**\n * Apply a page's (or the reorg list's) reorgs against the consumer's position.\n * Shared by the Streams and Index loops so the two cannot drift on the one\n * rule that decides data loss: NEVER rewind forward.\n *\n * A reorg is only actionable when its fork point is at or below the height\n * the cursor has reached (`fork_point_height <= resumeHeight(cursor)`).\n * Servers attach every reorg whose orphaned span intersects the page span, so\n * a page read from below the fork carries a reorg the consumer has not\n * written past yet. Rewinding to it would move the cursor FORWARD and skip\n * every row between the checkpoint and the fork, durably once a sink commits\n * the rewound cursor. Those reorgs are marked handled and left alone: the\n * page itself is already the canonical chain.\n *\n * Every fresh reorg is validated BEFORE the sink sees any of them: the fork\n * point must be a non-negative safe integer, and the rewind may not reach\n * more than `maxRollbackDepth` blocks below the checkpoint unless the caller\n * raised the ceiling. `fork_point_height` drives a `DELETE ... >= fork` on\n * every declared table, so a malformed or hostile value is refused loudly\n * rather than executed.\n */\nexport async function applyReorgs<\n\tTReorg extends { fork_point_height: number },\n>(opts: {\n\treorgs: readonly TReorg[];\n\tcursor: string | null;\n\t/** In-memory dedup across re-reported pages; mutated. */\n\thandled: Set<string>;\n\tkeyOf: (reorg: TReorg) => string;\n\tsink?: Pick<ConsumerSink<unknown>, \"rollback\">;\n\tonReorg?: (\n\t\treorg: TReorg,\n\t\tctx: { cursor: string | null },\n\t) => Promise<void> | void;\n\tmaxRollbackDepth?: number;\n}): Promise<ReorgRewind | null> {\n\tconst fresh = opts.reorgs.filter(\n\t\t(reorg) => !opts.handled.has(opts.keyOf(reorg)),\n\t);\n\tif (fresh.length === 0) return null;\n\n\tfor (const reorg of fresh) {\n\t\tconst fork = reorg.fork_point_height;\n\t\tif (!Number.isSafeInteger(fork) || fork < 0) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`Reorg fork_point_height ${String(fork)} is not a non-negative integer. Rollback deletes every row at or above the fork from every declared table, so a malformed fork point is refused before the sink runs.`,\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst position = resumeHeight(opts.cursor);\n\tconst applicable = fresh\n\t\t.filter((reorg) => position !== null && reorg.fork_point_height <= position)\n\t\t.sort((a, b) => a.fork_point_height - b.fork_point_height);\n\t// Fork above the checkpoint: nothing at or past it has been written, and\n\t// the page being read is already the new chain. Remember it, do not move.\n\tfor (const reorg of fresh) {\n\t\tif (!applicable.includes(reorg)) opts.handled.add(opts.keyOf(reorg));\n\t}\n\tif (applicable.length === 0 || position === null) return null;\n\n\tconst forkPoint = applicable[0]?.fork_point_height ?? position;\n\tconst depth = position - forkPoint;\n\tconst maxDepth = opts.maxRollbackDepth ?? DEFAULT_MAX_ROLLBACK_DEPTH;\n\tif (depth > maxDepth) {\n\t\tthrow new ValidationError(\n\t\t\t`Reorg at fork ${forkPoint} rewinds ${depth} blocks below the checkpoint at height ${position}, past maxRollbackDepth (${maxDepth}). A rollback this deep deletes every row at or above the fork from every declared table. Confirm the source is trusted, then pass maxRollbackDepth: ${depth} or higher to allow it.`,\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst rewind = Cursor.atHeight(forkPoint);\n\tfor (const reorg of applicable) {\n\t\t// Sink first: rollback + rewound cursor commit atomically. A user\n\t\t// onReorg (if any) runs after, for observability.\n\t\tawait opts.sink?.rollback(reorg.fork_point_height, rewind);\n\t\tawait opts.onReorg?.(reorg, { cursor: rewind });\n\t\topts.handled.add(opts.keyOf(reorg));\n\t}\n\treturn { forkPoint, cursor: rewind };\n}\n\ntype StreamsEventsFetchParams = {\n\tcursor?: string | null;\n\tlimit: number;\n\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/** Sleep clamp for a server `Retry-After`: the loop honors the header up to\n * five minutes per attempt and keeps retrying within `retryCount`. It never\n * gives up early on a long Retry-After; the tradeoff is a long wait, not a\n * dropped loop. Set `retryCount: 0` to surface the 429 immediately instead. */\nconst MAX_RETRY_AFTER_MS = 300_000;\n\nfunction errRetryable(err: unknown): boolean {\n\t// SecondLayerError family carries an explicit signal; a bare TypeError is\n\t// the raw fetch network failure (Streams' fetchImpl isn't wrapped).\n\tif (err && typeof err === \"object\" && \"retryable\" in err) {\n\t\treturn (err as { retryable: unknown }).retryable === true;\n\t}\n\treturn err instanceof TypeError;\n}\n\nfunction errRetryAfterMs(err: unknown): number | undefined {\n\tif (err && typeof err === \"object\" && \"retryAfterSeconds\" in err) {\n\t\tconst seconds = (err as { retryAfterSeconds: unknown }).retryAfterSeconds;\n\t\tif (typeof seconds === \"number\" && Number.isFinite(seconds)) {\n\t\t\treturn Math.min(seconds * 1000, MAX_RETRY_AFTER_MS);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Run one page fetch with retries. Scoped to the FETCH only — never the loop\n * body: retrying after an `onReorg`/`onBatch` throw would re-enter with\n * `handledReorgs` partially mutated and skip a rollback silently. `onBatch`\n * and `onReorg` throws always propagate to the caller.\n */\nexport async function fetchPageWithRetry<T>(\n\tfetchPage: () => Promise<T>,\n\topts: PageRetryOptions & { sleep: Sleep; signal?: AbortSignal },\n): Promise<T> {\n\tconst retryCount = opts.retryCount ?? 3;\n\tconst retryDelay = opts.retryDelay ?? 1000;\n\tfor (let attempt = 0; ; attempt++) {\n\t\ttry {\n\t\t\treturn await fetchPage();\n\t\t} catch (err) {\n\t\t\tconst retriesLeft = retryCount - attempt;\n\t\t\tif (retriesLeft <= 0 || !errRetryable(err) || opts.signal?.aborted) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tconst delayMs = errRetryAfterMs(err) ?? retryDelay * (attempt + 1);\n\t\t\topts.onError?.(err, { attempt, retriesLeft, delayMs });\n\t\t\tawait opts.sleep(delayMs, opts.signal);\n\t\t\t// Aborted mid-sleep: surface the original failure, not a fresh fetch.\n\t\t\tif (opts.signal?.aborted) throw err;\n\t\t}\n\t}\n}\n\nexport async function defaultSleep(\n\tms: number,\n\tsignal?: AbortSignal,\n): Promise<void> {\n\tif (signal?.aborted) return;\n\n\tawait new Promise<void>((resolve) => {\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tresolve();\n\t\t};\n\t\t// Detach on the timer path too: a tail at the tip sleeps once per\n\t\t// empty poll, and each sleep that left its listener behind pinned a\n\t\t// closure on the caller's long-lived signal until the process exited.\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nexport async function consumeStreamsEvents<TTx = never>(opts: {\n\tfromCursor?: string | null;\n\tmode?: \"tail\" | \"bounded\";\n\tfinalizedOnly?: boolean;\n\tbatchSize: number;\n\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/** `GET /v1/streams/reorgs`, polled on idle (empty) pages so a reorg\n\t * that lands while the consumer sits at the tip is still rolled back.\n\t * Pages only carry reorgs overlapping their own span. */\n\tfetchReorgs?: (params: {\n\t\tsince: string;\n\t}) => Promise<StreamsReorgsListEnvelope>;\n\t/** Destination adapter owning checkpoint + rollback (see IndexConsumeOptions.sink). */\n\tsink?: ConsumerSink<TTx>;\n\t/** Fires once per page, before `onBatch` and any early return. */\n\tonProgress?: (ctx: ConsumerBatchContext) => void;\n\tonBatch: (\n\t\tevents: StreamsEvent[],\n\t\tenvelope: StreamsEventsEnvelope,\n\t\tctx: ConsumerBatchContext & WithSinkTx<TTx>,\n\t) =>\n\t\t| void\n\t\t| string\n\t\t| null\n\t\t| undefined\n\t\t| Promise<void>\n\t\t| Promise<string | null | undefined>;\n\tonReorg?: (\n\t\treorg: StreamsReorg,\n\t\tctx: { cursor: string | null },\n\t) => Promise<void> | void;\n\t/** Deepest rewind one reorg may make below the checkpoint. Default 1000. */\n\tmaxRollbackDepth?: number;\n\tsleep?: Sleep;\n\temptyBackoffMs?: number;\n\tmaxPages?: number;\n\tmaxEmptyPolls?: number;\n\tretryCount?: number;\n\tretryDelay?: number;\n\tonError?: PageRetryOptions[\"onError\"];\n\tsignal?: AbortSignal;\n}): Promise<{ cursor: string | null; pages: number; emptyPolls: number }> {\n\tconst sleep = opts.sleep ?? defaultSleep;\n\tconst mode = opts.mode ?? \"tail\";\n\tconst finalizedOnly = opts.finalizedOnly ?? false;\n\tconst emptyBackoffMs = opts.emptyBackoffMs ?? 500;\n\tconst maxPages = opts.maxPages ?? Number.POSITIVE_INFINITY;\n\tconst maxEmptyPolls = opts.maxEmptyPolls ?? Number.POSITIVE_INFINITY;\n\tassertSinkModeCompatible(opts.sink, finalizedOnly);\n\t// Resume order: explicit fromCursor, then the sink's committed checkpoint.\n\t// `loadCursor` is also the sink's INIT — it creates the checkpoint table and\n\t// validates the rollback precondition. Short-circuiting it on an explicit\n\t// `fromCursor` meant a replay-from-cursor run crashed on its first commit,\n\t// and skipped the height-column check that keeps reorg rollback from being\n\t// a silent no-op. Always initialize; `fromCursor` still wins as the resume\n\t// position.\n\tconst committedCursor = (await opts.sink?.loadCursor()) ?? null;\n\tlet cursor = opts.fromCursor ?? committedCursor;\n\t// In-memory only: rollback is idempotent, so a crash before the rewind is\n\t// re-detected and re-applied harmlessly on restart — no need to persist.\n\tconst handledReorgs = new Set<string>();\n\t// Resume token for the idle-tip reorg list; `null` until the first idle\n\t// poll with a checkpoint to seed it from.\n\tlet reorgSince: string | null = null;\n\tlet pages = 0;\n\tlet emptyPolls = 0;\n\t// Highest block reached, carried across empty pages so a caught-up tail\n\t// keeps reporting its position instead of dropping to null. Seeded from\n\t// the resume cursor: a restart into a quiet tail knows where it stands\n\t// before the first row lands.\n\tlet height: number | null = resumeHeight(cursor);\n\t// Highest block VERIFIED — how far the sweep is actually caught up, as\n\t// opposed to `height` (last delivered row). Starts at the resume position;\n\t// each page moves it (see below).\n\tlet scanned: number | null = height;\n\n\twhile (\n\t\tpages < maxPages &&\n\t\temptyPolls < maxEmptyPolls &&\n\t\t!opts.signal?.aborted\n\t) {\n\t\t// Retry wraps ONLY the page fetch: one transient 429/5xx must not kill\n\t\t// an hours-long backfill, and handler throws must never be re-entered.\n\t\tconst envelope = await fetchPageWithRetry(\n\t\t\t() =>\n\t\t\t\topts.fetchEvents({\n\t\t\t\t\tcursor,\n\t\t\t\t\tlimit: opts.batchSize,\n\t\t\t\t\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 at or below the checkpoint, then\n\t\t// rewind to the lowest fork point and re-read the now-canonical run.\n\t\t// Finalized data never reorgs, so `finalizedOnly` skips this entirely.\n\t\t// A sink makes rollback UNCONDITIONAL: omitting `onReorg` used to skip\n\t\t// reorgs silently.\n\t\tconst reorgsOn = !finalizedOnly && Boolean(opts.onReorg || opts.sink);\n\t\tif (reorgsOn) {\n\t\t\tconst rewound = await applyReorgs({\n\t\t\t\treorgs: envelope.reorgs,\n\t\t\t\tcursor,\n\t\t\t\thandled: handledReorgs,\n\t\t\t\tkeyOf: reorgKey,\n\t\t\t\tsink: opts.sink,\n\t\t\t\tonReorg: opts.onReorg,\n\t\t\t\tmaxRollbackDepth: opts.maxRollbackDepth,\n\t\t\t});\n\t\t\tif (rewound) {\n\t\t\t\tcursor = rewound.cursor;\n\t\t\t\t// Everything at and above the fork is no longer canonical, so the\n\t\t\t\t// reached height rolls back with it — including the verified\n\t\t\t\t// position: the new chain above the fork is unread.\n\t\t\t\theight = rewound.forkPoint > 0 ? rewound.forkPoint - 1 : null;\n\t\t\t\tscanned = height;\n\t\t\t\temptyPolls = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Idle tip: a page only reports reorgs overlapping its own span, so a\n\t\t// fork that lands while the consumer sits at the tip (orphaning rows\n\t\t// BELOW the next non-empty page) is never on a page. On an empty page\n\t\t// ask the reorg list instead: one extra request per idle poll. Seeded\n\t\t// from the checkpoint cursor (the API reads a cursor as \"reorgs that\n\t\t// orphaned anything at or above this position\"), then advanced by the\n\t\t// list's own `next_since` token.\n\t\tif (reorgsOn && opts.fetchReorgs && envelope.events.length === 0) {\n\t\t\treorgSince ??= cursor;\n\t\t\tif (reorgSince !== null) {\n\t\t\t\tconst since: string = reorgSince;\n\t\t\t\tconst fetchReorgs = opts.fetchReorgs;\n\t\t\t\tconst listed: StreamsReorgsListEnvelope = await fetchPageWithRetry(\n\t\t\t\t\t() => fetchReorgs({ since }),\n\t\t\t\t\t{\n\t\t\t\t\t\tretryCount: opts.retryCount,\n\t\t\t\t\t\tretryDelay: opts.retryDelay,\n\t\t\t\t\t\tonError: opts.onError,\n\t\t\t\t\t\tsleep,\n\t\t\t\t\t\tsignal: opts.signal,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (listed.next_since !== null) reorgSince = listed.next_since;\n\t\t\t\tconst rewound = await applyReorgs({\n\t\t\t\t\treorgs: listed.reorgs,\n\t\t\t\t\tcursor,\n\t\t\t\t\thandled: handledReorgs,\n\t\t\t\t\tkeyOf: reorgKey,\n\t\t\t\t\tsink: opts.sink,\n\t\t\t\t\tonReorg: opts.onReorg,\n\t\t\t\t\tmaxRollbackDepth: opts.maxRollbackDepth,\n\t\t\t\t});\n\t\t\t\tif (rewound) {\n\t\t\t\t\tcursor = rewound.cursor;\n\t\t\t\t\theight = rewound.forkPoint > 0 ? rewound.forkPoint - 1 : null;\n\t\t\t\t\tscanned = height;\n\t\t\t\t\temptyPolls = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst emitted = finalizedOnly\n\t\t\t? envelope.events.filter((event) => event.finalized)\n\t\t\t: envelope.events;\n\t\t// Only advance to the last finalized event in finalizedOnly mode; the\n\t\t// unfinalized tail is re-read next poll until it settles.\n\t\tconst checkpoint = finalizedOnly\n\t\t\t? (emitted.at(-1)?.cursor ?? cursor)\n\t\t\t: envelope.next_cursor;\n\t\t// Ascending cursor order, so the last row is the highest block this page\n\t\t// reached; an empty page keeps the previous value.\n\t\theight = emitted.at(-1)?.block_height ?? height;\n\t\t// Verified position. Rows delivered → through the last row (the page\n\t\t// limit hides what's above it). Empty page with an ADVANCED cursor →\n\t\t// through that cursor only (a server may cap an expensive filtered\n\t\t// scan; claiming the tip would overstate). Truly empty page → the\n\t\t// server confirmed nothing matches up to the tip. Non-empty raw page\n\t\t// fully filtered (unfinalized tail) → position unchanged.\n\t\tif (emitted.length > 0) {\n\t\t\tscanned = height;\n\t\t} else if (checkpoint !== null && checkpoint !== cursor) {\n\t\t\tscanned = resumeHeight(checkpoint) ?? scanned;\n\t\t} else if (envelope.events.length === 0) {\n\t\t\tscanned = envelope.tip.block_height;\n\t\t}\n\n\t\t// An empty page reports the STANDING cursor, not null: the committed\n\t\t// checkpoint is still this consumer's position while it idles.\n\t\tconst ctx = batchContext(\n\t\t\tcheckpoint ?? cursor,\n\t\t\theight,\n\t\t\tenvelope.tip,\n\t\t\tenvelope.reorgs,\n\t\t\tscanned,\n\t\t);\n\t\t// Before any early return: an empty page still proves the loop is alive.\n\t\topts.onProgress?.(ctx);\n\n\t\tlet nextCursor: string | null;\n\t\tif (opts.sink) {\n\t\t\tconst sink = opts.sink;\n\t\t\t// Rows and cursor commit in ONE transaction; a handler throw aborts\n\t\t\t// both. Nothing moved → nothing to commit, handler not invoked.\n\t\t\tif (\n\t\t\t\tcheckpoint !== null &&\n\t\t\t\t(checkpoint !== cursor || emitted.length > 0)\n\t\t\t) {\n\t\t\t\tawait sink.commitBatch(checkpoint, async (tx) => {\n\t\t\t\t\t// The cast is sound exactly as far as the sink's own typing:\n\t\t\t\t\t// `sink: ConsumerSink<TTx>` binds TTx, and `tx` here is what its\n\t\t\t\t\t// commitBatch lends. Nothing verifies it at runtime — a sink whose\n\t\t\t\t\t// declared Tx lies about what it lends fails inside the handler.\n\t\t\t\t\tawait opts.onBatch(emitted, envelope, {\n\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\ttx,\n\t\t\t\t\t} as ConsumerBatchContext & WithSinkTx<TTx>);\n\t\t\t\t});\n\t\t\t}\n\t\t\tnextCursor = checkpoint;\n\t\t} else {\n\t\t\tconst returnedCursor = await opts.onBatch(\n\t\t\t\temitted,\n\t\t\t\tenvelope,\n\t\t\t\tctx as ConsumerBatchContext & WithSinkTx<TTx>,\n\t\t\t);\n\t\t\tif (finalizedOnly) assertFinalizedCheckpoint(returnedCursor, checkpoint);\n\t\t\tnextCursor = returnedCursor ?? checkpoint;\n\t\t}\n\n\t\tif (nextCursor && nextCursor !== cursor) {\n\t\t\tcursor = nextCursor;\n\t\t\temptyPolls = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (emitted.length === 0) {\n\t\t\temptyPolls++;\n\t\t\tif (mode === \"bounded\") {\n\t\t\t\treturn { cursor, pages, emptyPolls };\n\t\t\t}\n\t\t\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",
|
|
@@ -257,6 +257,7 @@ type ArchiveVerifyResult = {
|
|
|
257
257
|
reason?: string;
|
|
258
258
|
};
|
|
259
259
|
import { RangeDigest } from "@secondlayer/shared/archive/range-digest";
|
|
260
|
+
import { ArchiveStatus } from "@secondlayer/shared/archive/status";
|
|
260
261
|
type ArchiveDataset = "blocks" | "transactions" | "events";
|
|
261
262
|
type ArchiveFlow = "bootstrap" | "repair";
|
|
262
263
|
type ArchivePartition = {
|
|
@@ -326,7 +327,7 @@ type ArchiveLoadOptions = {
|
|
|
326
327
|
type ArchiveClient = {
|
|
327
328
|
latest(against?: string, opts?: ArchiveLoadOptions): Promise<LoadedArchive>;
|
|
328
329
|
load(against: string, opts?: ArchiveLoadOptions): Promise<LoadedArchive>;
|
|
329
|
-
status(): Promise<
|
|
330
|
+
status(): Promise<ArchiveStatus>;
|
|
330
331
|
partitions(ref: LoadedArchive, filter?: {
|
|
331
332
|
dataset?: ArchiveDataset;
|
|
332
333
|
fromBlock?: number;
|
|
@@ -2461,23 +2462,23 @@ declare class Index extends BaseClient {
|
|
|
2461
2462
|
private walkPoxCycles;
|
|
2462
2463
|
private getPoxCycle;
|
|
2463
2464
|
}
|
|
2464
|
-
import {
|
|
2465
|
-
declare class
|
|
2465
|
+
import { CreateWebhookRequest, CreateWebhookResponse, DeadRow, DeliveryRow, ReplayResult, RotateSecretResponse, UpdateWebhookRequest, WebhookDetail, WebhookSummary, WebhookTestResult } from "@secondlayer/shared/schemas/webhooks";
|
|
2466
|
+
declare class Webhooks extends BaseClient {
|
|
2466
2467
|
list(): Promise<{
|
|
2467
|
-
data:
|
|
2468
|
+
data: WebhookSummary[];
|
|
2468
2469
|
}>;
|
|
2469
|
-
get(id: string): Promise<
|
|
2470
|
-
create(input:
|
|
2471
|
-
update(id: string, patch:
|
|
2472
|
-
pause(id: string): Promise<
|
|
2473
|
-
resume(id: string): Promise<
|
|
2470
|
+
get(id: string): Promise<WebhookDetail>;
|
|
2471
|
+
create(input: CreateWebhookRequest): Promise<CreateWebhookResponse>;
|
|
2472
|
+
update(id: string, patch: UpdateWebhookRequest): Promise<WebhookDetail>;
|
|
2473
|
+
pause(id: string): Promise<WebhookDetail>;
|
|
2474
|
+
resume(id: string): Promise<WebhookDetail>;
|
|
2474
2475
|
delete(id: string): Promise<{
|
|
2475
2476
|
ok: true;
|
|
2476
2477
|
}>;
|
|
2477
2478
|
rotateSecret(id: string): Promise<RotateSecretResponse>;
|
|
2478
|
-
/** Send a one-off test webhook to the
|
|
2479
|
+
/** Send a one-off test webhook to the webhook's URL (built for its
|
|
2479
2480
|
* format, SSRF-guarded). Logged as a delivery row, visible via deliveries. */
|
|
2480
|
-
test(id: string): Promise<
|
|
2481
|
+
test(id: string): Promise<WebhookTestResult>;
|
|
2481
2482
|
/** The last 100 delivery attempts, newest first. The server caps the window;
|
|
2482
2483
|
* there is nothing to page. */
|
|
2483
2484
|
deliveries(id: string): Promise<{
|
|
@@ -2538,6 +2539,11 @@ interface ContextSnapshot {
|
|
|
2538
2539
|
streamsTip: ContextField<StreamsTip>;
|
|
2539
2540
|
indexTip: ContextField<IndexTip>;
|
|
2540
2541
|
subgraphs: ContextField<SubgraphSummary2[]>;
|
|
2542
|
+
webhooks: ContextField<{
|
|
2543
|
+
count: number;
|
|
2544
|
+
byStatus: Record<string, number>;
|
|
2545
|
+
}>;
|
|
2546
|
+
/** @deprecated Use {@link ContextSnapshot.webhooks}. Removed next minor. */
|
|
2541
2547
|
subscriptions: ContextField<{
|
|
2542
2548
|
count: number;
|
|
2543
2549
|
byStatus: Record<string, number>;
|
|
@@ -2552,9 +2558,11 @@ declare class SecondLayer extends BaseClient {
|
|
|
2552
2558
|
readonly index: Index;
|
|
2553
2559
|
readonly contracts: Contracts;
|
|
2554
2560
|
readonly subgraphs: Subgraphs;
|
|
2555
|
-
readonly
|
|
2561
|
+
readonly webhooks: Webhooks;
|
|
2556
2562
|
readonly archive: SecondLayerArchive;
|
|
2557
2563
|
readonly instance: InstanceClient;
|
|
2564
|
+
/** @deprecated Use `webhooks`. Removed next minor. */
|
|
2565
|
+
get subscriptions(): Webhooks;
|
|
2558
2566
|
constructor(options?: Partial<SecondLayerOptions>);
|
|
2559
2567
|
/**
|
|
2560
2568
|
* Up to 10 public reads in one round trip (`POST /v1/batch`). Each item
|
package/dist/subgraphs/index.js
CHANGED
|
@@ -983,7 +983,7 @@ function createArchiveClient(options = {}) {
|
|
|
983
983
|
if (!response.ok) {
|
|
984
984
|
throw new ApiError(response.status, `Could not fetch archive status (${response.status}).`);
|
|
985
985
|
}
|
|
986
|
-
return response.json();
|
|
986
|
+
return await response.json();
|
|
987
987
|
}
|
|
988
988
|
function partitions(ref, filter) {
|
|
989
989
|
let list = ref.manifest.partitions ?? [];
|
|
@@ -2448,50 +2448,51 @@ function createStreamsClient(options) {
|
|
|
2448
2448
|
};
|
|
2449
2449
|
}
|
|
2450
2450
|
|
|
2451
|
-
// src/
|
|
2452
|
-
import { trigger } from "@secondlayer/shared/schemas/
|
|
2451
|
+
// src/webhooks/client.ts
|
|
2452
|
+
import { trigger } from "@secondlayer/shared/schemas/webhooks";
|
|
2453
2453
|
|
|
2454
|
-
class
|
|
2454
|
+
class Webhooks extends BaseClient {
|
|
2455
2455
|
async list() {
|
|
2456
|
-
return this.request("GET", "/api/
|
|
2456
|
+
return this.request("GET", "/api/webhooks");
|
|
2457
2457
|
}
|
|
2458
2458
|
async get(id) {
|
|
2459
|
-
return this.request("GET", `/api/
|
|
2459
|
+
return this.request("GET", `/api/webhooks/${seg(id)}`);
|
|
2460
2460
|
}
|
|
2461
2461
|
async create(input) {
|
|
2462
|
-
return this.request("POST", "/api/
|
|
2462
|
+
return this.request("POST", "/api/webhooks", input);
|
|
2463
2463
|
}
|
|
2464
2464
|
async update(id, patch) {
|
|
2465
|
-
return this.request("PATCH", `/api/
|
|
2465
|
+
return this.request("PATCH", `/api/webhooks/${seg(id)}`, patch);
|
|
2466
2466
|
}
|
|
2467
2467
|
async pause(id) {
|
|
2468
|
-
return this.request("POST", `/api/
|
|
2468
|
+
return this.request("POST", `/api/webhooks/${seg(id)}/pause`);
|
|
2469
2469
|
}
|
|
2470
2470
|
async resume(id) {
|
|
2471
|
-
return this.request("POST", `/api/
|
|
2471
|
+
return this.request("POST", `/api/webhooks/${seg(id)}/resume`);
|
|
2472
2472
|
}
|
|
2473
2473
|
async delete(id) {
|
|
2474
|
-
return this.request("DELETE", `/api/
|
|
2474
|
+
return this.request("DELETE", `/api/webhooks/${seg(id)}`);
|
|
2475
2475
|
}
|
|
2476
2476
|
async rotateSecret(id) {
|
|
2477
|
-
return this.request("POST", `/api/
|
|
2477
|
+
return this.request("POST", `/api/webhooks/${seg(id)}/rotate-secret`);
|
|
2478
2478
|
}
|
|
2479
2479
|
async test(id) {
|
|
2480
|
-
return this.request("POST", `/api/
|
|
2480
|
+
return this.request("POST", `/api/webhooks/${seg(id)}/test`);
|
|
2481
2481
|
}
|
|
2482
2482
|
async deliveries(id) {
|
|
2483
|
-
return this.request("GET", `/api/
|
|
2483
|
+
return this.request("GET", `/api/webhooks/${seg(id)}/deliveries`);
|
|
2484
2484
|
}
|
|
2485
2485
|
async replay(id, range) {
|
|
2486
|
-
return this.request("POST", `/api/
|
|
2486
|
+
return this.request("POST", `/api/webhooks/${seg(id)}/replay`, range);
|
|
2487
2487
|
}
|
|
2488
2488
|
async dead(id) {
|
|
2489
|
-
return this.request("GET", `/api/
|
|
2489
|
+
return this.request("GET", `/api/webhooks/${seg(id)}/dead`);
|
|
2490
2490
|
}
|
|
2491
2491
|
async requeue(id, outboxId) {
|
|
2492
|
-
return this.request("POST", `/api/
|
|
2492
|
+
return this.request("POST", `/api/webhooks/${seg(id)}/dead/${seg(outboxId)}/requeue`);
|
|
2493
2493
|
}
|
|
2494
2494
|
}
|
|
2495
|
+
var Subscriptions = Webhooks;
|
|
2495
2496
|
|
|
2496
2497
|
// src/client.ts
|
|
2497
2498
|
async function contextField(read) {
|
|
@@ -2524,9 +2525,12 @@ class SecondLayer extends BaseClient {
|
|
|
2524
2525
|
index;
|
|
2525
2526
|
contracts;
|
|
2526
2527
|
subgraphs;
|
|
2527
|
-
|
|
2528
|
+
webhooks;
|
|
2528
2529
|
archive;
|
|
2529
2530
|
instance;
|
|
2531
|
+
get subscriptions() {
|
|
2532
|
+
return this.webhooks;
|
|
2533
|
+
}
|
|
2530
2534
|
constructor(options = {}) {
|
|
2531
2535
|
super(options);
|
|
2532
2536
|
this.streams = createStreamsClient({
|
|
@@ -2541,7 +2545,7 @@ class SecondLayer extends BaseClient {
|
|
|
2541
2545
|
this.index = new Index(options);
|
|
2542
2546
|
this.contracts = new Contracts(options);
|
|
2543
2547
|
this.subgraphs = new Subgraphs(options);
|
|
2544
|
-
this.
|
|
2548
|
+
this.webhooks = new Webhooks(options);
|
|
2545
2549
|
const request = (method, path, body) => this.request(method, path, body);
|
|
2546
2550
|
this.archive = {
|
|
2547
2551
|
...createArchiveClient({
|
|
@@ -2558,36 +2562,29 @@ class SecondLayer extends BaseClient {
|
|
|
2558
2562
|
return this.request("POST", "/v1/batch", { requests });
|
|
2559
2563
|
}
|
|
2560
2564
|
async context() {
|
|
2561
|
-
const [
|
|
2562
|
-
account,
|
|
2563
|
-
streamsTip,
|
|
2564
|
-
indexEnv,
|
|
2565
|
-
subgraphsRes,
|
|
2566
|
-
subscriptionsRes,
|
|
2567
|
-
instance
|
|
2568
|
-
] = await Promise.all([
|
|
2565
|
+
const [account, streamsTip, indexEnv, subgraphsRes, webhooksRes, instance] = await Promise.all([
|
|
2569
2566
|
contextField(this.request("GET", "/api/accounts/me")),
|
|
2570
2567
|
contextField(this.streams.tip()),
|
|
2571
2568
|
contextField(this.index.canonical.list({ limit: 1 })),
|
|
2572
2569
|
contextField(this.subgraphs.list()),
|
|
2573
|
-
contextField(this.
|
|
2570
|
+
contextField(this.webhooks.list()),
|
|
2574
2571
|
contextField(this.instance.diagnose())
|
|
2575
2572
|
]);
|
|
2576
2573
|
const subgraphs = {
|
|
2577
2574
|
value: subgraphsRes.value?.data ?? null,
|
|
2578
2575
|
...subgraphsRes.error ? { error: subgraphsRes.error } : {}
|
|
2579
2576
|
};
|
|
2580
|
-
const
|
|
2577
|
+
const webhooks = {
|
|
2581
2578
|
value: null,
|
|
2582
|
-
...
|
|
2579
|
+
...webhooksRes.error ? { error: webhooksRes.error } : {}
|
|
2583
2580
|
};
|
|
2584
|
-
if (
|
|
2581
|
+
if (webhooksRes.value) {
|
|
2585
2582
|
const byStatus = {};
|
|
2586
|
-
for (const s of
|
|
2583
|
+
for (const s of webhooksRes.value.data) {
|
|
2587
2584
|
byStatus[s.status] = (byStatus[s.status] ?? 0) + 1;
|
|
2588
2585
|
}
|
|
2589
|
-
|
|
2590
|
-
count:
|
|
2586
|
+
webhooks.value = {
|
|
2587
|
+
count: webhooksRes.value.data.length,
|
|
2591
2588
|
byStatus
|
|
2592
2589
|
};
|
|
2593
2590
|
}
|
|
@@ -2622,7 +2619,8 @@ class SecondLayer extends BaseClient {
|
|
|
2622
2619
|
...indexEnv.error ? { error: indexEnv.error } : {}
|
|
2623
2620
|
},
|
|
2624
2621
|
subgraphs,
|
|
2625
|
-
|
|
2622
|
+
webhooks,
|
|
2623
|
+
subscriptions: webhooks,
|
|
2626
2624
|
activeOperations,
|
|
2627
2625
|
instance
|
|
2628
2626
|
};
|
|
@@ -2644,5 +2642,5 @@ export {
|
|
|
2644
2642
|
Subgraphs
|
|
2645
2643
|
};
|
|
2646
2644
|
|
|
2647
|
-
//# debugId=
|
|
2645
|
+
//# debugId=4F7940AD0B707D9F64756E2164756E21
|
|
2648
2646
|
//# sourceMappingURL=index.js.map
|