@secondlayer/shared 11.7.1 → 11.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/dist/src/archive/copy-loader.d.ts +1 -1
  2. package/dist/src/archive/copy-loader.js +4 -20
  3. package/dist/src/archive/copy-loader.js.map +2 -2
  4. package/dist/src/archive/derived-stage-report.d.ts +1 -1
  5. package/dist/src/archive/derived-stage-report.js +3 -19
  6. package/dist/src/archive/derived-stage-report.js.map +2 -2
  7. package/dist/src/archive/disk-guard.d.ts +1 -1
  8. package/dist/src/archive/disk-guard.js +3 -19
  9. package/dist/src/archive/disk-guard.js.map +2 -2
  10. package/dist/src/archive/instance-diagnosis.d.ts +1 -1
  11. package/dist/src/archive/instance-diagnosis.js +6 -22
  12. package/dist/src/archive/instance-diagnosis.js.map +2 -2
  13. package/dist/src/archive/key-registry.d.ts +1 -1
  14. package/dist/src/archive/key-registry.js +12 -12
  15. package/dist/src/archive/key-registry.js.map +1 -1
  16. package/dist/src/archive/per-height-digest.d.ts +1 -1
  17. package/dist/src/archive/per-height-digest.js +3 -17
  18. package/dist/src/archive/per-height-digest.js.map +5 -5
  19. package/dist/src/archive/progress.d.ts +1 -1
  20. package/dist/src/archive/progress.js +4 -20
  21. package/dist/src/archive/progress.js.map +2 -2
  22. package/dist/src/archive/range-digest.d.ts +28 -3
  23. package/dist/src/archive/range-digest.js +4 -20
  24. package/dist/src/archive/range-digest.js.map +2 -2
  25. package/dist/src/archive/reference.d.ts +1 -1
  26. package/dist/src/archive/reference.js +14 -12
  27. package/dist/src/archive/reference.js.map +5 -5
  28. package/dist/src/archive/root-key.d.ts +1 -1
  29. package/dist/src/archive/root-key.js +3 -19
  30. package/dist/src/archive/root-key.js.map +2 -2
  31. package/dist/src/archive/semantic-digest-builder.d.ts +28 -3
  32. package/dist/src/archive/semantic-digest-builder.js +5 -19
  33. package/dist/src/archive/semantic-digest-builder.js.map +5 -5
  34. package/dist/src/archive/semantic-digest.d.ts +1 -1
  35. package/dist/src/archive/semantic-digest.js +4 -20
  36. package/dist/src/archive/semantic-digest.js.map +2 -2
  37. package/dist/src/archive/status.d.ts +1 -1
  38. package/dist/src/archive/status.js +4 -20
  39. package/dist/src/archive/status.js.map +2 -2
  40. package/dist/src/coverage/index.d.ts +27 -2
  41. package/dist/src/coverage/index.js +80 -96
  42. package/dist/src/coverage/index.js.map +2 -2
  43. package/dist/src/crypto/ed25519.d.ts +1 -1
  44. package/dist/src/crypto/ed25519.js +13 -13
  45. package/dist/src/crypto/ed25519.js.map +1 -1
  46. package/dist/src/crypto/hmac.d.ts +1 -1
  47. package/dist/src/crypto/hmac.js +9 -9
  48. package/dist/src/crypto/hmac.js.map +1 -1
  49. package/dist/src/crypto/secondlayer-webhook.d.ts +1 -1
  50. package/dist/src/crypto/secondlayer-webhook.js +14 -14
  51. package/dist/src/crypto/secondlayer-webhook.js.map +2 -2
  52. package/dist/src/crypto/secrets.d.ts +1 -1
  53. package/dist/src/crypto/secrets.js +15 -29
  54. package/dist/src/crypto/secrets.js.map +5 -5
  55. package/dist/src/crypto/standard-webhooks.d.ts +1 -1
  56. package/dist/src/crypto/standard-webhooks.js +3 -19
  57. package/dist/src/crypto/standard-webhooks.js.map +2 -2
  58. package/dist/src/db/index.d.ts +48 -19
  59. package/dist/src/db/index.js +41 -55
  60. package/dist/src/db/index.js.map +6 -6
  61. package/dist/src/db/jsonb.d.ts +1 -1
  62. package/dist/src/db/jsonb.js +3 -19
  63. package/dist/src/db/jsonb.js.map +2 -2
  64. package/dist/src/db/queries/chain-reorgs.d.ts +27 -2
  65. package/dist/src/db/queries/chain-reorgs.js +28 -42
  66. package/dist/src/db/queries/chain-reorgs.js.map +6 -6
  67. package/dist/src/db/queries/contracts.d.ts +27 -2
  68. package/dist/src/db/queries/contracts.js +9 -23
  69. package/dist/src/db/queries/contracts.js.map +5 -5
  70. package/dist/src/db/queries/instance.d.ts +27 -2
  71. package/dist/src/db/queries/instance.js +7 -23
  72. package/dist/src/db/queries/instance.js.map +2 -2
  73. package/dist/src/db/queries/integrity.d.ts +27 -2
  74. package/dist/src/db/queries/integrity.js +5 -21
  75. package/dist/src/db/queries/integrity.js.map +2 -2
  76. package/dist/src/db/queries/subgraph-gaps.d.ts +27 -2
  77. package/dist/src/db/queries/subgraph-gaps.js +5 -21
  78. package/dist/src/db/queries/subgraph-gaps.js.map +2 -2
  79. package/dist/src/db/queries/subgraph-operations.d.ts +27 -2
  80. package/dist/src/db/queries/subgraph-operations.js +17 -33
  81. package/dist/src/db/queries/subgraph-operations.js.map +2 -2
  82. package/dist/src/db/queries/subgraphs.d.ts +28 -14
  83. package/dist/src/db/queries/subgraphs.js +15 -37
  84. package/dist/src/db/queries/subgraphs.js.map +5 -5
  85. package/dist/src/db/queries/sync-scope.d.ts +27 -2
  86. package/dist/src/db/queries/sync-scope.js +6 -22
  87. package/dist/src/db/queries/sync-scope.js.map +2 -2
  88. package/dist/src/db/queries/webhooks.d.ts +27 -2
  89. package/dist/src/db/queries/webhooks.js +54 -50
  90. package/dist/src/db/queries/webhooks.js.map +5 -5
  91. package/dist/src/db/schema.d.ts +30 -2
  92. package/dist/src/env.d.ts +1 -1
  93. package/dist/src/env.js +7 -23
  94. package/dist/src/env.js.map +2 -2
  95. package/dist/src/errors.d.ts +4 -4
  96. package/dist/src/errors.js +15 -31
  97. package/dist/src/errors.js.map +3 -3
  98. package/dist/src/index-http.d.ts +1 -1
  99. package/dist/src/index-http.js +4 -20
  100. package/dist/src/index-http.js.map +3 -3
  101. package/dist/src/index-internal-auth.d.ts +4 -7
  102. package/dist/src/index-internal-auth.js +8 -24
  103. package/dist/src/index-internal-auth.js.map +3 -3
  104. package/dist/src/index.d.ts +176 -152
  105. package/dist/src/index.js +305 -317
  106. package/dist/src/index.js.map +15 -15
  107. package/dist/src/leader.d.ts +1 -1
  108. package/dist/src/leader.js +7 -21
  109. package/dist/src/leader.js.map +5 -5
  110. package/dist/src/logger.js +1 -17
  111. package/dist/src/logger.js.map +2 -2
  112. package/dist/src/mode.d.ts +1 -1
  113. package/dist/src/mode.js +5 -21
  114. package/dist/src/mode.js.map +2 -2
  115. package/dist/src/node/archive-client.d.ts +1 -1
  116. package/dist/src/node/archive-client.js +9 -23
  117. package/dist/src/node/archive-client.js.map +5 -5
  118. package/dist/src/node/client.d.ts +1 -1
  119. package/dist/src/node/client.js +4 -18
  120. package/dist/src/node/client.js.map +5 -5
  121. package/dist/src/node/consensus.d.ts +1 -1
  122. package/dist/src/node/consensus.js +5 -21
  123. package/dist/src/node/consensus.js.map +2 -2
  124. package/dist/src/node/hiro-client.d.ts +1 -1
  125. package/dist/src/node/hiro-client.js +1 -17
  126. package/dist/src/node/hiro-client.js.map +2 -2
  127. package/dist/src/node/hiro-pg-client.js +1 -17
  128. package/dist/src/node/hiro-pg-client.js.map +2 -2
  129. package/dist/src/node/local-client.d.ts +27 -2
  130. package/dist/src/node/local-client.js +3 -19
  131. package/dist/src/node/local-client.js.map +2 -2
  132. package/dist/src/node/nakamoto.d.ts +1 -1
  133. package/dist/src/node/nakamoto.js +12 -28
  134. package/dist/src/node/nakamoto.js.map +2 -2
  135. package/dist/src/queue/listener.d.ts +1 -1
  136. package/dist/src/queue/listener.js +4 -20
  137. package/dist/src/queue/listener.js.map +2 -2
  138. package/dist/src/runtime/index.d.ts +1 -1
  139. package/dist/src/runtime/index.js +51 -67
  140. package/dist/src/runtime/index.js.map +2 -2
  141. package/dist/src/schemas/index.d.ts +8 -4
  142. package/dist/src/schemas/index.js +64 -41
  143. package/dist/src/schemas/index.js.map +4 -4
  144. package/dist/src/schemas/subgraphs.d.ts +1 -4
  145. package/dist/src/schemas/subgraphs.js +1 -18
  146. package/dist/src/schemas/subgraphs.js.map +3 -3
  147. package/dist/src/schemas/webhooks.d.ts +19 -1
  148. package/dist/src/schemas/webhooks.js +70 -41
  149. package/dist/src/schemas/webhooks.js.map +3 -3
  150. package/dist/src/streams-bulk-manifest.d.ts +1 -1
  151. package/dist/src/streams-bulk-manifest.js +9 -9
  152. package/dist/src/streams-bulk-manifest.js.map +1 -1
  153. package/dist/src/streams-rows/index.d.ts +1 -1
  154. package/dist/src/streams-rows/index.js +32 -48
  155. package/dist/src/streams-rows/index.js.map +2 -2
  156. package/dist/src/subgraphs/spec.d.ts +1 -11
  157. package/dist/src/subgraphs/spec.js +27 -93
  158. package/dist/src/subgraphs/spec.js.map +3 -3
  159. package/dist/src/types.d.ts +1 -1
  160. package/migrations/0136_drop_subgraph_visibility.ts +34 -0
  161. package/migrations/0137_webhook_outbox_last_error.ts +27 -0
  162. package/migrations/0138_usage_ledger.ts +46 -0
  163. package/package.json +1 -1
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/env.ts", "../src/logger.ts", "../src/mode.ts", "../src/db/jsonb.ts", "../src/db/index.ts", "../src/db/source-read-columns.ts", "../src/db/migration-role.ts", "../src/db/table-plane.ts", "../src/db/queries/chain-reorgs.ts"],
3
+ "sources": ["../src/db/index.ts", "../src/env.ts", "../src/logger.ts", "../src/mode.ts", "../src/db/source-read-columns.ts", "../src/db/jsonb.ts", "../src/db/migration-role.ts", "../src/db/table-plane.ts", "../src/db/queries/chain-reorgs.ts"],
4
4
  "sourcesContent": [
5
+ "import { Kysely } from \"kysely\";\nimport { PostgresJSDialect } from \"kysely-postgres-js\";\nimport postgres from \"postgres\";\nimport { isProductionEnv } from \"../env.ts\";\nimport { logger } from \"../logger.ts\";\nimport { isPlatformMode } from \"../mode.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 extra 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 * Extra pools (e.g. setup-wizard via getRawClientFor) are bounded\n * (`DATABASE_MAX_POOLS`, default 25) with LRU eviction — the hot source/target\n * 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\n/** OSS: one application URL. SOURCE_/TARGET_ are hosted split only. */\nexport function applicationDatabaseUrl(): string {\n\treturn process.env.DATABASE_URL || DEFAULT_URL;\n}\n\nfunction resolveSourceUrl(): string {\n\tif (!isPlatformMode()) return applicationDatabaseUrl();\n\treturn (\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction resolveTargetUrl(): string {\n\tif (!isPlatformMode()) return applicationDatabaseUrl();\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\n/** Warn-once latch — one line per process, not one per import or connection. */\nlet warnedDefaultUrlFallthrough = false;\n\n/**\n * Test-run guard for the plain \"no DB env at all\" case, which `assertDbSplit`\n * deliberately does not cover (it only fires when a SPLIT is requested).\n *\n * Without any of the three URL vars, every getter resolves to the built-in\n * dev `DEFAULT_URL`. In a test run that means one of two silent outcomes: the\n * suite's own `skipIf(!process.env.DATABASE_URL)` guard disables it entirely,\n * or an unguarded test connects to whatever Postgres happens to be on\n * localhost:5432. Both exit 0 and read as \"tests passed\".\n *\n * Fires at MODULE LOAD, not from a getter: DB-backed suites guard `getDb()`\n * behind their own `skipIf`, so when the env is missing no getter is ever\n * called — import is the only point where this is still observable.\n *\n * Gated to `NODE_ENV=test` on purpose. `@secondlayer/shared` is published, and\n * end users running `sl local` / `sl dev` rely on `DEFAULT_URL` legitimately —\n * it matches what the CLI provisions. They must see nothing. Fail-soft: warns,\n * never throws, matching `assertDbSplit`'s contract.\n */\nfunction warnIfTestRunFallsThroughToDefault(): void {\n\tif (warnedDefaultUrlFallthrough) return;\n\t// Runtime read — inlining `process.env.NODE_ENV` gets constant-folded into\n\t// the shipped dist, freezing this to a build-time literal. See env.ts.\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler.\n\tif (process.env[\"NODE_ENV\"] !== \"test\") return;\n\tif (\n\t\tprocess.env.DATABASE_URL ||\n\t\tprocess.env.SOURCE_DATABASE_URL ||\n\t\tprocess.env.TARGET_DATABASE_URL\n\t) {\n\t\treturn;\n\t}\n\twarnedDefaultUrlFallthrough = true;\n\tconsole.warn(\n\t\t`⚠️ DATABASE_URL unset — falling through to the built-in DEFAULT_URL (${describeDbUrl(\n\t\t\tDEFAULT_URL,\n\t\t)}). Database-backed tests will skip or hit the wrong Postgres. Copy .env.example to .env in this package (see \\`bun run db\\`).`,\n\t);\n}\n\nwarnIfTestRunFallsThroughToDefault();\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\t// Runtime read — inlining `process.env.NODE_ENV` gets constant-folded in the\n\t// shipped dist (this prod branch would die silently). See env.ts.\n\tconst isProd = isProductionEnv();\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 extra pools don't pin connections they no\n\t// longer need (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 CLI setup-wizard and similar one-off tooling. Distinct from\n * {@link getRawClient}, which only knows the source/target roles resolved\n * 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 {\n\tSOURCE_READ_COLUMNS,\n\tSOURCE_READ_TYPES,\n\tSOURCE_READ_PKS,\n\ttype IndexColumn,\n\ttype IndexColumnType,\n\ttype IndexPrimaryKey,\n} from \"./source-read-columns.ts\";\nexport { jsonb, parseJsonb } from \"./jsonb.ts\";\nexport {\n\tgetMigrationRole,\n\tonChainPlane,\n\tonControlPlane,\n\tsetMigrationRole,\n} from \"./migration-role.ts\";\nexport type { MigrationRole } from \"./migration-role.ts\";\nexport { TABLE_TO_DB } from \"./table-plane.ts\";\nexport type { DbPlane } from \"./table-plane.ts\";\n",
5
6
  "import { z } from \"zod\";\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 * True when `NODE_ENV=production`, read at RUNTIME — the single source of truth\n * for prod-vs-dev branching in this package.\n *\n * Why a helper instead of inlining `process.env.NODE_ENV === \"production\"`:\n * bunup/esbuild constant-folds the dot-access `process.env.NODE_ENV` to its\n * BUILD-time value. `@secondlayer/shared` is consumed by other services as its\n * built `dist`, so an inlined check freezes to a literal in the shipped bundle\n * (e.g. `const isProd = false`) and silently ignores the container's real\n * NODE_ENV. The bracket access below is NOT folded, so it stays a runtime read.\n * Route every prod check through here so the footgun lives in exactly one place.\n */\nexport function isProductionEnv(): boolean {\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler, freezing this to a build-time literal in the shipped dist.\n\treturn process.env[\"NODE_ENV\"] === \"production\";\n}\n\ntype EnvMap = NodeJS.ProcessEnv;\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(env: EnvMap = process.env): boolean {\n\treturn env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n/**\n * PoX-5 print-event decoder is ON by default (mirrors pox-4/sBTC policy).\n * No activation gating needed: pox-5 events cannot exist before the Epoch 4.0\n * hard fork (Bitcoin block 960,230), so pre-activation the decoder idles at\n * tip. Opt out with `POX5_DECODER_ENABLED=false`.\n */\nexport function isPox5DecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.POX5_DECODER_ENABLED !== \"false\";\n}\n\n/** Default ON. Opt out with `SBTC_DECODER_ENABLED=false`. */\nexport function isSbtcDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.SBTC_DECODER_ENABLED !== \"false\";\n}\n\n/** Default OFF. Opt in with `BNS_DECODER_ENABLED=true`. */\nexport function isBnsDecoderEnabled(env: EnvMap = process.env): boolean {\n\treturn env.BNS_DECODER_ENABLED === \"true\";\n}\n\n// Export for testing\nexport { envSchema };\n",
6
7
  "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
8
  "/**\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`: the metered archive deployment. Magic-link auth, API keys,\n * accounts, credits, and metered `/v1` reads (Index + Streams + subgraphs)\n * against a single shared DB. No paid tier ladder — one metered `free`\n * tier plus first-party internal service credentials.\n */\n\nexport type InstanceMode = \"oss\" | \"platform\";\n\n/** What the operator wrote in the env — `archive` is the honest name for the\n * metered public-archive deployment and aliases `platform` behaviorally. */\nexport type DeclaredInstanceMode = InstanceMode | \"archive\";\n\nconst VALID_MODES: readonly DeclaredInstanceMode[] = [\n\t\"oss\",\n\t\"platform\",\n\t\"archive\",\n];\n\nfunction declaredMode(): DeclaredInstanceMode {\n\tconst raw = process.env.INSTANCE_MODE?.trim().toLowerCase();\n\tif (raw && (VALID_MODES as readonly string[]).includes(raw)) {\n\t\treturn raw as DeclaredInstanceMode;\n\t}\n\treturn \"oss\";\n}\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. `archive` normalizes to `platform` here so\n * every behavioral branch stays a two-way choice; use\n * `getDeclaredInstanceMode()` for display surfaces.\n */\nexport function getInstanceMode(): InstanceMode {\n\tconst declared = declaredMode();\n\treturn declared === \"archive\" ? \"platform\" : declared;\n}\n\n/** The mode as declared in the env, for status/identity surfaces. */\nexport function getDeclaredInstanceMode(): DeclaredInstanceMode {\n\treturn declaredMode();\n}\n\n/**\n * True when public reads are credit-metered (the free window, retention, and\n * credits gates arm). Platform/archive deployments meter by default;\n * self-host never does unless the operator explicitly sets\n * `METERED_READS=true`. `METERED_READS=false` disarms a metered deployment.\n */\nexport function isMeteredReads(): boolean {\n\tconst override = process.env.METERED_READS?.trim().toLowerCase();\n\tif (override === \"true\") return true;\n\tif (override === \"false\") return false;\n\treturn getInstanceMode() === \"platform\";\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",
8
- "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",
9
- "import { Kysely } from \"kysely\";\nimport { PostgresJSDialect } from \"kysely-postgres-js\";\nimport postgres from \"postgres\";\nimport { isProductionEnv } from \"../env.ts\";\nimport { logger } from \"../logger.ts\";\nimport { isPlatformMode } from \"../mode.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 extra 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 * Extra pools (e.g. setup-wizard via getRawClientFor) are bounded\n * (`DATABASE_MAX_POOLS`, default 25) with LRU eviction — the hot source/target\n * 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\n/** OSS: one application URL. SOURCE_/TARGET_ are hosted split only. */\nexport function applicationDatabaseUrl(): string {\n\treturn process.env.DATABASE_URL || DEFAULT_URL;\n}\n\nfunction resolveSourceUrl(): string {\n\tif (!isPlatformMode()) return applicationDatabaseUrl();\n\treturn (\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction resolveTargetUrl(): string {\n\tif (!isPlatformMode()) return applicationDatabaseUrl();\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\n/** Warn-once latch — one line per process, not one per import or connection. */\nlet warnedDefaultUrlFallthrough = false;\n\n/**\n * Test-run guard for the plain \"no DB env at all\" case, which `assertDbSplit`\n * deliberately does not cover (it only fires when a SPLIT is requested).\n *\n * Without any of the three URL vars, every getter resolves to the built-in\n * dev `DEFAULT_URL`. In a test run that means one of two silent outcomes: the\n * suite's own `skipIf(!process.env.DATABASE_URL)` guard disables it entirely,\n * or an unguarded test connects to whatever Postgres happens to be on\n * localhost:5432. Both exit 0 and read as \"tests passed\".\n *\n * Fires at MODULE LOAD, not from a getter: DB-backed suites guard `getDb()`\n * behind their own `skipIf`, so when the env is missing no getter is ever\n * called — import is the only point where this is still observable.\n *\n * Gated to `NODE_ENV=test` on purpose. `@secondlayer/shared` is published, and\n * end users running `sl local` / `sl dev` rely on `DEFAULT_URL` legitimately —\n * it matches what the CLI provisions. They must see nothing. Fail-soft: warns,\n * never throws, matching `assertDbSplit`'s contract.\n */\nfunction warnIfTestRunFallsThroughToDefault(): void {\n\tif (warnedDefaultUrlFallthrough) return;\n\t// Runtime read — inlining `process.env.NODE_ENV` gets constant-folded into\n\t// the shipped dist, freezing this to a build-time literal. See env.ts.\n\t// biome-ignore lint/complexity/useLiteralKeys: bracket access is deliberate — dot-access gets constant-folded by the bundler.\n\tif (process.env[\"NODE_ENV\"] !== \"test\") return;\n\tif (\n\t\tprocess.env.DATABASE_URL ||\n\t\tprocess.env.SOURCE_DATABASE_URL ||\n\t\tprocess.env.TARGET_DATABASE_URL\n\t) {\n\t\treturn;\n\t}\n\twarnedDefaultUrlFallthrough = true;\n\tconsole.warn(\n\t\t`⚠️ DATABASE_URL unset — falling through to the built-in DEFAULT_URL (${describeDbUrl(\n\t\t\tDEFAULT_URL,\n\t\t)}). Database-backed tests will skip or hit the wrong Postgres. Copy .env.example to .env in this package (see \\`bun run db\\`).`,\n\t);\n}\n\nwarnIfTestRunFallsThroughToDefault();\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\t// Runtime read — inlining `process.env.NODE_ENV` gets constant-folded in the\n\t// shipped dist (this prod branch would die silently). See env.ts.\n\tconst isProd = isProductionEnv();\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 extra pools don't pin connections they no\n\t// longer need (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 CLI setup-wizard and similar one-off tooling. Distinct from\n * {@link getRawClient}, which only knows the source/target roles resolved\n * 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 {\n\tSOURCE_READ_COLUMNS,\n\tSOURCE_READ_TYPES,\n\tSOURCE_READ_PKS,\n\ttype IndexColumn,\n\ttype IndexColumnType,\n\ttype IndexPrimaryKey,\n} from \"./source-read-columns.ts\";\nexport { jsonb, parseJsonb } from \"./jsonb.ts\";\nexport {\n\tgetMigrationRole,\n\tonChainPlane,\n\tonControlPlane,\n\tsetMigrationRole,\n} from \"./migration-role.ts\";\nexport type { MigrationRole } from \"./migration-role.ts\";\nexport { TABLE_TO_DB } from \"./table-plane.ts\";\nexport type { DbPlane } from \"./table-plane.ts\";\n",
10
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\tpox5_events: [\n\t\t\"amount_sats\",\n\t\t\"amount_ustx\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"bond_index\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"data\",\n\t\t\"event_index\",\n\t\t\"first_reward_cycle\",\n\t\t\"is_l1_lock\",\n\t\t\"reward_cycle\",\n\t\t\"signer\",\n\t\t\"signer_key\",\n\t\t\"signer_manager\",\n\t\t\"staker\",\n\t\t\"topic\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t\t\"unlock_burn_height\",\n\t\t\"unlock_cycle\",\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\"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\"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\n/** Portable column type for the Index read domain (a lean, ORM-agnostic vocab). */\nexport type IndexColumnType =\n\t| \"text\"\n\t| \"int\"\n\t| \"boolean\"\n\t| \"timestamp\"\n\t| \"jsonb\";\n\nexport interface IndexColumn {\n\ttype: IndexColumnType;\n\t/** SELECT type includes `| null`. Omitted = NOT NULL. */\n\tnullable?: boolean;\n}\n\n// The portable TS/SQL type for every column in SOURCE_READ_COLUMNS, single-sourced\n// from the `Database` interface (the producer's typed schema). This is what lets\n// `sl codegen index` emit a typed ORM/JSON-Schema for the public Index domain so a\n// read mirror is fully typed and can't drift from the API. The drift test\n// (source-read-columns.test.ts) asserts this covers exactly SOURCE_READ_COLUMNS;\n// the `satisfies` clause guarantees a type entry for every read table.\n//\n// `string` amount/value columns (e.g. amount_ustx, fee, price_ustx) are NUMERIC in\n// Postgres surfaced as strings — `text` here is lossless for a read mirror. `number`\n// columns map to `int`. Enum string-unions (topic, status, …) map to `text`.\nexport const SOURCE_READ_TYPES = {\n\tblocks: {\n\t\tburn_block_hash: { type: \"text\", nullable: true },\n\t\tburn_block_height: { type: \"int\" },\n\t\tcanonical: { type: \"boolean\" },\n\t\thash: { type: \"text\" },\n\t\theight: { type: \"int\" },\n\t\tparent_hash: { type: \"text\" },\n\t\ttimestamp: { type: \"int\" },\n\t},\n\tdecoded_events: {\n\t\tamount: { type: \"text\", nullable: true },\n\t\tasset_identifier: { type: \"text\", nullable: true },\n\t\tblock_height: { type: \"int\" },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcontract_id: { type: \"text\", nullable: true },\n\t\tcursor: { type: \"text\" },\n\t\tevent_index: { type: \"int\" },\n\t\tevent_type: { type: \"text\" },\n\t\tmemo: { type: \"text\", nullable: true },\n\t\tpayload: { type: \"jsonb\", nullable: true },\n\t\trecipient: { type: \"text\", nullable: true },\n\t\tsender: { type: \"text\", nullable: true },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t\tvalue: { type: \"text\", nullable: true },\n\t},\n\ttransactions: {\n\t\tblock_height: { type: \"int\" },\n\t\tcontract_id: { type: \"text\", nullable: true },\n\t\tfunction_args: { type: \"jsonb\", nullable: true },\n\t\tfunction_name: { type: \"text\", nullable: true },\n\t\traw_result: { type: \"text\", nullable: true },\n\t\traw_tx: { type: \"text\" },\n\t\tsender: { type: \"text\" },\n\t\tstatus: { type: \"text\" },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t\ttype: { type: \"text\" },\n\t},\n\tmempool_transactions: {\n\t\tcontract_id: { type: \"text\", nullable: true },\n\t\tfunction_args: { type: \"jsonb\", nullable: true },\n\t\tfunction_name: { type: \"text\", nullable: true },\n\t\traw_tx: { type: \"text\" },\n\t\treceived_at: { type: \"timestamp\" },\n\t\tsender: { type: \"text\" },\n\t\tseq: { type: \"text\" },\n\t\ttx_id: { type: \"text\" },\n\t\ttype: { type: \"text\" },\n\t},\n\tpox4_calls: {\n\t\taggregated_amount_ustx: { type: \"text\", nullable: true },\n\t\taggregated_signer_index: { type: \"int\", nullable: true },\n\t\tamount_ustx: { type: \"text\", nullable: true },\n\t\tauth_allowed: { type: \"boolean\", nullable: true },\n\t\tauth_id: { type: \"text\", nullable: true },\n\t\tauth_period: { type: \"int\", nullable: true },\n\t\tauth_topic: { type: \"text\", nullable: true },\n\t\tblock_height: { type: \"int\" },\n\t\tblock_time: { type: \"timestamp\" },\n\t\tburn_block_height: { type: \"int\" },\n\t\tcaller: { type: \"text\" },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcursor: { type: \"text\" },\n\t\tdelegate_to: { type: \"text\", nullable: true },\n\t\tend_cycle: { type: \"int\", nullable: true },\n\t\tfunction_name: { type: \"text\" },\n\t\tlock_period: { type: \"int\", nullable: true },\n\t\tmax_amount: { type: \"text\", nullable: true },\n\t\tpox_addr_btc: { type: \"text\", nullable: true },\n\t\tpox_addr_hashbytes: { type: \"text\", nullable: true },\n\t\tpox_addr_version: { type: \"int\", nullable: true },\n\t\tresult_ok: { type: \"boolean\" },\n\t\treward_cycle: { type: \"int\", nullable: true },\n\t\tsigner_key: { type: \"text\", nullable: true },\n\t\tsigner_signature: { type: \"text\", nullable: true },\n\t\tsource_cursor: { type: \"text\" },\n\t\tstacker: { type: \"text\", nullable: true },\n\t\tstart_cycle: { type: \"int\", nullable: true },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t},\n\tpox5_events: {\n\t\tamount_sats: { type: \"text\", nullable: true },\n\t\tamount_ustx: { type: \"text\", nullable: true },\n\t\tblock_height: { type: \"int\" },\n\t\tblock_time: { type: \"timestamp\" },\n\t\tbond_index: { type: \"int\", nullable: true },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcursor: { type: \"text\" },\n\t\tdata: { type: \"jsonb\", nullable: true },\n\t\tevent_index: { type: \"int\" },\n\t\tfirst_reward_cycle: { type: \"int\", nullable: true },\n\t\tis_l1_lock: { type: \"boolean\", nullable: true },\n\t\treward_cycle: { type: \"int\", nullable: true },\n\t\tsigner: { type: \"text\", nullable: true },\n\t\tsigner_key: { type: \"text\", nullable: true },\n\t\tsigner_manager: { type: \"text\", nullable: true },\n\t\tstaker: { type: \"text\", nullable: true },\n\t\ttopic: { type: \"text\" },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t\tunlock_burn_height: { type: \"int\", nullable: true },\n\t\tunlock_cycle: { type: \"int\", nullable: true },\n\t},\n\tsbtc_events: {\n\t\tamount: { type: \"text\", nullable: true },\n\t\tbitcoin_txid: { type: \"text\", nullable: true },\n\t\tblock_height: { type: \"int\" },\n\t\tblock_time: { type: \"timestamp\" },\n\t\tburn_hash: { type: \"text\", nullable: true },\n\t\tburn_height: { type: \"int\", nullable: true },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcursor: { type: \"text\" },\n\t\tevent_index: { type: \"int\" },\n\t\tfee: { type: \"text\", nullable: true },\n\t\tgovernance_contract_type: { type: \"int\", nullable: true },\n\t\tgovernance_new_contract: { type: \"text\", nullable: true },\n\t\tmax_fee: { type: \"text\", nullable: true },\n\t\toutput_index: { type: \"int\", nullable: true },\n\t\trecipient_btc_hashbytes: { type: \"text\", nullable: true },\n\t\trecipient_btc_version: { type: \"int\", nullable: true },\n\t\trequest_id: { type: \"int\", nullable: true },\n\t\tsender: { type: \"text\", nullable: true },\n\t\tsigner_address: { type: \"text\", nullable: true },\n\t\tsigner_aggregate_pubkey: { type: \"text\", nullable: true },\n\t\tsigner_bitmap: { type: \"text\", nullable: true },\n\t\tsigner_keys_count: { type: \"int\", nullable: true },\n\t\tsigner_threshold: { type: \"int\", nullable: true },\n\t\tsweep_txid: { type: \"text\", nullable: true },\n\t\ttopic: { type: \"text\" },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t},\n\tsbtc_token_events: {\n\t\tamount: { type: \"text\" },\n\t\tblock_height: { type: \"int\" },\n\t\tblock_time: { type: \"timestamp\" },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcursor: { type: \"text\" },\n\t\tevent_index: { type: \"int\" },\n\t\tevent_type: { type: \"text\" },\n\t\tmemo: { type: \"text\", nullable: true },\n\t\trecipient: { type: \"text\", nullable: true },\n\t\tsender: { type: \"text\", nullable: true },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t},\n\tbns_name_events: {\n\t\tblock_height: { type: \"int\" },\n\t\tblock_time: { type: \"timestamp\" },\n\t\tbns_id: { type: \"text\" },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcursor: { type: \"text\" },\n\t\tevent_index: { type: \"int\" },\n\t\tfqn: { type: \"text\" },\n\t\thashed_salted_fqn_preorder: { type: \"text\", nullable: true },\n\t\timported_at: { type: \"int\", nullable: true },\n\t\tname: { type: \"text\" },\n\t\tnamespace: { type: \"text\" },\n\t\towner: { type: \"text\", nullable: true },\n\t\tpreordered_by: { type: \"text\", nullable: true },\n\t\tregistered_at: { type: \"int\", nullable: true },\n\t\trenewal_height: { type: \"int\", nullable: true },\n\t\tstx_burn: { type: \"text\", nullable: true },\n\t\ttopic: { type: \"text\" },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t},\n\tbns_namespace_events: {\n\t\tblock_height: { type: \"int\" },\n\t\tblock_time: { type: \"timestamp\" },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcursor: { type: \"text\" },\n\t\tevent_index: { type: \"int\" },\n\t\tlaunched_at: { type: \"int\", nullable: true },\n\t\tlifetime: { type: \"int\", nullable: true },\n\t\tmanager: { type: \"text\", nullable: true },\n\t\tmanager_frozen: { type: \"boolean\", nullable: true },\n\t\tmanager_transfers_disabled: { type: \"boolean\", nullable: true },\n\t\tnamespace: { type: \"text\" },\n\t\tprice_frozen: { type: \"boolean\", nullable: true },\n\t\tprice_function: { type: \"text\", nullable: true },\n\t\trevealed_at: { type: \"int\", nullable: true },\n\t\tstatus: { type: \"text\" },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t},\n\tbns_marketplace_events: {\n\t\taction: { type: \"text\" },\n\t\tblock_height: { type: \"int\" },\n\t\tblock_time: { type: \"timestamp\" },\n\t\tbns_id: { type: \"text\" },\n\t\tcanonical: { type: \"boolean\" },\n\t\tcommission: { type: \"text\", nullable: true },\n\t\tcursor: { type: \"text\" },\n\t\tevent_index: { type: \"int\" },\n\t\tprice_ustx: { type: \"text\", nullable: true },\n\t\ttx_id: { type: \"text\" },\n\t\ttx_index: { type: \"int\" },\n\t},\n\tbns_names: {\n\t\tbns_id: { type: \"text\" },\n\t\tfqn: { type: \"text\" },\n\t\tlast_event_at: { type: \"timestamp\" },\n\t\tlast_event_cursor: { type: \"text\" },\n\t\tname: { type: \"text\" },\n\t\tnamespace: { type: \"text\" },\n\t\towner: { type: \"text\" },\n\t\tregistered_at: { type: \"int\", nullable: true },\n\t\trenewal_height: { type: \"int\", nullable: true },\n\t},\n\tbns_namespaces: {\n\t\tlast_event_at: { type: \"timestamp\" },\n\t\tlast_event_cursor: { type: \"text\" },\n\t\tlaunched_at: { type: \"int\", nullable: true },\n\t\tlifetime: { type: \"int\", nullable: true },\n\t\tmanager: { type: \"text\", nullable: true },\n\t\tmanager_frozen: { type: \"boolean\" },\n\t\tname_count: { type: \"int\" },\n\t\tnamespace: { type: \"text\" },\n\t\tprice_frozen: { type: \"boolean\" },\n\t},\n\tburn_block_rewards: {\n\t\tamount_sats: { type: \"text\" },\n\t\tburn_amount: { type: \"text\" },\n\t\tburn_block_hash: { type: \"text\" },\n\t\tburn_block_height: { type: \"int\" },\n\t\tcursor: { type: \"text\" },\n\t\trecipient_btc: { type: \"text\" },\n\t\treward_index: { type: \"int\" },\n\t},\n\tburn_block_reward_slots: {\n\t\tburn_block_hash: { type: \"text\" },\n\t\tburn_block_height: { type: \"int\" },\n\t\tcursor: { type: \"text\" },\n\t\tholder_btc: { type: \"text\" },\n\t\tslot_index: { type: \"int\" },\n\t},\n\tevents: {\n\t\tblock_height: { type: \"int\" },\n\t\tdata: { type: \"jsonb\" },\n\t\tevent_index: { type: \"int\" },\n\t\ttx_id: { type: \"text\" },\n\t\ttype: { type: \"text\" },\n\t},\n\tchain_reorgs: {\n\t\tdetected_at: { type: \"timestamp\" },\n\t},\n} as const satisfies Record<\n\tkeyof typeof SOURCE_READ_COLUMNS,\n\tRecord<string, IndexColumn>\n>;\n\nexport type IndexPrimaryKey = readonly string[] | null;\n\n// Primary key per read table, for codegen targets that require a model identity\n// (Prisma). Every listed column must be a read column (drift-tested). `null` = no\n// usable read-column key — the physical PK is a synthetic id excluded from the\n// read contract (chain_reorgs) — so Prisma omits the table. `events` uses its\n// natural unique (tx_id, event_index); its physical PK is a synthetic uuid not\n// surfaced in the read set.\nexport const SOURCE_READ_PKS = {\n\tblocks: [\"height\"],\n\tdecoded_events: [\"cursor\"],\n\ttransactions: [\"tx_id\"],\n\tmempool_transactions: [\"seq\"],\n\tpox4_calls: [\"cursor\"],\n\tpox5_events: [\"cursor\"],\n\tsbtc_events: [\"cursor\"],\n\tsbtc_token_events: [\"cursor\"],\n\tbns_name_events: [\"cursor\"],\n\tbns_namespace_events: [\"cursor\"],\n\tbns_marketplace_events: [\"cursor\"],\n\tbns_names: [\"fqn\"],\n\tbns_namespaces: [\"namespace\"],\n\tburn_block_rewards: [\"cursor\"],\n\tburn_block_reward_slots: [\"cursor\"],\n\tevents: [\"tx_id\", \"event_index\"],\n\tchain_reorgs: null,\n} as const satisfies Record<keyof typeof SOURCE_READ_COLUMNS, IndexPrimaryKey>;\n",
10
+ "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",
11
11
  "/**\n * Per-migration DB-plane gating for the source/target split.\n *\n * Under the split, SOURCE (chain DB) holds only chain+decoded tables — the\n * control-plane tables were dropped to reclaim space — while TARGET (platform\n * DB) holds the control plane. `migrate.ts` still runs EVERY migration on EVERY\n * database (kysely integrity: the provider set must never be filtered per-DB, or\n * kysely throws \"previously executed migration is missing\" because each DB's\n * `kysely_migration` already records all of them). Instead, `migrate.ts` sets a\n * role before each pass and a migration gates its DDL with the helpers below: a\n * control migration's `up()` is a no-op on SOURCE but is still recorded applied,\n * so there is no missing-migration error and no re-run.\n *\n * `'both'` is single-DB / collapsed-split mode (dev / OSS / CI): every helper\n * runs, identical to pre-split behavior.\n *\n * Authoring a new migration under the split:\n * export async function up(db: Kysely<unknown>): Promise<void> {\n * await onControlPlane(() => sql`ALTER TABLE accounts ADD COLUMN …`.execute(db));\n * await onChainPlane(() => sql`ALTER TABLE blocks ADD COLUMN …`.execute(db));\n * // schema-wide / mixed statements: leave unwrapped (run on both).\n * }\n */\n\nexport type MigrationRole = \"source\" | \"target\" | \"both\";\n\n// Module-level singleton: migrate runs sequentially in one process, one target\n// at a time, so there is no concurrency to guard.\nlet currentRole: MigrationRole = \"both\";\n\nexport function setMigrationRole(role: MigrationRole): void {\n\tcurrentRole = role;\n}\n\nexport function getMigrationRole(): MigrationRole {\n\treturn currentRole;\n}\n\n/** Run control-plane (TARGET) DDL only when this pass targets the control plane. */\nexport async function onControlPlane(fn: () => Promise<void>): Promise<void> {\n\tif (currentRole === \"target\" || currentRole === \"both\") await fn();\n}\n\n/** Run chain/decoded (SOURCE) DDL only when this pass targets the chain plane. */\nexport async function onChainPlane(fn: () => Promise<void>): Promise<void> {\n\tif (currentRole === \"source\" || currentRole === \"both\") await fn();\n}\n",
12
- "import type { Database } from \"./types.ts\";\n\nexport type DbPlane = \"source\" | \"target\" | \"both\";\n\n/**\n * Canonical table → DB-plane mapping for the source/target split.\n *\n * SOURCE = chain + decoded (the `postgres` instance); TARGET = control plane\n * (the `postgres-platform` instance). `both` = present/used on both planes\n * (`service_heartbeats`: the indexer writes its row on SOURCE, the\n * subgraph-processor writes its row on TARGET).\n *\n * `satisfies Record<keyof Database, DbPlane>` makes adding a table to `Database`\n * without classifying it here a COMPILE error. This is the single source of\n * truth for the split — `docker/SCHEMA_SPLIT.md` and the cutover script's\n * `CONTROL_TABLES` mirror the `target` set (guarded by `table-plane.test.ts`).\n * Use it to decide which migration helper a table's DDL belongs in\n * (`onControlPlane` for `target`, `onChainPlane` for `source`).\n *\n * Note: `kysely_migration` / `kysely_migration_lock` are kysely-managed (not in\n * `Database`) and exist on both — they are intentionally not listed here.\n */\nexport const TABLE_TO_DB = {\n\t// ── SOURCE: raw chain ──\n\tblocks: \"source\",\n\ttransactions: \"source\",\n\tevents: \"source\",\n\tvm_events: \"source\",\n\ttransactions_archive: \"source\",\n\tevents_archive: \"source\",\n\tvm_events_archive: \"source\",\n\tdead_letter_events: \"source\",\n\tmempool_transactions: \"source\",\n\tindex_progress: \"source\",\n\tcontracts: \"source\",\n\tchain_reorgs: \"source\",\n\t// Chain-derived read memo — keyed on index_block_hash, lives with the\n\t// blocks it pins to.\n\tchain_read_cache: \"source\",\n\t// Staged fork contenders — raw chain data, resolved during ingest.\n\tpending_fork_blocks: \"source\",\n\t// Exact observer callback receipts — the replay authority sits with chain data.\n\tobserver_journal: \"source\",\n\t// Declared scope — belongs with the chain whose start it declares.\n\tsync_scopes: \"source\",\n\t// Coverage kernel — attests the chain it sits next to.\n\tstage_registry: \"source\",\n\tstage_runs: \"source\",\n\tstage_block_receipts: \"source\",\n\tcoverage_segments: \"source\",\n\tstage_failures: \"source\",\n\t// ── SOURCE: decoded ──\n\tdecoded_events: \"source\",\n\tdecoder_checkpoints: \"source\",\n\tpox4_calls: \"source\",\n\tpox5_events: \"source\",\n\tburn_block_rewards: \"source\",\n\tburn_block_reward_slots: \"source\",\n\tsbtc_events: \"source\",\n\tsbtc_token_events: \"source\",\n\tsbtc_settlements: \"source\",\n\tbns_name_events: \"source\",\n\tbns_namespace_events: \"source\",\n\tbns_marketplace_events: \"source\",\n\tbns_names: \"source\",\n\tbns_namespaces: \"source\",\n\t// ── TARGET: accounts / auth / billing ──\n\tinstances: \"target\",\n\taccounts: \"target\",\n\tapi_keys: \"target\",\n\tsessions: \"target\",\n\tmagic_links: \"target\",\n\taccount_spend_caps: \"target\",\n\tprocessed_stripe_events: \"target\",\n\t// ── TARGET: webhooks ──\n\twebhooks: \"target\",\n\twebhook_outbox: \"target\",\n\twebhook_deliveries: \"target\",\n\ttrigger_evaluator_state: \"target\",\n\t// ── TARGET: subgraphs + metadata ──\n\tsubgraphs: \"target\",\n\tsubgraph_operations: \"target\",\n\tsubgraph_health_snapshots: \"target\",\n\tsubgraph_gaps: \"target\",\n\tsubgraph_violations: \"target\",\n\tsubgraph_processing_stats: \"target\",\n\taccount_credits: \"target\",\n\t// ── TARGET: archive fetch gate (design-f089) ──\n\tarchive_fetches: \"target\",\n\t// ── TARGET: public waitlist pages ──\n\twaitlists: \"target\",\n\twaitlist_signups: \"target\",\n\t// ── BOTH ──\n\tservice_heartbeats: \"both\",\n} satisfies Record<keyof Database, DbPlane>;\n",
12
+ "import type { Database } from \"./types.ts\";\n\nexport type DbPlane = \"source\" | \"target\" | \"both\";\n\n/**\n * Canonical table → DB-plane mapping for the source/target split.\n *\n * SOURCE = chain + decoded (the `postgres` instance); TARGET = control plane\n * (the `postgres-platform` instance). `both` = present/used on both planes\n * (`service_heartbeats`: the indexer writes its row on SOURCE, the\n * subgraph-processor writes its row on TARGET).\n *\n * `satisfies Record<keyof Database, DbPlane>` makes adding a table to `Database`\n * without classifying it here a COMPILE error. This is the single source of\n * truth for the split — `docker/SCHEMA_SPLIT.md` and the cutover script's\n * `CONTROL_TABLES` mirror the `target` set (guarded by `table-plane.test.ts`).\n * Use it to decide which migration helper a table's DDL belongs in\n * (`onControlPlane` for `target`, `onChainPlane` for `source`).\n *\n * Note: `kysely_migration` / `kysely_migration_lock` are kysely-managed (not in\n * `Database`) and exist on both — they are intentionally not listed here.\n */\nexport const TABLE_TO_DB = {\n\t// ── SOURCE: raw chain ──\n\tblocks: \"source\",\n\ttransactions: \"source\",\n\tevents: \"source\",\n\tvm_events: \"source\",\n\ttransactions_archive: \"source\",\n\tevents_archive: \"source\",\n\tvm_events_archive: \"source\",\n\tdead_letter_events: \"source\",\n\tmempool_transactions: \"source\",\n\tindex_progress: \"source\",\n\tcontracts: \"source\",\n\tchain_reorgs: \"source\",\n\t// Chain-derived read memo — keyed on index_block_hash, lives with the\n\t// blocks it pins to.\n\tchain_read_cache: \"source\",\n\t// Staged fork contenders — raw chain data, resolved during ingest.\n\tpending_fork_blocks: \"source\",\n\t// Exact observer callback receipts — the replay authority sits with chain data.\n\tobserver_journal: \"source\",\n\t// Declared scope — belongs with the chain whose start it declares.\n\tsync_scopes: \"source\",\n\t// Coverage kernel — attests the chain it sits next to.\n\tstage_registry: \"source\",\n\tstage_runs: \"source\",\n\tstage_block_receipts: \"source\",\n\tcoverage_segments: \"source\",\n\tstage_failures: \"source\",\n\t// ── SOURCE: decoded ──\n\tdecoded_events: \"source\",\n\tdecoder_checkpoints: \"source\",\n\tpox4_calls: \"source\",\n\tpox5_events: \"source\",\n\tburn_block_rewards: \"source\",\n\tburn_block_reward_slots: \"source\",\n\tsbtc_events: \"source\",\n\tsbtc_token_events: \"source\",\n\tsbtc_settlements: \"source\",\n\tbns_name_events: \"source\",\n\tbns_namespace_events: \"source\",\n\tbns_marketplace_events: \"source\",\n\tbns_names: \"source\",\n\tbns_namespaces: \"source\",\n\t// ── TARGET: accounts / auth / billing ──\n\tinstances: \"target\",\n\taccounts: \"target\",\n\tapi_keys: \"target\",\n\tsessions: \"target\",\n\tmagic_links: \"target\",\n\taccount_spend_caps: \"target\",\n\tprocessed_stripe_events: \"target\",\n\t// ── TARGET: webhooks ──\n\twebhooks: \"target\",\n\twebhook_outbox: \"target\",\n\twebhook_deliveries: \"target\",\n\ttrigger_evaluator_state: \"target\",\n\t// ── TARGET: subgraphs + metadata ──\n\tsubgraphs: \"target\",\n\tsubgraph_operations: \"target\",\n\tsubgraph_health_snapshots: \"target\",\n\tsubgraph_gaps: \"target\",\n\tsubgraph_violations: \"target\",\n\tsubgraph_processing_stats: \"target\",\n\taccount_credits: \"target\",\n\t// ── TARGET: archive fetch gate (design-f089) ──\n\tarchive_fetches: \"target\",\n\t// ── TARGET: metered ledger (plan-049) ──\n\tusage_ledger: \"target\",\n\t// ── TARGET: public waitlist pages ──\n\twaitlists: \"target\",\n\twaitlist_signups: \"target\",\n\t// ── BOTH ──\n\tservice_heartbeats: \"both\",\n} satisfies Record<keyof Database, DbPlane>;\n",
13
13
  "import type { Kysely, Transaction } from \"kysely\";\nimport { getSourceDb, sql } from \"../index.ts\";\nimport type { Database } from \"../types.ts\";\n\nexport type ChainReorgCursor = {\n\tblock_height: number;\n\tevent_index: number;\n};\n\n/**\n * Wall-clock resume cursor for `readChainReorgsSince`. `detected_at` is kept as\n * a raw string all the way to SQL (cast to timestamptz there) because Postgres\n * stores microseconds and a JS Date round-trip truncates to milliseconds —\n * truncation makes `detected_at > cursor` re-match the row the cursor came\n * from, re-delivering the same reorg forever. `id` breaks ties between rows\n * sharing a detected_at.\n */\nexport type ChainReorgTimeCursor = {\n\tdetected_at: string;\n\tid: string | null;\n};\n\nexport type ChainReorgRecord = {\n\tid: string;\n\tdetected_at: string;\n\tfork_point_height: number;\n\told_index_block_hash: string | null;\n\tnew_index_block_hash: string | null;\n\torphaned_range: { from: string; to: string };\n\tnew_canonical_tip: string;\n};\n\nexport type InsertChainReorgParams = {\n\tforkPointHeight: number;\n\toldIndexBlockHash?: string | null;\n\tnewIndexBlockHash?: string | null;\n\torphanedFrom: ChainReorgCursor;\n\torphanedTo: ChainReorgCursor;\n\tnewCanonicalTip: ChainReorgCursor;\n\tdb?: Kysely<Database> | Transaction<Database>;\n};\n\nexport type ReadChainReorgsSinceParams = {\n\tsince: Date | ChainReorgTimeCursor | ChainReorgCursor;\n\tlimit: number;\n\tdb?: Kysely<Database>;\n};\n\nexport type ReadChainReorgsForRangeParams = {\n\tfrom: ChainReorgCursor;\n\tto: ChainReorgCursor;\n\tdb?: Kysely<Database>;\n};\n\nexport type ReadChainReorgsForHeightRangeParams = {\n\tfromHeight: number;\n\ttoHeight: number;\n\tdb?: Kysely<Database>;\n};\n\ntype ChainReorgRow = {\n\tid: string;\n\tdetected_at: Date | string;\n\t/** Microsecond-precision ISO text, selected alongside `detected_at` where\n\t * the value feeds a resume cursor (pg's Date parsing drops microseconds). */\n\tdetected_at_us?: string;\n\tfork_point_height: string | number;\n\told_index_block_hash: string | null;\n\tnew_index_block_hash: string | null;\n\torphaned_from_height: string | number;\n\torphaned_from_event_index: string | number;\n\torphaned_to_height: string | number;\n\torphaned_to_event_index: string | number;\n\tnew_canonical_height: string | number;\n\tnew_canonical_event_index: string | number;\n};\n\nexport function encodeChainReorgCursor(cursor: ChainReorgCursor): string {\n\treturn `${cursor.block_height}:${cursor.event_index}`;\n}\n\nfunction normalizeRow(row: ChainReorgRow): ChainReorgRecord {\n\tconst detectedAt =\n\t\trow.detected_at_us ??\n\t\t(row.detected_at instanceof Date\n\t\t\t? row.detected_at.toISOString()\n\t\t\t: new Date(row.detected_at).toISOString());\n\n\treturn {\n\t\tid: row.id,\n\t\tdetected_at: detectedAt,\n\t\tfork_point_height: Number(row.fork_point_height),\n\t\told_index_block_hash: row.old_index_block_hash,\n\t\tnew_index_block_hash: row.new_index_block_hash,\n\t\torphaned_range: {\n\t\t\tfrom: encodeChainReorgCursor({\n\t\t\t\tblock_height: Number(row.orphaned_from_height),\n\t\t\t\tevent_index: Number(row.orphaned_from_event_index),\n\t\t\t}),\n\t\t\tto: encodeChainReorgCursor({\n\t\t\t\tblock_height: Number(row.orphaned_to_height),\n\t\t\t\tevent_index: Number(row.orphaned_to_event_index),\n\t\t\t}),\n\t\t},\n\t\tnew_canonical_tip: encodeChainReorgCursor({\n\t\t\tblock_height: Number(row.new_canonical_height),\n\t\t\tevent_index: Number(row.new_canonical_event_index),\n\t\t}),\n\t};\n}\n\nexport async function insertChainReorg(\n\tparams: InsertChainReorgParams,\n): Promise<ChainReorgRecord> {\n\tconst db = params.db ?? getSourceDb();\n\tconst row = await db\n\t\t.insertInto(\"chain_reorgs\")\n\t\t.values({\n\t\t\tfork_point_height: params.forkPointHeight,\n\t\t\told_index_block_hash: params.oldIndexBlockHash ?? null,\n\t\t\tnew_index_block_hash: params.newIndexBlockHash ?? null,\n\t\t\torphaned_from_height: params.orphanedFrom.block_height,\n\t\t\torphaned_from_event_index: params.orphanedFrom.event_index,\n\t\t\torphaned_to_height: params.orphanedTo.block_height,\n\t\t\torphaned_to_event_index: params.orphanedTo.event_index,\n\t\t\tnew_canonical_height: params.newCanonicalTip.block_height,\n\t\t\tnew_canonical_event_index: params.newCanonicalTip.event_index,\n\t\t})\n\t\t.returningAll()\n\t\t.executeTakeFirstOrThrow();\n\n\treturn normalizeRow(row);\n}\n\n/** Microsecond-precision ISO text for `detected_at`. Selected wherever the\n * value can feed a resume cursor: pg parses timestamptz into a JS Date, which\n * drops microseconds, and a truncated cursor re-matches the row it came from. */\nconst detectedAtUs = sql<string>`to_char(detected_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')`;\n\nexport async function readChainReorgsSince(\n\tparams: ReadChainReorgsSinceParams,\n): Promise<ChainReorgRecord[]> {\n\tconst db = params.db ?? getSourceDb();\n\tconst limit = Math.min(1000, Math.max(1, params.limit));\n\tconst { since } = params;\n\n\tif (since instanceof Date || \"detected_at\" in since) {\n\t\tconst cursor: ChainReorgTimeCursor =\n\t\t\tsince instanceof Date\n\t\t\t\t? { detected_at: since.toISOString(), id: null }\n\t\t\t\t: since;\n\t\t// The (…::text)::timestamptz double cast is load-bearing: a bare\n\t\t// ::timestamptz makes the driver infer the param as a timestamp and\n\t\t// convert the string client-side at millisecond precision, silently\n\t\t// discarding microseconds — the exact truncation this cursor exists to\n\t\t// avoid. ::text forces the raw string through so Postgres does the cast.\n\t\tconst result = cursor.id\n\t\t\t? await sql<ChainReorgRow>`\n\t\t\t\t\tSELECT *, ${detectedAtUs} AS detected_at_us\n\t\t\t\t\tFROM chain_reorgs\n\t\t\t\t\tWHERE (detected_at, id) > ((${cursor.detected_at}::text)::timestamptz, ${cursor.id}::uuid)\n\t\t\t\t\tORDER BY detected_at ASC, id ASC\n\t\t\t\t\tLIMIT ${limit}\n\t\t\t\t`.execute(db)\n\t\t\t: await sql<ChainReorgRow>`\n\t\t\t\t\tSELECT *, ${detectedAtUs} AS detected_at_us\n\t\t\t\t\tFROM chain_reorgs\n\t\t\t\t\tWHERE detected_at > (${cursor.detected_at}::text)::timestamptz\n\t\t\t\t\tORDER BY detected_at ASC, id ASC\n\t\t\t\t\tLIMIT ${limit}\n\t\t\t\t`.execute(db);\n\t\treturn result.rows.map(normalizeRow);\n\t}\n\n\tconst result = await sql<ChainReorgRow>`\n\t\tSELECT *, ${detectedAtUs} AS detected_at_us\n\t\tFROM chain_reorgs\n\t\tWHERE\n\t\t\torphaned_to_height > ${since.block_height}\n\t\t\tOR (\n\t\t\t\torphaned_to_height = ${since.block_height}\n\t\t\t\tAND orphaned_to_event_index >= ${since.event_index}\n\t\t\t)\n\t\tORDER BY detected_at ASC, id ASC\n\t\tLIMIT ${limit}\n\t`.execute(db);\n\n\treturn result.rows.map(normalizeRow);\n}\n\n/**\n * Reorgs overlapping the block-height window [fromHeight, toHeight], ignoring\n * event_index. For cursor keyspaces that are NOT event-indexed (the\n * transactions / contract-calls endpoints key on block_height:tx_index): a\n * height-granular overlap. Over-inclusive — a partially-orphaned height in range\n * surfaces even if the page's specific rows survived — but never under-reports.\n */\nexport async function readChainReorgsForHeightRange(\n\tparams: ReadChainReorgsForHeightRangeParams,\n): Promise<ChainReorgRecord[]> {\n\treturn readChainReorgsForRange({\n\t\tfrom: { block_height: params.fromHeight, event_index: 0 },\n\t\t// int4 max — event_index is a Postgres `integer`, so a larger sentinel\n\t\t// (e.g. Number.MAX_SAFE_INTEGER) overflows when bound for comparison.\n\t\tto: { block_height: params.toHeight, event_index: 2_147_483_647 },\n\t\tdb: params.db,\n\t});\n}\n\nexport async function readChainReorgsForRange(\n\tparams: ReadChainReorgsForRangeParams,\n): Promise<ChainReorgRecord[]> {\n\tconst db = params.db ?? getSourceDb();\n\tconst { from, to } = params;\n\tconst { rows } = await sql<ChainReorgRow>`\n\t\tSELECT *, ${detectedAtUs} AS detected_at_us\n\t\tFROM chain_reorgs\n\t\tWHERE\n\t\t\t(\n\t\t\t\torphaned_from_height < ${to.block_height}\n\t\t\t\tOR (\n\t\t\t\t\torphaned_from_height = ${to.block_height}\n\t\t\t\t\tAND orphaned_from_event_index <= ${to.event_index}\n\t\t\t\t)\n\t\t\t)\n\t\t\tAND (\n\t\t\t\torphaned_to_height > ${from.block_height}\n\t\t\t\tOR (\n\t\t\t\t\torphaned_to_height = ${from.block_height}\n\t\t\t\t\tAND orphaned_to_event_index >= ${from.event_index}\n\t\t\t\t)\n\t\t\t)\n\t\tORDER BY detected_at ASC, id ASC\n\t`.execute(db);\n\n\treturn rows.map(normalizeRow);\n}\n"
14
14
  ],
15
- "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,M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A;AAAA,IACA;AAAA,EACD;AAAA,EACA,gBAAgB;AAAA,IACf;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,cAAc;AAAA,IACb;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,EACD;AAAA,EACA,YAAY;AAAA,IACX;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,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,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,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,WAAW;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,gBAAgB;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,oBAAoB;AAAA,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ACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,cAAc;AAAA,IACb;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,EACD;AAAA,EACA,YAAY;AAAA,IACX;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,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,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,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,WAAW;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,gBAAgB;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,oBAAoB;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,yBAAyB;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AAAA,EACA,QA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,GAAG;AAAA,wCACO,GAAG;AAAA;AAAA;AAAA;AAAA,2BAIhB,KAAK;AAAA;AAAA,4BAEJ,KAAK;AAAA,sCACK,KAAK;AAAA;AAAA;AAAA;AAAA,GAIxC,QAAQ,EAAE;AAAA,EAEZ,OAAO,KAAK,IAAI,YAAY;AAAA;",
16
+ "debugId": "F100A5A34ED1F1CD64756E2164756E21",
17
17
  "names": []
18
18
  }
@@ -153,7 +153,6 @@ interface SubgraphsTable {
153
153
  handler_code: string | null;
154
154
  source_code: string | null;
155
155
  project_id: string | null;
156
- visibility: Generated<string>;
157
156
  /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
158
157
  expires_at: Date | null;
159
158
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
@@ -783,6 +782,7 @@ interface Database {
783
782
  coverage_segments: CoverageSegmentsTable;
784
783
  stage_failures: StageFailuresTable;
785
784
  archive_fetches: ArchiveFetchesTable;
785
+ usage_ledger: UsageLedgerTable;
786
786
  waitlists: WaitlistsTable;
787
787
  waitlist_signups: WaitlistSignupsTable;
788
788
  }
@@ -827,6 +827,27 @@ interface ArchiveFetchesTable {
827
827
  via_allowance: Generated<boolean>;
828
828
  charged_at: Generated<Date>;
829
829
  }
830
+ /**
831
+ * One metered ledger for every billable unit (archive partitions, hosted
832
+ * Index/Streams rows, and future hosted-stack meters). Append-only, written
833
+ * only by `meter()`. `idempotency_key` is UNIQUE so a retried submission
834
+ * no-ops instead of double-charging. `debited` is false when the balance
835
+ * (or a spend cap) refused the charge — the row still exists so the gap is
836
+ * visible, never silently dropped. `usd_micros` is negative for a Stripe
837
+ * top-up (`unit: "topup"`).
838
+ */
839
+ interface UsageLedgerTable {
840
+ id: Generated<string>;
841
+ account_id: string;
842
+ unit: string;
843
+ quantity: string | number | bigint;
844
+ usd_micros: string | number | bigint;
845
+ debited: Generated<boolean>;
846
+ source: string;
847
+ idempotency_key: string;
848
+ occurred_at: Generated<Date>;
849
+ recorded_at: Generated<Date>;
850
+ }
830
851
  type Contract = Selectable<ContractsTable>;
831
852
  type WebhookStatus = "active" | "paused" | "error";
832
853
  /** Polymorphic webhook mode: `subgraph` reacts to processed table rows;
@@ -890,6 +911,10 @@ interface WebhookOutboxTable {
890
911
  failed_at: Date | null;
891
912
  locked_by: string | null;
892
913
  locked_until: Date | null;
914
+ /** Set when a reorg marks an in-flight row `dead` instead of retrying it
915
+ * into an orphaned fork. Null otherwise — delivery failures track their
916
+ * history on `webhooks.last_error`, not per-row. */
917
+ last_error: string | null;
893
918
  created_at: Generated<Date>;
894
919
  }
895
920
  interface WebhookDeliveriesTable {
@@ -990,4 +1015,4 @@ declare function resolveTraitContractIds(db: Kysely<Database>, trait: string, as
990
1015
  * the new fork and recordContractDeploy re-canonicalizes them.
991
1016
  */
992
1017
  declare function markContractsNonCanonical(db: Kysely<Database>, fromBlockHeight: number): Promise<void>;
993
- export { setContractAbi, resolveTraitContractIds, recordContractDeploy, markContractsNonCanonical, listContractsPendingAbi, listContractsByTrait, getContract, Conformance, AbiStatus };
1018
+ export { AbiStatus, Conformance, getContract, listContractsByTrait, listContractsPendingAbi, markContractsNonCanonical, recordContractDeploy, resolveTraitContractIds, setContractAbi };
@@ -1,18 +1,5 @@
1
- import { createRequire } from "node:module";
2
- var __defProp = Object.defineProperty;
3
- var __returnValue = (v) => v;
4
- function __exportSetter(name, newValue) {
5
- this[name] = __returnValue.bind(null, newValue);
6
- }
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, {
10
- get: all[name],
11
- enumerable: true,
12
- configurable: true,
13
- set: __exportSetter.bind(all, name)
14
- });
15
- };
1
+ // src/db/queries/contracts.ts
2
+ import { sql as sql2 } from "kysely";
16
3
 
17
4
  // src/db/jsonb.ts
18
5
  import { sql } from "kysely";
@@ -32,7 +19,6 @@ function parseJsonb(value) {
32
19
  }
33
20
 
34
21
  // src/db/queries/contracts.ts
35
- import { sql as sql2 } from "kysely";
36
22
  async function recordContractDeploy(db, row) {
37
23
  await db.insertInto("contracts").values({
38
24
  contract_id: row.contractId,
@@ -81,14 +67,14 @@ async function markContractsNonCanonical(db, fromBlockHeight) {
81
67
  await db.updateTable("contracts").set({ canonical: false }).where("block_height", ">=", fromBlockHeight).execute();
82
68
  }
83
69
  export {
84
- setContractAbi,
85
- resolveTraitContractIds,
86
- recordContractDeploy,
87
- markContractsNonCanonical,
88
- listContractsPendingAbi,
70
+ getContract,
89
71
  listContractsByTrait,
90
- getContract
72
+ listContractsPendingAbi,
73
+ markContractsNonCanonical,
74
+ recordContractDeploy,
75
+ resolveTraitContractIds,
76
+ setContractAbi
91
77
  };
92
78
 
93
- //# debugId=5B124A4770F3CE2264756E2164756E21
79
+ //# debugId=E2278282AC73418664756E2164756E21
94
80
  //# sourceMappingURL=contracts.js.map
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/db/jsonb.ts", "../src/db/queries/contracts.ts"],
3
+ "sources": ["../src/db/queries/contracts.ts", "../src/db/jsonb.ts"],
4
4
  "sourcesContent": [
5
- "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",
6
- "import { type Kysely, sql } from \"kysely\";\nimport { jsonb } from \"../jsonb.ts\";\nimport type { Contract, Database } from \"../types.ts\";\n\n/**\n * Contract registry queries — backing for trait-based discovery. Populated from\n * contract deploys; ABI fetched async; standards inferred by static analysis.\n */\n\nexport type AbiStatus = \"pending\" | \"fetched\" | \"failed\" | \"unparseable\";\n\n/**\n * Record a contract deploy (idempotent). ABI is fetched separately + async.\n * On conflict the row is re-canonicalized rather than skipped: after a reorg\n * flips contracts non-canonical (markContractsNonCanonical), discovery\n * re-selects any id whose deploy tx exists on the new fork and this upsert\n * restores `canonical` with the fork's height. ABI fields are untouched, so a\n * previously fetched ABI survives the round trip.\n */\nexport async function recordContractDeploy(\n\tdb: Kysely<Database>,\n\trow: { contractId: string; deployer: string; blockHeight: number },\n): Promise<void> {\n\tawait db\n\t\t.insertInto(\"contracts\")\n\t\t.values({\n\t\t\tcontract_id: row.contractId,\n\t\t\tdeployer: row.deployer,\n\t\t\tblock_height: row.blockHeight,\n\t\t})\n\t\t.onConflict((oc) =>\n\t\t\toc.column(\"contract_id\").doUpdateSet({\n\t\t\t\tdeployer: row.deployer,\n\t\t\t\tblock_height: row.blockHeight,\n\t\t\t\tcanonical: true,\n\t\t\t}),\n\t\t)\n\t\t.execute();\n}\n\n/** Store a fetched ABI + the traits/standards derived from it. */\nexport async function setContractAbi(\n\tdb: Kysely<Database>,\n\tcontractId: string,\n\tdata: {\n\t\tabi: unknown | null;\n\t\tstatus: AbiStatus;\n\t\tdeclaredTraits?: string[];\n\t\tinferredStandards?: string[];\n\t},\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"contracts\")\n\t\t.set({\n\t\t\tabi: data.abi == null ? null : jsonb(data.abi),\n\t\t\tabi_status: data.status,\n\t\t\tabi_fetched_at: new Date(),\n\t\t\t...(data.declaredTraits ? { declared_traits: data.declaredTraits } : {}),\n\t\t\t...(data.inferredStandards\n\t\t\t\t? { inferred_standards: data.inferredStandards }\n\t\t\t\t: {}),\n\t\t})\n\t\t.where(\"contract_id\", \"=\", contractId)\n\t\t.execute();\n}\n\n/**\n * A contract reorged out and not (yet) redeployed on the new fork is not on\n * the canonical chain — serve 404, not its stale row/ABI. Matches every other\n * contracts read (list, trait scope, pending-ABI), which already filter.\n */\nexport async function getContract(\n\tdb: Kysely<Database>,\n\tcontractId: string,\n): Promise<Contract | null> {\n\treturn (\n\t\t(await db\n\t\t\t.selectFrom(\"contracts\")\n\t\t\t.selectAll()\n\t\t\t.where(\"contract_id\", \"=\", contractId)\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\n/** Contracts still awaiting an ABI fetch (drives the fetch/backfill worker). */\nexport async function listContractsPendingAbi(\n\tdb: Kysely<Database>,\n\tlimit = 100,\n): Promise<Contract[]> {\n\treturn db\n\t\t.selectFrom(\"contracts\")\n\t\t.selectAll()\n\t\t.where(\"abi_status\", \"=\", \"pending\")\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.orderBy(\"block_height\", \"asc\")\n\t\t.limit(limit)\n\t\t.execute();\n}\n\nexport type Conformance = \"declared\" | \"inferred\" | \"any\";\n\n/** Discovery: contracts matching a trait/standard, by conformance source. */\nexport async function listContractsByTrait(\n\tdb: Kysely<Database>,\n\ttrait: string,\n\topts: { conformance?: Conformance; limit?: number; afterId?: string } = {},\n): Promise<Contract[]> {\n\tconst conformance = opts.conformance ?? \"any\";\n\tlet q = db.selectFrom(\"contracts\").selectAll().where(\"canonical\", \"=\", true);\n\n\tif (conformance === \"declared\") {\n\t\tq = q.where(sql<boolean>`${sql.ref(\"declared_traits\")} @> ARRAY[${trait}]`);\n\t} else if (conformance === \"inferred\") {\n\t\tq = q.where(\n\t\t\tsql<boolean>`${sql.ref(\"inferred_standards\")} @> ARRAY[${trait}]`,\n\t\t);\n\t} else {\n\t\tq = q.where(\n\t\t\tsql<boolean>`(${sql.ref(\"declared_traits\")} @> ARRAY[${trait}] OR ${sql.ref(\"inferred_standards\")} @> ARRAY[${trait}])`,\n\t\t);\n\t}\n\n\tif (opts.afterId) q = q.where(\"contract_id\", \">\", opts.afterId);\n\treturn q\n\t\t.orderBy(\"contract_id\", \"asc\")\n\t\t.limit(opts.limit ?? 100)\n\t\t.execute();\n}\n\n/**\n * As-of-block trait resolution (B4): contract IDs conforming to `trait` whose\n * deploy block ≤ `asOfBlock`. Lets a trait-scoped subgraph reindex a token's\n * full history even if classification lagged its deploy.\n */\nexport async function resolveTraitContractIds(\n\tdb: Kysely<Database>,\n\ttrait: string,\n\tasOfBlock: number,\n): Promise<string[]> {\n\tconst rows = await db\n\t\t.selectFrom(\"contracts\")\n\t\t.select(\"contract_id\")\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.where(\"block_height\", \"<=\", asOfBlock)\n\t\t.where(\n\t\t\tsql<boolean>`(${sql.ref(\"declared_traits\")} @> ARRAY[${trait}] OR ${sql.ref(\"inferred_standards\")} @> ARRAY[${trait}])`,\n\t\t)\n\t\t.execute();\n\treturn rows.map((r) => r.contract_id);\n}\n\n/**\n * Reorg: flip contracts deployed at/above a reorged height to non-canonical.\n * Called from the indexer's handleReorg tx. Recovery is eventual: discovery\n * (discoverDeploys) re-selects non-canonical ids whose deploy tx exists on\n * the new fork and recordContractDeploy re-canonicalizes them.\n */\nexport async function markContractsNonCanonical(\n\tdb: Kysely<Database>,\n\tfromBlockHeight: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"contracts\")\n\t\t.set({ canonical: false })\n\t\t.where(\"block_height\", \">=\", fromBlockHeight)\n\t\t.execute();\n}\n"
5
+ "import { type Kysely, sql } from \"kysely\";\nimport { jsonb } from \"../jsonb.ts\";\nimport type { Contract, Database } from \"../types.ts\";\n\n/**\n * Contract registry queries — backing for trait-based discovery. Populated from\n * contract deploys; ABI fetched async; standards inferred by static analysis.\n */\n\nexport type AbiStatus = \"pending\" | \"fetched\" | \"failed\" | \"unparseable\";\n\n/**\n * Record a contract deploy (idempotent). ABI is fetched separately + async.\n * On conflict the row is re-canonicalized rather than skipped: after a reorg\n * flips contracts non-canonical (markContractsNonCanonical), discovery\n * re-selects any id whose deploy tx exists on the new fork and this upsert\n * restores `canonical` with the fork's height. ABI fields are untouched, so a\n * previously fetched ABI survives the round trip.\n */\nexport async function recordContractDeploy(\n\tdb: Kysely<Database>,\n\trow: { contractId: string; deployer: string; blockHeight: number },\n): Promise<void> {\n\tawait db\n\t\t.insertInto(\"contracts\")\n\t\t.values({\n\t\t\tcontract_id: row.contractId,\n\t\t\tdeployer: row.deployer,\n\t\t\tblock_height: row.blockHeight,\n\t\t})\n\t\t.onConflict((oc) =>\n\t\t\toc.column(\"contract_id\").doUpdateSet({\n\t\t\t\tdeployer: row.deployer,\n\t\t\t\tblock_height: row.blockHeight,\n\t\t\t\tcanonical: true,\n\t\t\t}),\n\t\t)\n\t\t.execute();\n}\n\n/** Store a fetched ABI + the traits/standards derived from it. */\nexport async function setContractAbi(\n\tdb: Kysely<Database>,\n\tcontractId: string,\n\tdata: {\n\t\tabi: unknown | null;\n\t\tstatus: AbiStatus;\n\t\tdeclaredTraits?: string[];\n\t\tinferredStandards?: string[];\n\t},\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"contracts\")\n\t\t.set({\n\t\t\tabi: data.abi == null ? null : jsonb(data.abi),\n\t\t\tabi_status: data.status,\n\t\t\tabi_fetched_at: new Date(),\n\t\t\t...(data.declaredTraits ? { declared_traits: data.declaredTraits } : {}),\n\t\t\t...(data.inferredStandards\n\t\t\t\t? { inferred_standards: data.inferredStandards }\n\t\t\t\t: {}),\n\t\t})\n\t\t.where(\"contract_id\", \"=\", contractId)\n\t\t.execute();\n}\n\n/**\n * A contract reorged out and not (yet) redeployed on the new fork is not on\n * the canonical chain — serve 404, not its stale row/ABI. Matches every other\n * contracts read (list, trait scope, pending-ABI), which already filter.\n */\nexport async function getContract(\n\tdb: Kysely<Database>,\n\tcontractId: string,\n): Promise<Contract | null> {\n\treturn (\n\t\t(await db\n\t\t\t.selectFrom(\"contracts\")\n\t\t\t.selectAll()\n\t\t\t.where(\"contract_id\", \"=\", contractId)\n\t\t\t.where(\"canonical\", \"=\", true)\n\t\t\t.executeTakeFirst()) ?? null\n\t);\n}\n\n/** Contracts still awaiting an ABI fetch (drives the fetch/backfill worker). */\nexport async function listContractsPendingAbi(\n\tdb: Kysely<Database>,\n\tlimit = 100,\n): Promise<Contract[]> {\n\treturn db\n\t\t.selectFrom(\"contracts\")\n\t\t.selectAll()\n\t\t.where(\"abi_status\", \"=\", \"pending\")\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.orderBy(\"block_height\", \"asc\")\n\t\t.limit(limit)\n\t\t.execute();\n}\n\nexport type Conformance = \"declared\" | \"inferred\" | \"any\";\n\n/** Discovery: contracts matching a trait/standard, by conformance source. */\nexport async function listContractsByTrait(\n\tdb: Kysely<Database>,\n\ttrait: string,\n\topts: { conformance?: Conformance; limit?: number; afterId?: string } = {},\n): Promise<Contract[]> {\n\tconst conformance = opts.conformance ?? \"any\";\n\tlet q = db.selectFrom(\"contracts\").selectAll().where(\"canonical\", \"=\", true);\n\n\tif (conformance === \"declared\") {\n\t\tq = q.where(sql<boolean>`${sql.ref(\"declared_traits\")} @> ARRAY[${trait}]`);\n\t} else if (conformance === \"inferred\") {\n\t\tq = q.where(\n\t\t\tsql<boolean>`${sql.ref(\"inferred_standards\")} @> ARRAY[${trait}]`,\n\t\t);\n\t} else {\n\t\tq = q.where(\n\t\t\tsql<boolean>`(${sql.ref(\"declared_traits\")} @> ARRAY[${trait}] OR ${sql.ref(\"inferred_standards\")} @> ARRAY[${trait}])`,\n\t\t);\n\t}\n\n\tif (opts.afterId) q = q.where(\"contract_id\", \">\", opts.afterId);\n\treturn q\n\t\t.orderBy(\"contract_id\", \"asc\")\n\t\t.limit(opts.limit ?? 100)\n\t\t.execute();\n}\n\n/**\n * As-of-block trait resolution (B4): contract IDs conforming to `trait` whose\n * deploy block ≤ `asOfBlock`. Lets a trait-scoped subgraph reindex a token's\n * full history even if classification lagged its deploy.\n */\nexport async function resolveTraitContractIds(\n\tdb: Kysely<Database>,\n\ttrait: string,\n\tasOfBlock: number,\n): Promise<string[]> {\n\tconst rows = await db\n\t\t.selectFrom(\"contracts\")\n\t\t.select(\"contract_id\")\n\t\t.where(\"canonical\", \"=\", true)\n\t\t.where(\"block_height\", \"<=\", asOfBlock)\n\t\t.where(\n\t\t\tsql<boolean>`(${sql.ref(\"declared_traits\")} @> ARRAY[${trait}] OR ${sql.ref(\"inferred_standards\")} @> ARRAY[${trait}])`,\n\t\t)\n\t\t.execute();\n\treturn rows.map((r) => r.contract_id);\n}\n\n/**\n * Reorg: flip contracts deployed at/above a reorged height to non-canonical.\n * Called from the indexer's handleReorg tx. Recovery is eventual: discovery\n * (discoverDeploys) re-selects non-canonical ids whose deploy tx exists on\n * the new fork and recordContractDeploy re-canonicalizes them.\n */\nexport async function markContractsNonCanonical(\n\tdb: Kysely<Database>,\n\tfromBlockHeight: number,\n): Promise<void> {\n\tawait db\n\t\t.updateTable(\"contracts\")\n\t\t.set({ canonical: false })\n\t\t.where(\"block_height\", \">=\", fromBlockHeight)\n\t\t.execute();\n}\n",
6
+ "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"
7
7
  ],
8
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAWO,SAAS,KAAkB,CAAC,OAAyB;AAAA,EAC3D,MAAM,UAAU,KAAK,UAAU,OAAO,CAAC,IAAI,MAC1C,OAAO,MAAM,WAAW,EAAE,SAAS,IAAI,CACxC,EAAE,QAAQ,MAAM,IAAI;AAAA,EACpB,OAAO,MAAM,IAAI,IAAI,IAAI,iBAAiB;AAAA;AAQpC,SAAS,UAAuB,CAAC,OAAmB;AAAA,EAC1D,IAAI,OAAO,UAAU,UAAU;AAAA,IAC9B,IAAI;AAAA,MACH,OAAO,KAAK,MAAM,KAAK;AAAA,MACtB,MAAM;AAAA,MACP,OAAO;AAAA;AAAA,EAET;AAAA,EACA,OAAQ,SAAS,CAAC;AAAA;;;AC/BnB,gBAAsB;AAmBtB,eAAsB,oBAAoB,CACzC,IACA,KACgB;AAAA,EAChB,MAAM,GACJ,WAAW,WAAW,EACtB,OAAO;AAAA,IACP,aAAa,IAAI;AAAA,IACjB,UAAU,IAAI;AAAA,IACd,cAAc,IAAI;AAAA,EACnB,CAAC,EACA,WAAW,CAAC,OACZ,GAAG,OAAO,aAAa,EAAE,YAAY;AAAA,IACpC,UAAU,IAAI;AAAA,IACd,cAAc,IAAI;AAAA,IAClB,WAAW;AAAA,EACZ,CAAC,CACF,EACC,QAAQ;AAAA;AAIX,eAAsB,cAAc,CACnC,IACA,YACA,MAMgB;AAAA,EAChB,MAAM,GACJ,YAAY,WAAW,EACvB,IAAI;AAAA,IACJ,KAAK,KAAK,OAAO,OAAO,OAAO,MAAM,KAAK,GAAG;AAAA,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AM,OAAe,KAAI,IAAI,iBAAiB,cAAc,QAAQ;AAAA,EAC3E,EAAO,SAAI,gBAAgB,YAAY;AAAA,IACtC,IAAI,EAAE,MACL,OAAe,KAAI,IAAI,oBAAoB,cAAc,QAC1D;AAAA,EACD,EAAO;AAAA,IACN,IAAI,EAAE,MACL,QAAgB,KAAI,IAAI,iBAAiB,cAAc,aAAa,KAAI,IAAI,oBAAoB,cAAc,SAC/G;AAAA;AAAA,EAGD,IAAI,KAAK;AAAA,IAAS,IAAI,EAAE,MAAM,eAAe,KAAK,KAAK,OAAO;AAAA,EAC9D,OAAO,EACL,QAAQ,eAAe,KAAK,EAC5B,MAAM,KAAK,SAAS,GAAG,EACvB,QAAQ;AAAA;AAQX,eAAsB,uBAAuB,CAC5C,IACA,OACA,WACoB;AAAA,EACpB,MAAM,OAAO,MAAM,GACjB,WAAW,WAAW,EACtB,OAAO,aAAa,EACpB,MAAM,aAAa,KAAK,IAAI,EAC5B,MAAM,gBAAgB,MAAM,SAAS,EACrC,MACA,QAAgB,KAAI,IAAI,iBAAiB,cAAc,aAAa,KAAI,IAAI,oBAAoB,cAAc,SAC/G,EACC,QAAQ;AAAA,EACV,OAAO,KAAK,IAAI,CAAC,MAAM,EAAE,WAAW;AAAA;AASrC,eAAsB,yBAAyB,CAC9C,IACA,iBACgB;AAAA,EAChB,MAAM,GACJ,YAAY,WAAW,EACvB,IAAI,EAAE,WAAW,MAAM,CAAC,EACxB,MAAM,gBAAgB,MAAM,eAAe,EAC3C,QAAQ;AAAA;",
9
+ "debugId": "E2278282AC73418664756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -153,7 +153,6 @@ interface SubgraphsTable {
153
153
  handler_code: string | null;
154
154
  source_code: string | null;
155
155
  project_id: string | null;
156
- visibility: Generated<string>;
157
156
  /** Paid (wallet-ghost) deploys expire unless renewed or claimed; NULL = no expiry. */
158
157
  expires_at: Date | null;
159
158
  /** (event type, contract) probe pairs persisted at deploy for weight classification. */
@@ -783,6 +782,7 @@ interface Database {
783
782
  coverage_segments: CoverageSegmentsTable;
784
783
  stage_failures: StageFailuresTable;
785
784
  archive_fetches: ArchiveFetchesTable;
785
+ usage_ledger: UsageLedgerTable;
786
786
  waitlists: WaitlistsTable;
787
787
  waitlist_signups: WaitlistSignupsTable;
788
788
  }
@@ -827,6 +827,27 @@ interface ArchiveFetchesTable {
827
827
  via_allowance: Generated<boolean>;
828
828
  charged_at: Generated<Date>;
829
829
  }
830
+ /**
831
+ * One metered ledger for every billable unit (archive partitions, hosted
832
+ * Index/Streams rows, and future hosted-stack meters). Append-only, written
833
+ * only by `meter()`. `idempotency_key` is UNIQUE so a retried submission
834
+ * no-ops instead of double-charging. `debited` is false when the balance
835
+ * (or a spend cap) refused the charge — the row still exists so the gap is
836
+ * visible, never silently dropped. `usd_micros` is negative for a Stripe
837
+ * top-up (`unit: "topup"`).
838
+ */
839
+ interface UsageLedgerTable {
840
+ id: Generated<string>;
841
+ account_id: string;
842
+ unit: string;
843
+ quantity: string | number | bigint;
844
+ usd_micros: string | number | bigint;
845
+ debited: Generated<boolean>;
846
+ source: string;
847
+ idempotency_key: string;
848
+ occurred_at: Generated<Date>;
849
+ recorded_at: Generated<Date>;
850
+ }
830
851
  type WebhookStatus = "active" | "paused" | "error";
831
852
  /** Polymorphic webhook mode: `subgraph` reacts to processed table rows;
832
853
  * `chain` reacts to raw chain events matched directly off the Index/Streams
@@ -889,6 +910,10 @@ interface WebhookOutboxTable {
889
910
  failed_at: Date | null;
890
911
  locked_by: string | null;
891
912
  locked_until: Date | null;
913
+ /** Set when a reorg marks an in-flight row `dead` instead of retrying it
914
+ * into an orphaned fork. Null otherwise — delivery failures track their
915
+ * history on `webhooks.last_error`, not per-row. */
916
+ last_error: string | null;
892
917
  created_at: Generated<Date>;
893
918
  }
894
919
  interface WebhookDeliveriesTable {
@@ -966,4 +991,4 @@ declare function getInstance(db: Kysely<Database>): Promise<InstanceRow | null>;
966
991
  declare function ensureInstance(db: Kysely<Database>, input: {
967
992
  network: InstanceNetwork
968
993
  }): Promise<InstanceRow>;
969
- export { parseInstanceNetwork, instanceNetworkFromEnv, getInstance, ensureInstance, InvalidInstanceNetworkError, InstanceRow, InstanceNetworkMismatchError, InstanceNetwork, INSTANCE_NETWORKS };
994
+ export { INSTANCE_NETWORKS, InstanceNetwork, InstanceNetworkMismatchError, InstanceRow, InvalidInstanceNetworkError, ensureInstance, getInstance, instanceNetworkFromEnv, parseInstanceNetwork };