@secondlayer/shared 6.19.0 → 6.21.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.
@@ -5,13 +5,13 @@
5
5
  "import { z } from \"zod/v4\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tenabledNetworks = [\"mainnet\"]; // Default\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(): boolean {\n\treturn process.env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n// Export for testing\nexport { envSchema };\n",
6
6
  "import { getEnv } from \"./env.ts\";\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n\tdebug: 0,\n\tinfo: 1,\n\twarn: 2,\n\terror: 3,\n};\n\nclass Logger {\n\tprivate _level?: LogLevel;\n\tprivate _isProduction?: boolean;\n\tprivate _initialized = false;\n\n\tprivate init() {\n\t\tif (this._initialized) return;\n\t\tthis._initialized = true;\n\t\ttry {\n\t\t\tconst env = getEnv();\n\t\t\tthis._level = env.LOG_LEVEL;\n\t\t\tthis._isProduction = env.NODE_ENV === \"production\";\n\t\t} catch {\n\t\t\t// Fallback when env is unavailable (e.g. tests without DATABASE_URL)\n\t\t\tthis._level = \"info\";\n\t\t\tthis._isProduction = false;\n\t\t}\n\t}\n\n\tprivate get level(): LogLevel {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._level!;\n\t}\n\n\tprivate get isProduction(): boolean {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._isProduction!;\n\t}\n\n\tprivate shouldLog(level: LogLevel): boolean {\n\t\treturn LOG_LEVELS[level] >= LOG_LEVELS[this.level];\n\t}\n\n\tprivate formatMessage(\n\t\tlevel: LogLevel,\n\t\tmessage: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\tmeta?: Record<string, any>,\n\t) {\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tif (this.isProduction) {\n\t\t\t// JSON output for production\n\t\t\treturn JSON.stringify({\n\t\t\t\ttimestamp,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\t...meta,\n\t\t\t});\n\t\t}\n\n\t\t// Human-readable output for development\n\t\tconst metaStr = meta ? ` ${JSON.stringify(meta)}` : \"\";\n\t\treturn `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tdebug(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.debug(this.formatMessage(\"debug\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tinfo(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.info(this.formatMessage(\"info\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\twarn(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.warn(this.formatMessage(\"warn\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\terror(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"error\", message, meta));\n\t\t}\n\t}\n}\n\n// Export singleton instance\nexport const logger: Logger = new Logger();\n",
7
7
  "import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n",
8
- "import { Kysely } from \"kysely\";\nimport { PostgresJSDialect } from \"kysely-postgres-js\";\nimport postgres from \"postgres\";\nimport { logger } from \"../logger.ts\";\nimport type { Database } from \"./types.ts\";\n\nexport type { Database } from \"./types.ts\";\n\nconst DEFAULT_URL =\n\t\"postgres://postgres:postgres@localhost:5432/secondlayer_dev\";\n\ninterface PoolEntry {\n\tdb: Kysely<Database>;\n\trawClient: ReturnType<typeof postgres>;\n\t/** Last access (ms) — drives LRU eviction of BYO pools. */\n\tlastUsed: number;\n\t/** Monotonic counter as a tiebreaker; Date.now() can repeat under load. */\n\tseq: number;\n}\n\n/**\n * Cache of Kysely + raw postgres.js pools keyed by resolved URL.\n * Two getters resolving to the same URL share one entry (single pool) —\n * this is the single-DB backward-compat contract: when only `DATABASE_URL`\n * is set, `getSourceDb() === getTargetDb()` (zero regression vs. pre-dual-DB).\n *\n * The BYO data plane adds one pool per user-owned DB. To stop N user DBs from\n * exhausting connections/FDs, the map is bounded (`DATABASE_MAX_POOLS`, default\n * 25) with LRU eviction — the hot source/target pools are never evicted.\n */\nconst pools = new Map<string, PoolEntry>();\nlet poolSeq = 0;\n\nfunction maxPools(): number {\n\treturn Number.parseInt(process.env.DATABASE_MAX_POOLS ?? \"25\", 10);\n}\n\n/** Close the least-recently-used non-(source/target) pool when over the cap. */\nfunction evictIfNeeded(): void {\n\tif (pools.size <= maxPools()) return;\n\tconst protectedUrls = new Set([resolveSourceUrl(), resolveTargetUrl()]);\n\tlet lruUrl: string | undefined;\n\tlet lruEntry: PoolEntry | undefined;\n\tfor (const [url, entry] of pools) {\n\t\tif (protectedUrls.has(url)) continue;\n\t\tif (\n\t\t\t!lruEntry ||\n\t\t\tentry.lastUsed < lruEntry.lastUsed ||\n\t\t\t(entry.lastUsed === lruEntry.lastUsed && entry.seq < lruEntry.seq)\n\t\t) {\n\t\t\tlruUrl = url;\n\t\t\tlruEntry = entry;\n\t\t}\n\t}\n\tif (!lruUrl || !lruEntry) return;\n\tpools.delete(lruUrl);\n\tconst evicted = lruEntry;\n\t// Close in the background — never block pool creation on teardown.\n\tvoid evicted.db\n\t\t.destroy()\n\t\t.catch(() => {})\n\t\t.then(() => evicted.rawClient.end({ timeout: 5 }))\n\t\t.catch(() => {});\n}\n\nfunction resolveSourceUrl(): string {\n\treturn (\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction resolveTargetUrl(): string {\n\treturn (\n\t\tprocess.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\n/**\n * Boot guard: if the chain/control split is requested (`SOURCE_DATABASE_URL` or\n * `TARGET_DATABASE_URL` set) but both still resolve to the same DB — a typo, or\n * a stray `DATABASE_URL` masking the intent — the split silently collapses and\n * chain + control plane share one instance. Surface it loudly. Fail-soft (no\n * throw) so a misconfig doesn't brick startup; logs make it obvious.\n */\nexport function assertDbSplit(): void {\n\tconst wantsSplit = !!(\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.TARGET_DATABASE_URL\n\t);\n\tif (!wantsSplit) return;\n\tif (resolveSourceUrl() === resolveTargetUrl()) {\n\t\tconst msg =\n\t\t\t\"DB split requested but SOURCE_DATABASE_URL === TARGET_DATABASE_URL (check for a typo or a stray DATABASE_URL fallback)\";\n\t\tif (process.env.NODE_ENV === \"production\") console.error(`❌ ${msg}`);\n\t\telse console.warn(`⚠️ ${msg}`);\n\t}\n}\n\nfunction getOrCreatePool(url: string): PoolEntry {\n\tconst existing = pools.get(url);\n\tif (existing) {\n\t\texisting.lastUsed = Date.now();\n\t\texisting.seq = poolSeq++;\n\t\treturn existing;\n\t}\n\n\t// \"Local\" = we skip TLS. Any Docker service alias (single-label hostname\n\t// with no dots) is on an internal network and won't serve TLS.\n\tconst host = (() => {\n\t\ttry {\n\t\t\treturn new URL(url).hostname;\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t})();\n\tconst isLocal =\n\t\thost === \"localhost\" || host === \"127.0.0.1\" || !host.includes(\".\");\n\tconst poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? \"20\", 10);\n\t// Close idle connections so a fleet of BYO pools doesn't pin connections it\n\t// no longer needs (0 = never; postgres.js default).\n\tconst idleTimeout = Number.parseInt(\n\t\tprocess.env.DATABASE_IDLE_TIMEOUT ?? \"300\",\n\t\t10,\n\t);\n\tconst rawClient = postgres(url, {\n\t\tmax: poolMax,\n\t\tidle_timeout: idleTimeout,\n\t\tssl: isLocal\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\trejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== \"0\",\n\t\t\t\t},\n\t});\n\tconst db = new Kysely<Database>({\n\t\tdialect: new PostgresJSDialect({ postgres: rawClient }),\n\t\t// Diagnostic hook: surface the failing SQL whenever postgres rejects\n\t\t// with code 42P10 (ON CONFLICT target doesn't match any unique\n\t\t// constraint). Temporary — remove once we've caught the culprit\n\t\t// query in prod logs and fixed the schema drift.\n\t\tlog: (event) => {\n\t\t\tif (event.level !== \"error\") return;\n\t\t\tconst err = event.error as {\n\t\t\t\tcode?: string;\n\t\t\t\tmessage?: string;\n\t\t\t} | null;\n\t\t\tif (err?.code !== \"42P10\") return;\n\t\t\tlogger.warn(\"db.on_conflict_constraint_missing\", {\n\t\t\t\tcode: err.code,\n\t\t\t\tmessage: err.message,\n\t\t\t\tsql: event.query.sql,\n\t\t\t\tparams: event.query.parameters,\n\t\t\t});\n\t\t},\n\t});\n\tconst entry: PoolEntry = {\n\t\tdb,\n\t\trawClient,\n\t\tlastUsed: Date.now(),\n\t\tseq: poolSeq++,\n\t};\n\tpools.set(url, entry);\n\tevictIfNeeded();\n\treturn entry;\n}\n\n/**\n * Kysely instance for the SOURCE DB (block/tx/event reads from the shared\n * indexer). Resolution: `SOURCE_DATABASE_URL || DATABASE_URL`.\n */\nexport function getSourceDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveSourceUrl()).db;\n}\n\n/**\n * Kysely instance for the TARGET DB (subgraph schemas, subgraphs table,\n * account-scoped data — tenant-side writes). Resolution:\n * `TARGET_DATABASE_URL || DATABASE_URL`.\n */\nexport function getTargetDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveTargetUrl()).db;\n}\n\n/**\n * Backward-compat alias for `getTargetDb()`. Accepts an optional\n * `connectionString` override used by seed/test helpers — when supplied,\n * bypasses env resolution and uses the provided URL directly (still cached).\n */\nexport function getDb(connectionString?: string): Kysely<Database> {\n\tif (connectionString) return getOrCreatePool(connectionString).db;\n\treturn getTargetDb();\n}\n\n/**\n * Raw postgres.js client for dynamic schema DDL (CREATE SCHEMA, DROP, etc.).\n * Defaults to the target role (tenant schemas live in the target DB).\n */\nexport function getRawClient(\n\trole: \"source\" | \"target\" = \"target\",\n): ReturnType<typeof postgres> {\n\tconst url = role === \"source\" ? resolveSourceUrl() : resolveTargetUrl();\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/**\n * Raw postgres.js client for an arbitrary connection string (cached by URL).\n * Used by the BYO data plane to run DDL / serving queries against a\n * user-owned Postgres. Distinct from {@link getRawClient}, which only knows the\n * source/target roles resolved from env.\n */\nexport function getRawClientFor(url: string): ReturnType<typeof postgres> {\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/** Close all DB connection pools. Call in CLI commands to allow process exit. */\nexport async function closeDb(): Promise<void> {\n\tfor (const entry of pools.values()) {\n\t\tawait entry.db.destroy();\n\t\tawait entry.rawClient.end();\n\t}\n\tpools.clear();\n}\n\nimport { sql } from \"kysely\";\nexport { sql };\nexport * from \"./types.ts\";\nexport type { DbReadRow, NumericAsText } from \"./read-row.ts\";\nexport { SOURCE_READ_COLUMNS } from \"./source-read-columns.ts\";\nexport { jsonb, parseJsonb } from \"./jsonb.ts\";\n",
8
+ "import { Kysely } from \"kysely\";\nimport { PostgresJSDialect } from \"kysely-postgres-js\";\nimport postgres from \"postgres\";\nimport { logger } from \"../logger.ts\";\nimport type { Database } from \"./types.ts\";\n\nexport type { Database } from \"./types.ts\";\n\nconst DEFAULT_URL =\n\t\"postgres://postgres:postgres@localhost:5432/secondlayer_dev\";\n\ninterface PoolEntry {\n\tdb: Kysely<Database>;\n\trawClient: ReturnType<typeof postgres>;\n\t/** Last access (ms) — drives LRU eviction of BYO pools. */\n\tlastUsed: number;\n\t/** Monotonic counter as a tiebreaker; Date.now() can repeat under load. */\n\tseq: number;\n}\n\n/**\n * Cache of Kysely + raw postgres.js pools keyed by resolved URL.\n * Two getters resolving to the same URL share one entry (single pool) —\n * this is the single-DB backward-compat contract: when only `DATABASE_URL`\n * is set, `getSourceDb() === getTargetDb()` (zero regression vs. pre-dual-DB).\n *\n * The BYO data plane adds one pool per user-owned DB. To stop N user DBs from\n * exhausting connections/FDs, the map is bounded (`DATABASE_MAX_POOLS`, default\n * 25) with LRU eviction — the hot source/target pools are never evicted.\n */\nconst pools = new Map<string, PoolEntry>();\nlet poolSeq = 0;\n\nfunction maxPools(): number {\n\treturn Number.parseInt(process.env.DATABASE_MAX_POOLS ?? \"25\", 10);\n}\n\n/** Close the least-recently-used non-(source/target) pool when over the cap. */\nfunction evictIfNeeded(): void {\n\tif (pools.size <= maxPools()) return;\n\tconst protectedUrls = new Set([resolveSourceUrl(), resolveTargetUrl()]);\n\tlet lruUrl: string | undefined;\n\tlet lruEntry: PoolEntry | undefined;\n\tfor (const [url, entry] of pools) {\n\t\tif (protectedUrls.has(url)) continue;\n\t\tif (\n\t\t\t!lruEntry ||\n\t\t\tentry.lastUsed < lruEntry.lastUsed ||\n\t\t\t(entry.lastUsed === lruEntry.lastUsed && entry.seq < lruEntry.seq)\n\t\t) {\n\t\t\tlruUrl = url;\n\t\t\tlruEntry = entry;\n\t\t}\n\t}\n\tif (!lruUrl || !lruEntry) return;\n\tpools.delete(lruUrl);\n\tconst evicted = lruEntry;\n\t// Close in the background — never block pool creation on teardown.\n\tvoid evicted.db\n\t\t.destroy()\n\t\t.catch(() => {})\n\t\t.then(() => evicted.rawClient.end({ timeout: 5 }))\n\t\t.catch(() => {});\n}\n\nfunction resolveSourceUrl(): string {\n\treturn (\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction resolveTargetUrl(): string {\n\treturn (\n\t\tprocess.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\n/** Host[:port]/dbname for a connection URL — credentials stripped. */\nfunction describeDbUrl(url: string): string {\n\ttry {\n\t\tconst u = new URL(url);\n\t\treturn `${u.hostname}${u.port ? `:${u.port}` : \"\"}${u.pathname}`;\n\t} catch {\n\t\treturn \"invalid-url\";\n\t}\n}\n\nexport interface DbSplitStatus {\n\t/** \"split\" when source/target resolve to different DBs, else \"single\". */\n\tmode: \"split\" | \"single\";\n\t/** True when the chain/control split is live (distinct DBs). */\n\tactive: boolean;\n\t/** SOURCE host[:port]/dbname (no credentials). */\n\tsourceDb: string;\n\t/** TARGET host[:port]/dbname (no credentials). */\n\ttargetDb: string;\n}\n\n/**\n * Resolved source/target DB identity for status/health surfaces. Lets operators\n * see whether the chain/control split is live or dormant (collapsed to one DB)\n * without shelling in. Credentials are never exposed — host/db only.\n *\n * `active` is a STRING-IDENTITY check on the two URLs: it can't catch two\n * distinct URLs that alias the same physical instance (e.g. `postgres` vs\n * `127.0.0.1`, or a swapped/wrong host). Treat `active: true` as \"configured\n * for split\", not a proof of physical isolation.\n */\nexport function getDbSplitStatus(): DbSplitStatus {\n\tconst source = resolveSourceUrl();\n\tconst target = resolveTargetUrl();\n\tconst active = source !== target;\n\treturn {\n\t\tmode: active ? \"split\" : \"single\",\n\t\tactive,\n\t\tsourceDb: describeDbUrl(source),\n\t\ttargetDb: describeDbUrl(target),\n\t};\n}\n\n/**\n * Boot guard for the chain/control DB split. Surfaces three misconfigurations\n * loudly (fail-soft — logs, never throws, so a misconfig can't brick startup):\n *\n * 1. Silent wrong-DB: a split is requested (one of SOURCE_/TARGET_ set) but\n * `DATABASE_URL` is absent (the split-prod default) and the OTHER var is\n * unset, so it falls through to the built-in dev `DEFAULT_URL` — about to\n * read/write a real-but-wrong database. This is the failure mode the\n * remove-DATABASE_URL decision creates; catch it.\n * 2. Collapsed split: both vars set but resolve to the same DB (typo, or a\n * stray `DATABASE_URL` masking the intent).\n * 3. Dormant split (prod only): neither var set, so all services share one\n * Postgres failure domain. Not an error, but no longer silent.\n */\nexport function assertDbSplit(): void {\n\tconst isProd = process.env.NODE_ENV === \"production\";\n\tconst wantsSplit = !!(\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.TARGET_DATABASE_URL\n\t);\n\tconst databaseUrlSet = !!process.env.DATABASE_URL;\n\tconst source = resolveSourceUrl();\n\tconst target = resolveTargetUrl();\n\n\tif (\n\t\twantsSplit &&\n\t\t!databaseUrlSet &&\n\t\t(source === DEFAULT_URL || target === DEFAULT_URL)\n\t) {\n\t\tconst which =\n\t\t\tsource === DEFAULT_URL ? \"SOURCE_DATABASE_URL\" : \"TARGET_DATABASE_URL\";\n\t\tconst msg = `${which} unset and DATABASE_URL absent — resolving to built-in DEFAULT_URL; refusing to silently use the wrong database`;\n\t\tif (isProd) console.error(`❌ ${msg}`);\n\t\telse console.warn(`⚠️ ${msg}`);\n\t\treturn;\n\t}\n\n\tif (!wantsSplit) {\n\t\tif (isProd) {\n\t\t\tconsole.warn(\n\t\t\t\t\"⚠️ DB split dormant — all services share one Postgres failure domain (SOURCE_/TARGET_DATABASE_URL unset)\",\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (source === target) {\n\t\tconst msg =\n\t\t\t\"DB split requested but SOURCE_DATABASE_URL === TARGET_DATABASE_URL (check for a typo or a stray DATABASE_URL fallback)\";\n\t\tif (isProd) console.error(`❌ ${msg}`);\n\t\telse console.warn(`⚠️ ${msg}`);\n\t}\n}\n\nfunction getOrCreatePool(url: string): PoolEntry {\n\tconst existing = pools.get(url);\n\tif (existing) {\n\t\texisting.lastUsed = Date.now();\n\t\texisting.seq = poolSeq++;\n\t\treturn existing;\n\t}\n\n\t// \"Local\" = we skip TLS. Any Docker service alias (single-label hostname\n\t// with no dots) is on an internal network and won't serve TLS.\n\tconst host = (() => {\n\t\ttry {\n\t\t\treturn new URL(url).hostname;\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t})();\n\tconst isLocal =\n\t\thost === \"localhost\" || host === \"127.0.0.1\" || !host.includes(\".\");\n\tconst poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? \"20\", 10);\n\t// Close idle connections so a fleet of BYO pools doesn't pin connections it\n\t// no longer needs (0 = never; postgres.js default).\n\tconst idleTimeout = Number.parseInt(\n\t\tprocess.env.DATABASE_IDLE_TIMEOUT ?? \"300\",\n\t\t10,\n\t);\n\tconst rawClient = postgres(url, {\n\t\tmax: poolMax,\n\t\tidle_timeout: idleTimeout,\n\t\tssl: isLocal\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\trejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== \"0\",\n\t\t\t\t},\n\t});\n\tconst db = new Kysely<Database>({\n\t\tdialect: new PostgresJSDialect({ postgres: rawClient }),\n\t\t// Diagnostic hook: surface the failing SQL whenever postgres rejects\n\t\t// with code 42P10 (ON CONFLICT target doesn't match any unique\n\t\t// constraint). Temporary — remove once we've caught the culprit\n\t\t// query in prod logs and fixed the schema drift.\n\t\tlog: (event) => {\n\t\t\tif (event.level !== \"error\") return;\n\t\t\tconst err = event.error as {\n\t\t\t\tcode?: string;\n\t\t\t\tmessage?: string;\n\t\t\t} | null;\n\t\t\tif (err?.code !== \"42P10\") return;\n\t\t\tlogger.warn(\"db.on_conflict_constraint_missing\", {\n\t\t\t\tcode: err.code,\n\t\t\t\tmessage: err.message,\n\t\t\t\tsql: event.query.sql,\n\t\t\t\tparams: event.query.parameters,\n\t\t\t});\n\t\t},\n\t});\n\tconst entry: PoolEntry = {\n\t\tdb,\n\t\trawClient,\n\t\tlastUsed: Date.now(),\n\t\tseq: poolSeq++,\n\t};\n\tpools.set(url, entry);\n\tevictIfNeeded();\n\treturn entry;\n}\n\n/**\n * Kysely instance for the SOURCE DB (block/tx/event reads from the shared\n * indexer). Resolution: `SOURCE_DATABASE_URL || DATABASE_URL`.\n */\nexport function getSourceDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveSourceUrl()).db;\n}\n\n/**\n * Kysely instance for the TARGET DB (subgraph schemas, subgraphs table,\n * account-scoped data — tenant-side writes). Resolution:\n * `TARGET_DATABASE_URL || DATABASE_URL`.\n */\nexport function getTargetDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveTargetUrl()).db;\n}\n\n/**\n * Backward-compat alias for `getTargetDb()`. Accepts an optional\n * `connectionString` override used by seed/test helpers — when supplied,\n * bypasses env resolution and uses the provided URL directly (still cached).\n */\nexport function getDb(connectionString?: string): Kysely<Database> {\n\tif (connectionString) return getOrCreatePool(connectionString).db;\n\treturn getTargetDb();\n}\n\n/**\n * Raw postgres.js client for dynamic schema DDL (CREATE SCHEMA, DROP, etc.).\n * Defaults to the target role (tenant schemas live in the target DB).\n */\nexport function getRawClient(\n\trole: \"source\" | \"target\" = \"target\",\n): ReturnType<typeof postgres> {\n\tconst url = role === \"source\" ? resolveSourceUrl() : resolveTargetUrl();\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/**\n * Raw postgres.js client for an arbitrary connection string (cached by URL).\n * Used by the BYO data plane to run DDL / serving queries against a\n * user-owned Postgres. Distinct from {@link getRawClient}, which only knows the\n * source/target roles resolved from env.\n */\nexport function getRawClientFor(url: string): ReturnType<typeof postgres> {\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/** Close all DB connection pools. Call in CLI commands to allow process exit. */\nexport async function closeDb(): Promise<void> {\n\tfor (const entry of pools.values()) {\n\t\tawait entry.db.destroy();\n\t\tawait entry.rawClient.end();\n\t}\n\tpools.clear();\n}\n\nimport { sql } from \"kysely\";\nexport { sql };\nexport * from \"./types.ts\";\nexport type { DbReadRow, NumericAsText } from \"./read-row.ts\";\nexport { SOURCE_READ_COLUMNS } from \"./source-read-columns.ts\";\nexport { jsonb, parseJsonb } from \"./jsonb.ts\";\n",
9
9
  "import type { Database } from \"./types.ts\";\n\n// The physical source-table columns the public read API (packages/api) actually\n// reads via getSourceDb(). This is the read contract between the indexer (which\n// owns the write schema) and the API (which reads it raw). A column rename or\n// removal on the producer side that isn't reflected here is caught by the\n// snapshot drift test; the `satisfies` clause guarantees every entry is a real\n// table + column today.\n//\n// Computed/aliased read expressions are intentionally excluded — they are not\n// part of the producer contract: `cursor`/`block_time` where derived in SQL\n// rather than stored, window ranks (stream_event_index), and JSONB extractions\n// from `events.data`. Generated bookkeeping columns (created_at/updated_at) are\n// excluded unless a read path selects them.\nexport const SOURCE_READ_COLUMNS = {\n\tblocks: [\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"hash\",\n\t\t\"height\",\n\t\t\"parent_hash\",\n\t\t\"timestamp\",\n\t],\n\tdecoded_events: [\n\t\t\"amount\",\n\t\t\"asset_identifier\",\n\t\t\"block_height\",\n\t\t\"canonical\",\n\t\t\"contract_id\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"event_type\",\n\t\t\"memo\",\n\t\t\"payload\",\n\t\t\"recipient\",\n\t\t\"sender\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t\t\"value\",\n\t],\n\ttransactions: [\n\t\t\"block_height\",\n\t\t\"contract_id\",\n\t\t\"function_args\",\n\t\t\"function_name\",\n\t\t\"raw_result\",\n\t\t\"raw_tx\",\n\t\t\"sender\",\n\t\t\"status\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t\t\"type\",\n\t],\n\tmempool_transactions: [\n\t\t\"contract_id\",\n\t\t\"function_args\",\n\t\t\"function_name\",\n\t\t\"raw_tx\",\n\t\t\"received_at\",\n\t\t\"sender\",\n\t\t\"seq\",\n\t\t\"tx_id\",\n\t\t\"type\",\n\t],\n\tpox4_calls: [\n\t\t\"aggregated_amount_ustx\",\n\t\t\"aggregated_signer_index\",\n\t\t\"amount_ustx\",\n\t\t\"auth_allowed\",\n\t\t\"auth_id\",\n\t\t\"auth_period\",\n\t\t\"auth_topic\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"burn_block_height\",\n\t\t\"caller\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"delegate_to\",\n\t\t\"end_cycle\",\n\t\t\"function_name\",\n\t\t\"lock_period\",\n\t\t\"max_amount\",\n\t\t\"pox_addr_btc\",\n\t\t\"pox_addr_hashbytes\",\n\t\t\"pox_addr_version\",\n\t\t\"result_ok\",\n\t\t\"reward_cycle\",\n\t\t\"signer_key\",\n\t\t\"signer_signature\",\n\t\t\"source_cursor\",\n\t\t\"stacker\",\n\t\t\"start_cycle\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tsbtc_events: [\n\t\t\"amount\",\n\t\t\"bitcoin_txid\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"burn_hash\",\n\t\t\"burn_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"fee\",\n\t\t\"governance_contract_type\",\n\t\t\"governance_new_contract\",\n\t\t\"max_fee\",\n\t\t\"output_index\",\n\t\t\"recipient_btc_hashbytes\",\n\t\t\"recipient_btc_version\",\n\t\t\"request_id\",\n\t\t\"sender\",\n\t\t\"signer_address\",\n\t\t\"signer_aggregate_pubkey\",\n\t\t\"signer_bitmap\",\n\t\t\"signer_keys_count\",\n\t\t\"signer_threshold\",\n\t\t\"sweep_txid\",\n\t\t\"topic\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tsbtc_token_events: [\n\t\t\"amount\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"event_type\",\n\t\t\"memo\",\n\t\t\"recipient\",\n\t\t\"sender\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_name_events: [\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"bns_id\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"fqn\",\n\t\t\"hashed_salted_fqn_preorder\",\n\t\t\"imported_at\",\n\t\t\"name\",\n\t\t\"namespace\",\n\t\t\"owner\",\n\t\t\"preordered_by\",\n\t\t\"registered_at\",\n\t\t\"renewal_height\",\n\t\t\"stx_burn\",\n\t\t\"topic\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_namespace_events: [\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"launched_at\",\n\t\t\"lifetime\",\n\t\t\"manager\",\n\t\t\"manager_frozen\",\n\t\t\"manager_transfers_disabled\",\n\t\t\"namespace\",\n\t\t\"price_frozen\",\n\t\t\"price_function\",\n\t\t\"revealed_at\",\n\t\t\"status\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_marketplace_events: [\n\t\t\"action\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"bns_id\",\n\t\t\"canonical\",\n\t\t\"commission\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"price_ustx\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_names: [\n\t\t\"bns_id\",\n\t\t\"fqn\",\n\t\t\"last_event_at\",\n\t\t\"last_event_cursor\",\n\t\t\"name\",\n\t\t\"namespace\",\n\t\t\"owner\",\n\t\t\"registered_at\",\n\t\t\"renewal_height\",\n\t],\n\tbns_namespaces: [\n\t\t\"last_event_at\",\n\t\t\"last_event_cursor\",\n\t\t\"launched_at\",\n\t\t\"lifetime\",\n\t\t\"manager\",\n\t\t\"manager_frozen\",\n\t\t\"name_count\",\n\t\t\"namespace\",\n\t\t\"price_frozen\",\n\t],\n\tburn_block_rewards: [\n\t\t\"amount_sats\",\n\t\t\"burn_amount\",\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"recipient_btc\",\n\t\t\"reward_index\",\n\t],\n\tburn_block_reward_slots: [\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"holder_btc\",\n\t\t\"slot_index\",\n\t],\n\tevents: [\"block_height\", \"data\", \"event_index\", \"tx_id\", \"type\"],\n\tchain_reorgs: [\"detected_at\"],\n} as const satisfies {\n\treadonly [T in keyof Database]?: readonly (keyof Database[T])[];\n};\n",
10
10
  "/**\n * Instance modes for the Secondlayer platform.\n *\n * - `oss`: self-hosted, single-tenant. No auth middleware, no platform routes\n * (projects, admin). Everything runs against a single `DATABASE_URL`.\n * Intended for `docker compose up`.\n *\n * - `platform`: control-plane mode. Magic-link auth, API keys, projects,\n * admin. Serves the dashboard + CLI against a single shared DB. Post\n * 2026-05-14 shared-rip this also serves subgraphs + subscriptions.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\nconst VALID_MODES: readonly InstanceMode[] = [\"oss\", \"platform\"];\n\n/**\n * Resolve the active instance mode from `process.env.INSTANCE_MODE`.\n * Defaults to `\"oss\"` — the safest default for self-hosters who deploy\n * without setting the variable.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as InstanceMode;\n\t}\n\treturn \"oss\";\n}\n\n/** True when the active mode is `\"platform\"` (shared multi-tenant). */\nexport function isPlatformMode(): boolean {\n\treturn getInstanceMode() === \"platform\";\n}\n\n/** True when the active mode is `\"oss\"` (self-hosted). */\nexport function isOssMode(): boolean {\n\treturn getInstanceMode() === \"oss\";\n}\n",
11
11
  "import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport {\n\tappendFileSync,\n\tcloseSync,\n\texistsSync,\n\topenSync,\n\treadFileSync,\n\tunlinkSync,\n} from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { getInstanceMode } from \"../mode.ts\";\n\n/**\n * AES-256-GCM symmetric envelope for encrypted secrets at rest (tenant keys,\n * subscription signing secrets, etc.).\n *\n * Ciphertext layout: `iv (12 bytes) || authTag (16 bytes) || ciphertext`\n *\n * The key comes from `SECONDLAYER_SECRETS_KEY` — 32 bytes hex. In OSS mode,\n * if the env var is unset on first use we autogenerate a key and persist it\n * to `.env.local` in the current working directory so subsequent restarts\n * pick it up without user intervention. Dedicated/platform modes throw —\n * those runtimes must provision the key explicitly.\n *\n * Rotation strategy: re-encrypt all rows with the new key and swap the env\n * var. Not zero-downtime, but acceptable at v2 scale. For real KMS (AWS\n * KMS, Vault, GCP KMS), wrap the same byte layout behind an\n * `EncryptSecret`/`DecryptSecret` interface and swap at startup.\n */\n\nconst KEY_ENV = \"SECONDLAYER_SECRETS_KEY\";\nconst IV_LEN = 12;\nconst TAG_LEN = 16;\n\nfunction readExistingKey(envPath: string): string | null {\n\tif (!existsSync(envPath)) return null;\n\tconst contents = readFileSync(envPath, \"utf8\");\n\tconst match = contents.match(/^SECONDLAYER_SECRETS_KEY=([a-fA-F0-9]{64})/m);\n\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\treturn match ? match[1]! : null;\n}\n\n/**\n * Atomic file lock via `openSync(..., \"wx\")` — O_CREAT | O_EXCL. If two\n * processes race on cold-compose start, exactly one creates the lock\n * file; the loser polls until the winner finishes writing `.env.local`,\n * then reads the winner's key. Stale locks (process crashed mid-write)\n * are cleaned after `STALE_LOCK_MS`.\n */\nconst STALE_LOCK_MS = 10_000;\nconst POLL_MS = 25;\n\nfunction bootstrapOssKey(): string {\n\tconst envPath = resolve(process.cwd(), \".env.local\");\n\n\t// Fast path — key already on disk from a prior run.\n\tconst existing = readExistingKey(envPath);\n\tif (existing) {\n\t\tprocess.env[KEY_ENV] = existing;\n\t\treturn existing;\n\t}\n\n\tconst lockPath = `${envPath}.secret-bootstrap.lock`;\n\tlet lockFd: number | null = null;\n\ttry {\n\t\tlockFd = openSync(lockPath, \"wx\", 0o600);\n\t} catch (err) {\n\t\tconst e = err as NodeJS.ErrnoException;\n\t\tif (e.code !== \"EEXIST\") throw err;\n\t}\n\n\tif (lockFd === null) {\n\t\t// Another process is bootstrapping. Poll for its result.\n\t\tconst deadline = Date.now() + STALE_LOCK_MS;\n\t\twhile (Date.now() < deadline) {\n\t\t\tconst key = readExistingKey(envPath);\n\t\t\tif (key) {\n\t\t\t\tprocess.env[KEY_ENV] = key;\n\t\t\t\treturn key;\n\t\t\t}\n\t\t\tBun.sleepSync(POLL_MS);\n\t\t}\n\t\t// Lock holder died mid-write — force-clean and retry once.\n\t\ttry {\n\t\t\tunlinkSync(lockPath);\n\t\t} catch {}\n\t\treturn bootstrapOssKey();\n\t}\n\n\ttry {\n\t\tconst hex = randomBytes(32).toString(\"hex\");\n\t\tconst line = `${existsSync(envPath) ? \"\\n\" : \"\"}${KEY_ENV}=${hex}\\n`;\n\t\tappendFileSync(envPath, line, { mode: 0o600 });\n\t\tprocess.env[KEY_ENV] = hex;\n\t\tconsole.log(\n\t\t\t`[secondlayer] generated ${KEY_ENV}; saved to ${envPath} (mode 0600)`,\n\t\t);\n\t\treturn hex;\n\t} finally {\n\t\tcloseSync(lockFd);\n\t\ttry {\n\t\t\tunlinkSync(lockPath);\n\t\t} catch {}\n\t}\n}\n\nfunction loadKey(): Buffer {\n\tlet hex = process.env[KEY_ENV];\n\tif (!hex) {\n\t\tif (getInstanceMode() === \"oss\") {\n\t\t\thex = bootstrapOssKey();\n\t\t} else {\n\t\t\tthrow new Error(\n\t\t\t\t`${KEY_ENV} not set. Generate one with: openssl rand -hex 32`,\n\t\t\t);\n\t\t}\n\t}\n\tconst key = Buffer.from(hex, \"hex\");\n\tif (key.length !== 32) {\n\t\tthrow new Error(`${KEY_ENV} must be 32 bytes hex (got ${key.length})`);\n\t}\n\treturn key;\n}\n\nlet _cachedKey: Buffer | null = null;\nfunction getKey(): Buffer {\n\tif (!_cachedKey) _cachedKey = loadKey();\n\treturn _cachedKey;\n}\n\nexport function encryptSecret(plaintext: string): Buffer {\n\tconst key = getKey();\n\tconst iv = randomBytes(IV_LEN);\n\tconst cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(plaintext, \"utf8\"),\n\t\tcipher.final(),\n\t]);\n\tconst tag = cipher.getAuthTag();\n\treturn Buffer.concat([iv, tag, ciphertext]);\n}\n\nexport function decryptSecret(envelope: Buffer): string {\n\tconst key = getKey();\n\tconst iv = envelope.subarray(0, IV_LEN);\n\tconst tag = envelope.subarray(IV_LEN, IV_LEN + TAG_LEN);\n\tconst ciphertext = envelope.subarray(IV_LEN + TAG_LEN);\n\tconst decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n\tdecipher.setAuthTag(tag);\n\treturn decipher.update(ciphertext).toString(\"utf8\") + decipher.final(\"utf8\");\n}\n\n/** Generate a fresh 32-byte hex key suitable for `SECONDLAYER_SECRETS_KEY`. */\nexport function generateSecretsKey(): string {\n\treturn randomBytes(32).toString(\"hex\");\n}\n",
12
12
  "import { type Kysely, sql } from \"kysely\";\nimport type postgres from \"postgres\";\nimport { decryptSecret, encryptSecret } from \"../../crypto/secrets.ts\";\nimport { getDb, getRawClient, getRawClientFor, getTargetDb } from \"../index.ts\";\nimport { jsonb } from \"../jsonb.ts\";\nimport type { Database, Subgraph } from \"../types.ts\";\n\n/**\n * BYO data plane helpers. A subgraph's user-owned Postgres connection string is\n * stored encrypted at rest in `database_url_enc` (AES-GCM envelope). Plaintext\n * only exists transiently — at deploy (to encrypt) and at pool construction (to\n * connect). Never serialize it into API responses.\n */\nexport function encryptDatabaseUrl(url: string): Buffer {\n\treturn encryptSecret(url);\n}\n\n/** Decrypt a subgraph's BYO connection string, or null when managed. */\nexport function subgraphDatabaseUrl(subgraph: Subgraph): string | null {\n\treturn subgraph.database_url_enc\n\t\t? decryptSecret(subgraph.database_url_enc)\n\t\t: null;\n}\n\n/** True when the subgraph writes/serves from a user-owned DB. */\nexport function isByoSubgraph(subgraph: Subgraph): boolean {\n\treturn subgraph.database_url_enc != null;\n}\n\n/**\n * Resolve the Kysely instance a subgraph's data plane lives on: the user's DB\n * when BYO, else the managed target DB. Pools are cached by URL in db/index.ts.\n */\nexport function resolveSubgraphDb(subgraph: Subgraph): Kysely<Database> {\n\tconst url = subgraphDatabaseUrl(subgraph);\n\treturn url ? getDb(url) : getTargetDb();\n}\n\n/** Raw postgres.js client for a subgraph's data plane (DDL / serving queries). */\nexport function resolveSubgraphRawClient(\n\tsubgraph: Subgraph,\n): ReturnType<typeof postgres> {\n\tconst url = subgraphDatabaseUrl(subgraph);\n\treturn url ? getRawClientFor(url) : getRawClient(\"target\");\n}\n\n/**\n * Convert a subgraph name to its PostgreSQL schema name (legacy form).\n * Pre shared-rip every tenant DB had its own schema namespace so disambiguation\n * was implicit. Kept for oss mode (single-tenant) and legacy-row fallback.\n * Platform-mode deploys use `pgSchemaNameFor(accountId, name)`.\n */\nexport function pgSchemaName(subgraphName: string): string {\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${safeName}`;\n}\n\n/**\n * Account-scoped schema name. Matches migration 0028's rename pattern:\n * subgraph_{first8charsOfAccountId, dashes-as-underscores}_{name}\n * Empty accountId falls back to legacy form (oss mode).\n */\nexport function pgSchemaNameFor(\n\taccountId: string,\n\tsubgraphName: string,\n): string {\n\tif (!accountId) return pgSchemaName(subgraphName);\n\tconst accountPrefix = accountId.slice(0, 8).replace(/-/g, \"_\");\n\tconst safeName = subgraphName.replace(/-/g, \"_\");\n\treturn `subgraph_${accountPrefix}_${safeName}`;\n}\n\nexport async function registerSubgraph(\n\tdb: Kysely<Database>,\n\tdata: {\n\t\tname: string;\n\t\tversion: string;\n\t\tdefinition: Record<string, unknown>;\n\t\tschemaHash: string;\n\t\thandlerPath: string;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tstartBlock?: number;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\t/** BYO data plane: encrypted user-DB connection string, or null = managed. */\n\t\tdatabaseUrlEnc?: Buffer | null;\n\t},\n): Promise<Subgraph> {\n\treturn await db\n\t\t.insertInto(\"subgraphs\")\n\t\t.values({\n\t\t\tname: data.name,\n\t\t\tversion: data.version,\n\t\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\t\tschema_hash: data.schemaHash,\n\t\t\thandler_path: data.handlerPath,\n\t\t\taccount_id: data.accountId ?? \"\",\n\t\t\thandler_code: data.handlerCode ?? null,\n\t\t\tsource_code: data.sourceCode ?? null,\n\t\t\tschema_name: data.schemaName ?? null,\n\t\t\tstart_block: data.startBlock ?? 0,\n\t\t\tdatabase_url_enc: data.databaseUrlEnc ?? null,\n\t\t})\n\t\t.onConflict((oc) =>\n\t\t\toc.columns([\"name\", \"account_id\"]).doUpdateSet({\n\t\t\t\tversion: data.version,\n\t\t\t\tdefinition: jsonb<Record<string, unknown>>(data.definition),\n\t\t\t\tschema_hash: data.schemaHash,\n\t\t\t\thandler_path: data.handlerPath,\n\t\t\t\thandler_code: data.handlerCode ?? null,\n\t\t\t\tsource_code: data.sourceCode ?? null,\n\t\t\t\tschema_name: data.schemaName ?? null,\n\t\t\t\tstart_block: data.startBlock ?? 0,\n\t\t\t\tdatabase_url_enc: data.databaseUrlEnc ?? null,\n\t\t\t\tupdated_at: new Date(),\n\t\t\t}),\n\t\t)\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n}\n\nexport async function getSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll().where(\"name\", \"=\", name);\n\n\tif (accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\n\treturn (await query.executeTakeFirst()) ?? null;\n}\n\nexport async function listSubgraphs(\n\tdb: Kysely<Database>,\n\taccountId?: string,\n): Promise<Subgraph[]> {\n\tlet query = db.selectFrom(\"subgraphs\").selectAll();\n\tif (accountId !== undefined) {\n\t\tquery = query.where(\"account_id\", \"=\", accountId);\n\t}\n\treturn query.execute();\n}\n\nexport async function updateSubgraphStatus(\n\tdb: Kysely<Database>,\n\tname: string,\n\tstatus: string,\n\tlastProcessedBlock?: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\tstatus,\n\t\t\t...(lastProcessedBlock !== undefined\n\t\t\t\t? { last_processed_block: lastProcessedBlock }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function recordSubgraphProcessed(\n\tdb: Kysely<Database>,\n\tname: string,\n\tprocessed: number,\n\terrors: number,\n\tlastError?: string,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\ttotal_processed: sql`total_processed + ${processed}`,\n\t\t\ttotal_errors: sql`total_errors + ${errors}`,\n\t\t\t...(lastError\n\t\t\t\t? { last_error: lastError, last_error_at: new Date() }\n\t\t\t\t: {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function updateSubgraphHandlerPath(\n\tdb: Kysely<Database>,\n\tname: string,\n\thandlerPath: string,\n\topts?: { handlerCode?: string; sourceCode?: string },\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"subgraphs\")\n\t\t.set({\n\t\t\thandler_path: handlerPath,\n\t\t\t...(opts?.handlerCode != null ? { handler_code: opts.handlerCode } : {}),\n\t\t\t...(opts?.sourceCode != null ? { source_code: opts.sourceCode } : {}),\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"name\", \"=\", name)\n\t\t.execute();\n}\n\nexport async function deleteSubgraph(\n\tdb: Kysely<Database>,\n\tname: string,\n\taccountId?: string,\n): Promise<Subgraph | null> {\n\tconst subgraph = await getSubgraph(db, name, accountId);\n\tif (!subgraph) return null;\n\n\t// Use stored schema_name if available, otherwise compute\n\tconst schemaName = subgraph.schema_name ?? pgSchemaName(name);\n\n\t// Cascade to subscriptions: a subscription pointing at a deleted\n\t// subgraph + table will throw `relation does not exist` on every\n\t// subsequent emission. Pause active subs and purge any pending outbox\n\t// rows so receivers don't get phantom replays. We don't delete the\n\t// subscriptions themselves — operators may want to repoint them at a\n\t// resurrected subgraph; we just stop them firing.\n\tawait db\n\t\t.updateTable(\"subscriptions\")\n\t\t.set({\n\t\t\tstatus: \"paused\",\n\t\t\tlast_error: `Subgraph \"${name}\" deleted; subscription auto-paused.`,\n\t\t\tupdated_at: new Date(),\n\t\t})\n\t\t.where(\"subgraph_name\", \"=\", name)\n\t\t.execute();\n\tawait db\n\t\t.deleteFrom(\"subscription_outbox\")\n\t\t.where(\"status\", \"=\", \"pending\")\n\t\t.where(\"subscription_id\", \"in\", (qb) =>\n\t\t\tqb\n\t\t\t\t.selectFrom(\"subscriptions\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"subgraph_name\", \"=\", name),\n\t\t)\n\t\t.execute();\n\n\t// Drop the subgraph's schema (CASCADE drops all tables within). For BYO the\n\t// schema lives in the user's DB — we deliberately do NOT connect there to\n\t// drop their data on delete; deleting the subgraph just removes our registry\n\t// row (and, with it, the encrypted connection) + pauses subscriptions. The\n\t// user drops the schema themselves if they want it gone.\n\tif (!isByoSubgraph(subgraph)) {\n\t\tawait sql`DROP SCHEMA IF EXISTS ${sql.raw(`\"${schemaName}\"`)} CASCADE`.execute(\n\t\t\tdb,\n\t\t);\n\t}\n\n\t// Remove from registry (the inline database_url_enc envelope goes with it)\n\tawait db.deleteFrom(\"subgraphs\").where(\"id\", \"=\", subgraph.id).execute();\n\n\treturn subgraph;\n}\n"
13
13
  ],
14
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAGA,IAAM,iBAAiB,EAAE,OAAO,EAAE,UAAU,CAAC,QAAQ;AAAA,EACpD,MAAM,WAAW,IACf,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,OAAO;AAAA,EAChB,MAAM,QAAQ,CAAC,WAAW,SAAS;AAAA,EACnC,WAAW,KAAK,UAAU;AAAA,IACzB,IAAI,CAAC,MAAM,SAAS,CAAC,GAAG;AAAA,MACvB,MAAM,IAAI,MACT,oBAAoB,sBAAsB,MAAM,KAAK,IAAI,GAC1D;AAAA,IACD;AAAA,EACD;AAAA,EACA,OAAO;AAAA,CACP;AAsBD,IAAM,YAAwC,EAAE,OAAO;AAAA,EACtD,cAAc,EAAE,WACf,CAAC,QAAS,OAAO,QAAQ,YAAY,IAAI,WAAW,IAAI,YAAY,KACpE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAC3B;AAAA,EACA,qBAAqB,EAAE,WACtB,CAAC,QAAS,OAAO,QAAQ,YAAY,IAAI,WAAW,IAAI,YAAY,KACpE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAC3B;AAAA,EACA,qBAAqB,EAAE,WACtB,CAAC,QAAS,OAAO,QAAQ,YAAY,IAAI,WAAW,IAAI,YAAY,KACpE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAC3B;AAAA,EACA,SAAS,EAAE,KAAK,CAAC,WAAW,SAAS,CAAC,EAAE,SAAS;AAAA,EACjD,UAAU,eAAe,SAAS;AAAA,EAClC,WAAW,EAAE,KAAK,CAAC,SAAS,QAAQ,QAAQ,OAAO,CAAC,EA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AAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,aAAa;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,mBAAmB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,iBAAiB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,sBAAsB;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,wBAAwB;AAAA,IAC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,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,aAAa;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,mBAAmB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,iBAAiB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,sBAAsB;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD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-23,6 +23,10 @@ function defaultInternalIndexApiKey() {
23
23
 
24
24
  // src/index-http.ts
25
25
  var PAGE_LIMIT = 1000;
26
+ var MAX_ATTEMPTS = 4;
27
+ var RETRY_BASE_MS = 150;
28
+ var RETRYABLE_STATUS = new Set([502, 503, 504]);
29
+ var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
26
30
 
27
31
  class IndexHttpClient {
28
32
  indexBaseUrl;
@@ -36,13 +40,32 @@ class IndexHttpClient {
36
40
  this.streamsApiKey = opts.streamsApiKey;
37
41
  }
38
42
  async get(url, apiKey) {
39
- const res = await fetch(url, {
40
- headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {}
41
- });
42
- if (!res.ok) {
43
- throw new Error(`GET ${url} → ${res.status} ${await res.text()}`);
43
+ const headers = apiKey ? { authorization: `Bearer ${apiKey}` } : {};
44
+ let lastErr;
45
+ for (let attempt = 1;attempt <= MAX_ATTEMPTS; attempt++) {
46
+ let res;
47
+ try {
48
+ res = await fetch(url, { headers });
49
+ } catch (err) {
50
+ if (err instanceof Error && err.name === "AbortError")
51
+ throw err;
52
+ lastErr = err;
53
+ if (attempt >= MAX_ATTEMPTS)
54
+ break;
55
+ await delay(RETRY_BASE_MS * 2 ** (attempt - 1));
56
+ continue;
57
+ }
58
+ if (!res.ok) {
59
+ if (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {
60
+ await res.text().catch(() => {});
61
+ await delay(RETRY_BASE_MS * 2 ** (attempt - 1));
62
+ continue;
63
+ }
64
+ throw new Error(`GET ${url} → ${res.status} ${await res.text()}`);
65
+ }
66
+ return await res.json();
44
67
  }
45
- return await res.json();
68
+ throw lastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`);
46
69
  }
47
70
  async getPage(path, key, params) {
48
71
  const env = await this.get(`${this.indexBaseUrl}${path}?${params}`, this.indexApiKey);
@@ -106,5 +129,5 @@ export {
106
129
  IndexHttpClient
107
130
  };
108
131
 
109
- //# debugId=D7EA6E24A653E5AE64756E2164756E21
132
+ //# debugId=4028B89AE919612464756E2164756E21
110
133
  //# sourceMappingURL=index-http.js.map
@@ -3,9 +3,9 @@
3
3
  "sources": ["../src/index-internal-auth.ts", "../src/index-http.ts"],
4
4
  "sourcesContent": [
5
5
  "// Internal service credential for first-party consumers of /v1/index over HTTP\n// (e.g. the subgraph processor's PublicApiBlockSource). Seeded into the Index\n// token store as an enterprise tenant with NO account_id, so these reads are\n// unmetered (Index metering gates on account_id). Mirrors the Streams internal\n// key (packages/indexer/src/l2/internal-auth.ts). Lives in shared so both the\n// API (seed) and the subgraph processor (consumer) import it without a cycle.\nexport const INDEX_INTERNAL_TENANT_ID = \"tenant_index_internal\";\n\nconst DEFAULT_INDEX_INTERNAL_API_KEY = \"sk-sl_index_internal\";\n\nexport function defaultInternalIndexApiKey(): string {\n\treturn process.env.INDEX_INTERNAL_API_KEY || DEFAULT_INDEX_INTERNAL_API_KEY;\n}\n",
6
- "import { defaultInternalIndexApiKey } from \"./index-internal-auth.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\tevent_index: number;\n\tcontract_id: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\nexport type StreamsReorgRow = {\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Defaults to the internal enterprise key. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams (internal enterprise key). */\n\tstreamsApiKey: string;\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst res = await fetch(url, {\n\t\t\theaders: apiKey ? { authorization: `Bearer ${apiKey}` } : {},\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`GET ${url} → ${res.status} ${await res.text()}`);\n\t\t}\n\t\treturn (await res.json()) as T;\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{ event_type: eventType },\n\t\t);\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t */\n\tasync getIndexTip(): Promise<number> {\n\t\tconst env = await this.get<{ tip: { block_height: number } }>(\n\t\t\t`${this.indexBaseUrl}/v1/index/blocks?limit=1`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). */\n\tasync listReorgs(\n\t\tsince: string,\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n"
6
+ "import { defaultInternalIndexApiKey } from \"./index-internal-auth.ts\";\n\n/**\n * Low-level transport for the public Index (`/v1/index`) + Streams clock\n * (`/v1/streams`) HTTP APIs: cursor-paginated reads, tip, reorgs. Lives in\n * `shared` (a leaf both the SDK and the subgraph runtime depend on) so the wire\n * format has one home and no package cycle. The SDK's ergonomic client should\n * eventually consume these row types too (see the plan's convergence task).\n *\n * This is intentionally minimal — just the GETs the subgraph runtime's\n * PublicApiBlockSource needs. It is NOT the SDK's full client (walk/consume/\n * retries/auth resolution).\n */\n\nconst PAGE_LIMIT = 1000;\n\n// Transport resilience for the streams-index data plane. The api runs N>1\n// replicas behind Caddy; during a rolling deploy one replica is briefly\n// unreachable, surfacing as a thrown fetch (connection refused/reset) or a\n// Caddy 502/503/504 while it fails over. Retrying a few times with backoff\n// makes a single-replica recreate transparent to the subgraph-processor /\n// l2-decoder — closing the processors-depend-on-api coupling.\nconst MAX_ATTEMPTS = 4;\nconst RETRY_BASE_MS = 150;\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\nconst delay = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => setTimeout(resolve, ms));\n\ntype Envelope<K extends string, T> = {\n\t[P in K]: T[];\n} & { next_cursor: string | null };\n\n// ── Index API wire shapes (single source of truth) ─────────────────────────\nexport type IndexBlockRow = {\n\tblock_height: number;\n\tblock_hash: string;\n\tparent_hash: string;\n\tburn_block_height: number;\n\tburn_block_hash: string | null;\n\tblock_time: string | null;\n};\n\ntype IndexEventCommon = {\n\tblock_height: number;\n\ttx_id: string;\n\tevent_index: number;\n\tcontract_id: string | null;\n};\n\nexport type IndexEventRow = IndexEventCommon &\n\t(\n\t\t| {\n\t\t\t\tevent_type: \"ft_transfer\" | \"ft_mint\" | \"ft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"nft_transfer\" | \"nft_mint\" | \"nft_burn\";\n\t\t\t\tasset_identifier: string;\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tvalue: string;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_transfer\" | \"stx_mint\" | \"stx_burn\";\n\t\t\t\tsender?: string;\n\t\t\t\trecipient?: string;\n\t\t\t\tamount: string;\n\t\t\t\tmemo?: string | null;\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"stx_lock\";\n\t\t\t\tsender: string;\n\t\t\t\tamount: string;\n\t\t\t\tpayload: { unlock_height: string | null };\n\t\t }\n\t\t| {\n\t\t\t\tevent_type: \"print\";\n\t\t\t\tpayload: {\n\t\t\t\t\ttopic: string | null;\n\t\t\t\t\tvalue: unknown;\n\t\t\t\t\traw_value: string | null;\n\t\t\t\t};\n\t\t }\n\t);\n\nexport type IndexTransactionRow = {\n\ttx_id: string;\n\tblock_height: number;\n\tblock_time?: string | null;\n\tburn_block_height?: number | null;\n\ttx_index: number;\n\ttx_type: string;\n\tsender: string;\n\tstatus: string;\n\tcontract_call?: {\n\t\tcontract_id: string;\n\t\tfunction_name: string;\n\t\tfunction_args_hex?: string[] | null;\n\t\tresult_hex?: string | null;\n\t} | null;\n\tsmart_contract?: { contract_id: string | null } | null;\n};\n\nexport type StreamsReorgRow = {\n\tdetected_at: string;\n\tfork_point_height: number;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n};\n\nexport type IndexHttpOptions = {\n\t/** Base URL for /v1/index (the decoded data plane). */\n\tindexBaseUrl: string;\n\t/** Bearer for /v1/index. Defaults to the internal enterprise key. */\n\tindexApiKey?: string;\n\t/** Base URL for /v1/streams (the canonical clock). */\n\tstreamsBaseUrl: string;\n\t/** Bearer for /v1/streams (internal enterprise key). */\n\tstreamsApiKey: string;\n};\n\nexport class IndexHttpClient {\n\tprivate readonly indexBaseUrl: string;\n\tprivate readonly indexApiKey: string;\n\tprivate readonly streamsBaseUrl: string;\n\tprivate readonly streamsApiKey: string;\n\n\tconstructor(opts: IndexHttpOptions) {\n\t\tthis.indexBaseUrl = opts.indexBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.indexApiKey = opts.indexApiKey ?? defaultInternalIndexApiKey();\n\t\tthis.streamsBaseUrl = opts.streamsBaseUrl.replace(/\\/+$/, \"\");\n\t\tthis.streamsApiKey = opts.streamsApiKey;\n\t}\n\n\tprivate async get<T>(url: string, apiKey: string): Promise<T> {\n\t\t// Index reads are anon — omit the header entirely when no key is set, so\n\t\t// an empty key reads anonymously rather than 401-ing as an invalid bearer.\n\t\tconst headers: Record<string, string> = apiKey\n\t\t\t? { authorization: `Bearer ${apiKey}` }\n\t\t\t: {};\n\t\tlet lastErr: unknown;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\tlet res: Response;\n\t\t\ttry {\n\t\t\t\tres = await fetch(url, { headers });\n\t\t\t} catch (err) {\n\t\t\t\t// An explicit abort/cancel is intentional — surface it immediately\n\t\t\t\t// rather than burning the retry budget masking it as transient.\n\t\t\t\tif (err instanceof Error && err.name === \"AbortError\") throw err;\n\t\t\t\t// Otherwise a transport-level failure (connection refused/reset) —\n\t\t\t\t// e.g. an api replica mid-recreate. Retry; the next attempt\n\t\t\t\t// round-robins to a healthy replica.\n\t\t\t\tlastErr = err;\n\t\t\t\tif (attempt >= MAX_ATTEMPTS) break;\n\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!res.ok) {\n\t\t\t\tif (RETRYABLE_STATUS.has(res.status) && attempt < MAX_ATTEMPTS) {\n\t\t\t\t\t// Drain the body so the connection can be reused, then back off.\n\t\t\t\t\tawait res.text().catch(() => {});\n\t\t\t\t\tawait delay(RETRY_BASE_MS * 2 ** (attempt - 1));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow new Error(`GET ${url} → ${res.status} ${await res.text()}`);\n\t\t\t}\n\t\t\treturn (await res.json()) as T;\n\t\t}\n\t\tthrow (\n\t\t\tlastErr ?? new Error(`GET ${url} failed after ${MAX_ATTEMPTS} attempts`)\n\t\t);\n\t}\n\n\t/** Fetch a single cursor page of an Index collection. */\n\tprivate async getPage<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tparams: URLSearchParams,\n\t): Promise<{ items: T[]; next_cursor: string | null }> {\n\t\tconst env: Envelope<K, T> = await this.get(\n\t\t\t`${this.indexBaseUrl}${path}?${params}`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn { items: env[key], next_cursor: env.next_cursor };\n\t}\n\n\t/** Drain a cursor-paginated Index collection over [fromHeight, toHeight]. */\n\tprivate async walk<K extends string, T>(\n\t\tpath: string,\n\t\tkey: K,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t\textraParams: Record<string, string> = {},\n\t): Promise<T[]> {\n\t\tconst out: T[] = [];\n\t\tlet cursor: string | null = null;\n\t\tdo {\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tto_height: String(toHeight),\n\t\t\t\tlimit: String(PAGE_LIMIT),\n\t\t\t\t...extraParams,\n\t\t\t});\n\t\t\t// from_height and cursor are mutually exclusive — anchor the first page\n\t\t\t// by height, then page forward by cursor only.\n\t\t\tif (cursor) params.set(\"cursor\", cursor);\n\t\t\telse params.set(\"from_height\", String(fromHeight));\n\t\t\tconst { items, next_cursor } = await this.getPage<K, T>(\n\t\t\t\tpath,\n\t\t\t\tkey,\n\t\t\t\tparams,\n\t\t\t);\n\t\t\tout.push(...items);\n\t\t\tcursor = next_cursor;\n\t\t} while (cursor);\n\t\treturn out;\n\t}\n\n\t/**\n\t * Fetch ONE page of contract-call transactions filtered to `contractId`.\n\t * Unlike walk(), this does NOT drain — the caller pages by feeding back\n\t * next_cursor — so a sparse high-volume filter (e.g. a single contract over\n\t * all history) costs one request per batch, not O(all-history) per tick.\n\t * `cursor` is exclusive (rows strictly after it); on the first call pass\n\t * `fromHeight` to anchor the backfill start instead.\n\t */\n\tasync fetchContractCalls(\n\t\tcontractId: string,\n\t\topts: {\n\t\t\ttoHeight: number;\n\t\t\tcursor?: string | null;\n\t\t\tfromHeight?: number;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<{\n\t\ttransactions: IndexTransactionRow[];\n\t\tnext_cursor: string | null;\n\t}> {\n\t\tconst params = new URLSearchParams({\n\t\t\tto_height: String(opts.toHeight),\n\t\t\tlimit: String(opts.limit ?? PAGE_LIMIT),\n\t\t\tcontract_id: contractId,\n\t\t});\n\t\tif (opts.cursor) params.set(\"cursor\", opts.cursor);\n\t\telse params.set(\"from_height\", String(opts.fromHeight ?? 0));\n\t\tconst { items, next_cursor } = await this.getPage<\n\t\t\t\"transactions\",\n\t\t\tIndexTransactionRow\n\t\t>(\"/v1/index/transactions\", \"transactions\", params);\n\t\treturn { transactions: items, next_cursor };\n\t}\n\n\twalkBlocks(fromHeight: number, toHeight: number): Promise<IndexBlockRow[]> {\n\t\treturn this.walk<\"blocks\", IndexBlockRow>(\n\t\t\t\"/v1/index/blocks\",\n\t\t\t\"blocks\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\twalkEvents(\n\t\teventType: string,\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexEventRow[]> {\n\t\treturn this.walk<\"events\", IndexEventRow>(\n\t\t\t\"/v1/index/events\",\n\t\t\t\"events\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t\t{ event_type: eventType },\n\t\t);\n\t}\n\n\twalkTransactions(\n\t\tfromHeight: number,\n\t\ttoHeight: number,\n\t): Promise<IndexTransactionRow[]> {\n\t\treturn this.walk<\"transactions\", IndexTransactionRow>(\n\t\t\t\"/v1/index/transactions\",\n\t\t\t\"transactions\",\n\t\t\tfromHeight,\n\t\t\ttoHeight,\n\t\t);\n\t}\n\n\t/** Canonical tip height from the Streams clock. */\n\tasync getStreamsTip(): Promise<number> {\n\t\tconst tip = await this.get<{ block_height: number }>(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/tip`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t\treturn Number(tip.block_height) || 0;\n\t}\n\n\t/**\n\t * Highest block height the Index data plane can serve (tip is inline in every\n\t * envelope). This is the data-availability bound — a consumer must not\n\t * process past it, even if the Streams clock is ahead.\n\t */\n\tasync getIndexTip(): Promise<number> {\n\t\tconst env = await this.get<{ tip: { block_height: number } }>(\n\t\t\t`${this.indexBaseUrl}/v1/index/blocks?limit=1`,\n\t\t\tthis.indexApiKey,\n\t\t);\n\t\treturn Number(env.tip?.block_height) || 0;\n\t}\n\n\t/** Reorgs since a resume token (wall-clock `detected_at`-keyed). */\n\tasync listReorgs(\n\t\tsince: string,\n\t): Promise<{ reorgs: StreamsReorgRow[]; next_since: string | null }> {\n\t\tconst params = new URLSearchParams({ since });\n\t\treturn this.get(\n\t\t\t`${this.streamsBaseUrl}/v1/streams/reorgs?${params}`,\n\t\t\tthis.streamsApiKey,\n\t\t);\n\t}\n}\n"
7
7
  ],
8
- "mappings": ";;;;;;;;;;;;;;;;;AAMO,IAAM,2BAA2B;AAExC,IAAM,iCAAiC;AAEhC,SAAS,0BAA0B,GAAW;AAAA,EACpD,OAAO,QAAQ,IAAI,0BAA0B;AAAA;;;ACG9C,IAAM,aAAa;AAAA;AAkGZ,MAAM,gBAAgB;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,WAAW,CAAC,MAAwB;AAAA,IACnC,KAAK,eAAe,KAAK,aAAa,QAAQ,QAAQ,EAAE;AAAA,IACxD,KAAK,cAAc,KAAK,eAAe,2BAA2B;AAAA,IAClE,KAAK,iBAAiB,KAAK,eAAe,QAAQ,QAAQ,EAAE;AAAA,IAC5D,KAAK,gBAAgB,KAAK;AAAA;AAAA,OAGb,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QAAQ,OAAO,gBAAgB,MAAM,KAAK,QAGxC,0BAA0B,gBAAgB,MAAM;AAAA,IAClD,OAAO,EAAE,cAAc,OAAO,YAAY;AAAA;AAAA,EAG3C,UAAU,CAAC,YAAoB,UAA4C;AAAA,IAC1E,OAAO,KAAK,KACX,oBACA,UACA,YACA,QACD;AAAA;AAAA,EAGD,UAAU,CACT,WACA,YACA,UAC2B;AAAA,IAC3B,OAAO,KAAK,KACX,oBACA,UACA,YACA,UACA,EAAE,YAAY,UAAU,CACzB;AAAA;AAAA,EAGD,gBAAgB,CACf,YACA,UACiC;AAAA,IACjC,OAAO,KAAK,KACX,0BACA,gBACA,YACA,QACD;AAAA;AAAA,OAIK,cAAa,GAAoB;AAAA,IACtC,MAAM,MAAM,MAAM,KAAK,IACtB,GAAG,KAAK,iCACR,KAAK,aACN;AAAA,IACA,OAAO,OAAO,IAAI,YAAY,KAAK;AAAA;AAAA,OAQ9B,YAAW,GAAoB;AAAA,IACpC,MAAM,MAAM,MAAM,KAAK,IACtB,GAAG,KAAK,wCACR,KAAK,WACN;AAAA,IACA,OAAO,OAAO,IAAI,KAAK,YAAY,KAAK;AAAA;AAAA,OAInC,WAAU,CACf,OACoE;AAAA,IACpE,MAAM,SAAS,IAAI,gBAAgB,EAAE,MAAM,CAAC;AAAA,IAC5C,OAAO,KAAK,IACX,GAAG,KAAK,oCAAoC,UAC5C,KAAK,aACN;AAAA;AAEF;",
9
+ "debugId": "4028B89AE919612464756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -975,12 +975,40 @@ declare const SOURCE_READ_COLUMNS: {
975
975
  readonly events: readonly ["block_height", "data", "event_index", "tx_id", "type"]
976
976
  readonly chain_reorgs: readonly ["detected_at"]
977
977
  };
978
+ interface DbSplitStatus {
979
+ /** "split" when source/target resolve to different DBs, else "single". */
980
+ mode: "split" | "single";
981
+ /** True when the chain/control split is live (distinct DBs). */
982
+ active: boolean;
983
+ /** SOURCE host[:port]/dbname (no credentials). */
984
+ sourceDb: string;
985
+ /** TARGET host[:port]/dbname (no credentials). */
986
+ targetDb: string;
987
+ }
978
988
  /**
979
- * Boot guard: if the chain/control split is requested (`SOURCE_DATABASE_URL` or
980
- * `TARGET_DATABASE_URL` set) but both still resolve to the same DB a typo, or
981
- * a stray `DATABASE_URL` masking the intentthe split silently collapses and
982
- * chain + control plane share one instance. Surface it loudly. Fail-soft (no
983
- * throw) so a misconfig doesn't brick startup; logs make it obvious.
989
+ * Resolved source/target DB identity for status/health surfaces. Lets operators
990
+ * see whether the chain/control split is live or dormant (collapsed to one DB)
991
+ * without shelling in. Credentials are never exposed host/db only.
992
+ *
993
+ * `active` is a STRING-IDENTITY check on the two URLs: it can't catch two
994
+ * distinct URLs that alias the same physical instance (e.g. `postgres` vs
995
+ * `127.0.0.1`, or a swapped/wrong host). Treat `active: true` as "configured
996
+ * for split", not a proof of physical isolation.
997
+ */
998
+ declare function getDbSplitStatus(): DbSplitStatus;
999
+ /**
1000
+ * Boot guard for the chain/control DB split. Surfaces three misconfigurations
1001
+ * loudly (fail-soft — logs, never throws, so a misconfig can't brick startup):
1002
+ *
1003
+ * 1. Silent wrong-DB: a split is requested (one of SOURCE_/TARGET_ set) but
1004
+ * `DATABASE_URL` is absent (the split-prod default) and the OTHER var is
1005
+ * unset, so it falls through to the built-in dev `DEFAULT_URL` — about to
1006
+ * read/write a real-but-wrong database. This is the failure mode the
1007
+ * remove-DATABASE_URL decision creates; catch it.
1008
+ * 2. Collapsed split: both vars set but resolve to the same DB (typo, or a
1009
+ * stray `DATABASE_URL` masking the intent).
1010
+ * 3. Dormant split (prod only): neither var set, so all services share one
1011
+ * Postgres failure domain. Not an error, but no longer silent.
984
1012
  */
985
1013
  declare function assertDbSplit(): void;
986
1014
  /**
@@ -1715,4 +1743,4 @@ declare function publicKeyPemFromPrivate(privateKeyPem: string): string;
1715
1743
  declare function ed25519KeyId(publicKeyPem: string): string;
1716
1744
  declare function signEd25519(payload: string, privateKey: KeyObject): string;
1717
1745
  declare function verifyEd25519(payload: string, signatureBase64: string, publicKey: KeyObject): boolean;
1718
- export { validateSubscriptionFilterForTable, sql, parseJsonb, logger, jsonb, isPox4DecoderEnabled, getTargetDb, getSourceDb, getRawClientFor, getRawClient, getErrorMessage, getEnv, getDb, generateSubgraphSpec, generateSubgraphOpenApi, generateSubgraphMarkdown, generateSubgraphAgentSchema, formatSubscriptionSchemaErrors, finalizedBurnHeight, encodeStreamsCursor, exports_ed25519 as ed25519, decodeStreamsCursor, exports_hmac as crypto, closeDb, assertDbSplit, VersionConflictError, ValidationError, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateTransaction, UpdateTenantUsageMonthly, UpdateTenantComputeAddon, UpdateTenant, UpdateSubscriptionRequestSchema, UpdateSubscriptionRequest, UpdateSubscriptionOutbox, UpdateSubscription, UpdateSubgraphOperation, UpdateSubgraph, UpdateProject, UpdateIndexProgress, UpdateEvent, UpdateContract, UpdateChatSession, UpdateBlock, UpdateApiKey, UpdateAccountSpendCap, TriggerEvaluatorStateTable, TriggerEvaluatorState, TransactionsTable, TransactionsArchiveTable, Transaction, TenantsTable, TenantUsageMonthlyTable, TenantUsageMonthly, TenantSuspendedError, TenantStatus, TenantComputeAddonsTable, TenantComputeAddon, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubscriptionsTable, SubscriptionSummary, SubscriptionStatusSchema, SubscriptionStatus, SubscriptionSchemaTables, SubscriptionSchemaTable, SubscriptionSchemaColumn, SubscriptionRuntimeSchema, SubscriptionRuntime, SubscriptionOutboxTable, SubscriptionOutbox, SubscriptionKind, SubscriptionFormatSchema, SubscriptionFormat, SubscriptionFilterSchema, SubscriptionFilterPrimitiveSchema, SubscriptionFilterPrimitive, SubscriptionFilterOperatorSchema, SubscriptionFilterOperator, SubscriptionFilterClauseSchema, SubscriptionFilterClause, SubscriptionFilter, SubscriptionDetail, SubscriptionDelivery, SubscriptionDeliveriesTable, Subscription, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphSyncInfo, SubgraphSummary, SubgraphSpecOptions, SubgraphSpecFormat, SubgraphResourceWarning, SubgraphQueryParams, SubgraphProcessingStatsTable, SubgraphOperationsTable, SubgraphOperationStatus, SubgraphOperationKind, SubgraphOperation, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGapsResponse, SubgraphGapRange, SubgraphGapEntry, SubgraphGap, SubgraphDetail, SubgraphAgentSchema, Subgraph, StxTransferFilterSchema, StxTransferFilter, StxMintFilterSchema, StxMintFilter, StxLockFilterSchema, StxLockFilter, StxBurnFilterSchema, StxBurnFilter, StreamsEventType, StreamsDbEventType, StreamsCursor, SessionsTable, Session, ServiceHeartbeatsTable, SecondLayerError, SbtcTokenEventsTable, SbtcTokenEventType, SbtcSupplySnapshotsTable, SbtcEventsTable, SbtcEventTopic, SUBSCRIPTION_STATUSES, SUBSCRIPTION_RUNTIMES, SUBSCRIPTION_FORMATS, SUBSCRIPTION_FILTER_OPERATORS, STREAMS_TO_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_DB_EVENT_TYPES, SOURCE_READ_COLUMNS, RotateSecretResponse, ReplaySubscriptionRequestSchema, ReplaySubscriptionRequest, ReplayResult, ReindexResponse, RateLimitError, ProvisioningAuditStatus, ProvisioningAuditLogTable, ProvisioningAuditLog, ProvisioningAuditEvent, ProjectsTable, Project, ProcessedStripeEventsTable, PrintEventFilterSchema, PrintEventFilter, Pox4SignersDailyTable, Pox4FunctionName, Pox4CyclesDailyTable, Pox4CallsTable, ParsedUpdateSubscriptionRequest, ParsedReplaySubscriptionRequest, ParsedCreateSubscriptionRequest, OutboxStatus, NumericAsText, NotFoundError, NftTransferFilterSchema, NftTransferFilter, NftMintFilterSchema, NftMintFilter, NftBurnFilterSchema, NftBurnFilter, MempoolTransactionsTable, MempoolTransaction, MagicLinksTable, MagicLink, L2DecoderCheckpointsTable, KeyRotatedError, InsertTransaction, InsertTenantUsageMonthly, InsertTenantComputeAddon, InsertTenant, InsertTeamMember, InsertTeamInvitation, InsertSubscriptionOutbox, InsertSubscriptionDelivery, InsertSubscription, InsertSubgraphUsageDaily, InsertSubgraphOperation, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProvisioningAuditLog, InsertProject, InsertMempoolTransaction, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertContract, InsertChatSession, InsertChatMessage, InsertBlock, InsertApiKey, InsertAccountSpendCap, InsertAccountInsight, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, FtTransferFilterSchema, FtTransferFilter, FtMintFilterSchema, FtMintFilter, FtBurnFilterSchema, FtBurnFilter, ForbiddenError, EventsTable, EventsArchiveTable, EventFilterSchema, EventFilter, Event, ErrorCodes, ErrorCode, Env, EMPTY_RANGE_EVENT_INDEX_SENTINEL, DeploySubgraphResponse, DeploySubgraphRequestSchema, DeploySubgraphRequest, DeliveryRow, DecodedEventsTable, DecodedEventType, DeadRow, DeadLetterEventsTable, DbReadRow, DatabaseError, Database, DEFAULT_BTC_CONFIRMATIONS, DECODED_EVENT_TYPES, DB_TO_STREAMS_EVENT_TYPE, CreateSubscriptionResponse, CreateSubscriptionRequestSchema, CreateSubscriptionRequest, ContractsTable, ContractDeployFilterSchema, ContractDeployFilter, ContractCallFilterSchema, ContractCallFilter, Contract, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, ChainReorgsTable, CODE_TO_STATUS, CHAIN_TRIGGER_TYPES, BurnBlockRewardsTable, BurnBlockRewardSlotsTable, BnsNamespacesTable, BnsNamespaceEventsTable, BnsNamespaceEventStatus, BnsNamesTable, BnsNameEventsTable, BnsNameEventTopic, BnsMarketplaceEventsTable, BnsMarketplaceAction, BlocksTable, Block, AuthorizationError, AuthenticationError, ApiKeysTable, ApiKey, AccountsTable, AccountSpendCapsTable, AccountSpendCap, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
1746
+ export { validateSubscriptionFilterForTable, sql, parseJsonb, logger, jsonb, isPox4DecoderEnabled, getTargetDb, getSourceDb, getRawClientFor, getRawClient, getErrorMessage, getEnv, getDbSplitStatus, getDb, generateSubgraphSpec, generateSubgraphOpenApi, generateSubgraphMarkdown, generateSubgraphAgentSchema, formatSubscriptionSchemaErrors, finalizedBurnHeight, encodeStreamsCursor, exports_ed25519 as ed25519, decodeStreamsCursor, exports_hmac as crypto, closeDb, assertDbSplit, VersionConflictError, ValidationError, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateTransaction, UpdateTenantUsageMonthly, UpdateTenantComputeAddon, UpdateTenant, UpdateSubscriptionRequestSchema, UpdateSubscriptionRequest, UpdateSubscriptionOutbox, UpdateSubscription, UpdateSubgraphOperation, UpdateSubgraph, UpdateProject, UpdateIndexProgress, UpdateEvent, UpdateContract, UpdateChatSession, UpdateBlock, UpdateApiKey, UpdateAccountSpendCap, TriggerEvaluatorStateTable, TriggerEvaluatorState, TransactionsTable, TransactionsArchiveTable, Transaction, TenantsTable, TenantUsageMonthlyTable, TenantUsageMonthly, TenantSuspendedError, TenantStatus, TenantComputeAddonsTable, TenantComputeAddon, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubscriptionsTable, SubscriptionSummary, SubscriptionStatusSchema, SubscriptionStatus, SubscriptionSchemaTables, SubscriptionSchemaTable, SubscriptionSchemaColumn, SubscriptionRuntimeSchema, SubscriptionRuntime, SubscriptionOutboxTable, SubscriptionOutbox, SubscriptionKind, SubscriptionFormatSchema, SubscriptionFormat, SubscriptionFilterSchema, SubscriptionFilterPrimitiveSchema, SubscriptionFilterPrimitive, SubscriptionFilterOperatorSchema, SubscriptionFilterOperator, SubscriptionFilterClauseSchema, SubscriptionFilterClause, SubscriptionFilter, SubscriptionDetail, SubscriptionDelivery, SubscriptionDeliveriesTable, Subscription, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphSyncInfo, SubgraphSummary, SubgraphSpecOptions, SubgraphSpecFormat, SubgraphResourceWarning, SubgraphQueryParams, SubgraphProcessingStatsTable, SubgraphOperationsTable, SubgraphOperationStatus, SubgraphOperationKind, SubgraphOperation, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGapsResponse, SubgraphGapRange, SubgraphGapEntry, SubgraphGap, SubgraphDetail, SubgraphAgentSchema, Subgraph, StxTransferFilterSchema, StxTransferFilter, StxMintFilterSchema, StxMintFilter, StxLockFilterSchema, StxLockFilter, StxBurnFilterSchema, StxBurnFilter, StreamsEventType, StreamsDbEventType, StreamsCursor, SessionsTable, Session, ServiceHeartbeatsTable, SecondLayerError, SbtcTokenEventsTable, SbtcTokenEventType, SbtcSupplySnapshotsTable, SbtcEventsTable, SbtcEventTopic, SUBSCRIPTION_STATUSES, SUBSCRIPTION_RUNTIMES, SUBSCRIPTION_FORMATS, SUBSCRIPTION_FILTER_OPERATORS, STREAMS_TO_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_DB_EVENT_TYPES, SOURCE_READ_COLUMNS, RotateSecretResponse, ReplaySubscriptionRequestSchema, ReplaySubscriptionRequest, ReplayResult, ReindexResponse, RateLimitError, ProvisioningAuditStatus, ProvisioningAuditLogTable, ProvisioningAuditLog, ProvisioningAuditEvent, ProjectsTable, Project, ProcessedStripeEventsTable, PrintEventFilterSchema, PrintEventFilter, Pox4SignersDailyTable, Pox4FunctionName, Pox4CyclesDailyTable, Pox4CallsTable, ParsedUpdateSubscriptionRequest, ParsedReplaySubscriptionRequest, ParsedCreateSubscriptionRequest, OutboxStatus, NumericAsText, NotFoundError, NftTransferFilterSchema, NftTransferFilter, NftMintFilterSchema, NftMintFilter, NftBurnFilterSchema, NftBurnFilter, MempoolTransactionsTable, MempoolTransaction, MagicLinksTable, MagicLink, L2DecoderCheckpointsTable, KeyRotatedError, InsertTransaction, InsertTenantUsageMonthly, InsertTenantComputeAddon, InsertTenant, InsertTeamMember, InsertTeamInvitation, InsertSubscriptionOutbox, InsertSubscriptionDelivery, InsertSubscription, InsertSubgraphUsageDaily, InsertSubgraphOperation, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProvisioningAuditLog, InsertProject, InsertMempoolTransaction, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertContract, InsertChatSession, InsertChatMessage, InsertBlock, InsertApiKey, InsertAccountSpendCap, InsertAccountInsight, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, FtTransferFilterSchema, FtTransferFilter, FtMintFilterSchema, FtMintFilter, FtBurnFilterSchema, FtBurnFilter, ForbiddenError, EventsTable, EventsArchiveTable, EventFilterSchema, EventFilter, Event, ErrorCodes, ErrorCode, Env, EMPTY_RANGE_EVENT_INDEX_SENTINEL, DeploySubgraphResponse, DeploySubgraphRequestSchema, DeploySubgraphRequest, DeliveryRow, DecodedEventsTable, DecodedEventType, DeadRow, DeadLetterEventsTable, DbSplitStatus, DbReadRow, DatabaseError, Database, DEFAULT_BTC_CONFIRMATIONS, DECODED_EVENT_TYPES, DB_TO_STREAMS_EVENT_TYPE, CreateSubscriptionResponse, CreateSubscriptionRequestSchema, CreateSubscriptionRequest, ContractsTable, ContractDeployFilterSchema, ContractDeployFilter, ContractCallFilterSchema, ContractCallFilter, Contract, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, ChainReorgsTable, CODE_TO_STATUS, CHAIN_TRIGGER_TYPES, BurnBlockRewardsTable, BurnBlockRewardSlotsTable, BnsNamespacesTable, BnsNamespaceEventsTable, BnsNamespaceEventStatus, BnsNamesTable, BnsNameEventsTable, BnsNameEventTopic, BnsMarketplaceEventsTable, BnsMarketplaceAction, BlocksTable, Block, AuthorizationError, AuthenticationError, ApiKeysTable, ApiKey, AccountsTable, AccountSpendCapsTable, AccountSpendCap, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
package/dist/src/index.js CHANGED
@@ -411,14 +411,50 @@ function resolveSourceUrl() {
411
411
  function resolveTargetUrl() {
412
412
  return process.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL;
413
413
  }
414
+ function describeDbUrl(url) {
415
+ try {
416
+ const u = new URL(url);
417
+ return `${u.hostname}${u.port ? `:${u.port}` : ""}${u.pathname}`;
418
+ } catch {
419
+ return "invalid-url";
420
+ }
421
+ }
422
+ function getDbSplitStatus() {
423
+ const source = resolveSourceUrl();
424
+ const target = resolveTargetUrl();
425
+ const active = source !== target;
426
+ return {
427
+ mode: active ? "split" : "single",
428
+ active,
429
+ sourceDb: describeDbUrl(source),
430
+ targetDb: describeDbUrl(target)
431
+ };
432
+ }
414
433
  function assertDbSplit() {
434
+ const isProd = false;
415
435
  const wantsSplit = !!(process.env.SOURCE_DATABASE_URL || process.env.TARGET_DATABASE_URL);
416
- if (!wantsSplit)
436
+ const databaseUrlSet = !!process.env.DATABASE_URL;
437
+ const source = resolveSourceUrl();
438
+ const target = resolveTargetUrl();
439
+ if (wantsSplit && !databaseUrlSet && (source === DEFAULT_URL || target === DEFAULT_URL)) {
440
+ const which = source === DEFAULT_URL ? "SOURCE_DATABASE_URL" : "TARGET_DATABASE_URL";
441
+ const msg = `${which} unset and DATABASE_URL absent — resolving to built-in DEFAULT_URL; refusing to silently use the wrong database`;
442
+ if (isProd)
443
+ console.error(`❌ ${msg}`);
444
+ else
445
+ console.warn(`⚠️ ${msg}`);
446
+ return;
447
+ }
448
+ if (!wantsSplit) {
449
+ if (isProd) {
450
+ console.warn("⚠️ DB split dormant — all services share one Postgres failure domain (SOURCE_/TARGET_DATABASE_URL unset)");
451
+ }
417
452
  return;
418
- if (resolveSourceUrl() === resolveTargetUrl()) {
453
+ }
454
+ if (source === target) {
419
455
  const msg = "DB split requested but SOURCE_DATABASE_URL === TARGET_DATABASE_URL (check for a typo or a stray DATABASE_URL fallback)";
420
- if (false)
421
- ;
456
+ if (isProd)
457
+ console.error(`❌ ${msg}`);
422
458
  else
423
459
  console.warn(`⚠️ ${msg}`);
424
460
  }
@@ -1590,6 +1626,7 @@ export {
1590
1626
  getRawClient,
1591
1627
  getErrorMessage,
1592
1628
  getEnv,
1629
+ getDbSplitStatus,
1593
1630
  getDb,
1594
1631
  generateSubgraphSpec,
1595
1632
  generateSubgraphOpenApi,
@@ -1656,5 +1693,5 @@ export {
1656
1693
  AuthenticationError
1657
1694
  };
1658
1695
 
1659
- //# debugId=DA391FC32E755E3A64756E2164756E21
1696
+ //# debugId=80DED0C0E8D3237364756E2164756E21
1660
1697
  //# sourceMappingURL=index.js.map