@secondlayer/shared 6.21.0 → 6.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -948,6 +948,113 @@ declare const SOURCE_READ_COLUMNS: {
948
948
  readonly events: readonly ["block_height", "data", "event_index", "tx_id", "type"]
949
949
  readonly chain_reorgs: readonly ["detected_at"]
950
950
  };
951
+ /**
952
+ * Per-migration DB-plane gating for the source/target split.
953
+ *
954
+ * Under the split, SOURCE (chain DB) holds only chain+decoded tables — the
955
+ * control-plane tables were dropped to reclaim space — while TARGET (platform
956
+ * DB) holds the control plane. `migrate.ts` still runs EVERY migration on EVERY
957
+ * database (kysely integrity: the provider set must never be filtered per-DB, or
958
+ * kysely throws "previously executed migration is missing" because each DB's
959
+ * `kysely_migration` already records all of them). Instead, `migrate.ts` sets a
960
+ * role before each pass and a migration gates its DDL with the helpers below: a
961
+ * control migration's `up()` is a no-op on SOURCE but is still recorded applied,
962
+ * so there is no missing-migration error and no re-run.
963
+ *
964
+ * `'both'` is single-DB / collapsed-split mode (dev / OSS / CI): every helper
965
+ * runs, identical to pre-split behavior.
966
+ *
967
+ * Authoring a new migration under the split:
968
+ * async function up(db: Kysely<unknown>): Promise<void> {
969
+ * await onControlPlane(() => sql`ALTER TABLE accounts ADD COLUMN …`.execute(db));
970
+ * await onChainPlane(() => sql`ALTER TABLE blocks ADD COLUMN …`.execute(db));
971
+ * // schema-wide / mixed statements: leave unwrapped (run on both).
972
+ * }
973
+ */
974
+ type MigrationRole = "source" | "target" | "both";
975
+ declare function setMigrationRole(role: MigrationRole): void;
976
+ declare function getMigrationRole(): MigrationRole;
977
+ /** Run control-plane (TARGET) DDL only when this pass targets the control plane. */
978
+ declare function onControlPlane(fn: () => Promise<void>): Promise<void>;
979
+ /** Run chain/decoded (SOURCE) DDL only when this pass targets the chain plane. */
980
+ declare function onChainPlane(fn: () => Promise<void>): Promise<void>;
981
+ type DbPlane = "source" | "target" | "both";
982
+ /**
983
+ * Canonical table → DB-plane mapping for the source/target split.
984
+ *
985
+ * SOURCE = chain + decoded (the `postgres` instance); TARGET = control plane
986
+ * (the `postgres-platform` instance). `both` = present/used on both planes
987
+ * (`service_heartbeats`: the indexer writes its row on SOURCE, the
988
+ * subgraph-processor writes its row on TARGET).
989
+ *
990
+ * `satisfies Record<keyof Database, DbPlane>` makes adding a table to `Database`
991
+ * without classifying it here a COMPILE error. This is the single source of
992
+ * truth for the split — `docker/SCHEMA_SPLIT.md` and the cutover script's
993
+ * `CONTROL_TABLES` mirror the `target` set (guarded by `table-plane.test.ts`).
994
+ * Use it to decide which migration helper a table's DDL belongs in
995
+ * (`onControlPlane` for `target`, `onChainPlane` for `source`).
996
+ *
997
+ * Note: `kysely_migration` / `kysely_migration_lock` are kysely-managed (not in
998
+ * `Database`) and exist on both — they are intentionally not listed here.
999
+ */
1000
+ declare const TABLE_TO_DB: {
1001
+ blocks: string
1002
+ transactions: string
1003
+ events: string
1004
+ transactions_archive: string
1005
+ events_archive: string
1006
+ dead_letter_events: string
1007
+ mempool_transactions: string
1008
+ index_progress: string
1009
+ contracts: string
1010
+ chain_reorgs: string
1011
+ decoded_events: string
1012
+ l2_decoder_checkpoints: string
1013
+ pox4_calls: string
1014
+ pox4_cycles_daily: string
1015
+ pox4_signers_daily: string
1016
+ burn_block_rewards: string
1017
+ burn_block_reward_slots: string
1018
+ sbtc_events: string
1019
+ sbtc_token_events: string
1020
+ sbtc_supply_snapshots: string
1021
+ bns_name_events: string
1022
+ bns_namespace_events: string
1023
+ bns_marketplace_events: string
1024
+ bns_names: string
1025
+ bns_namespaces: string
1026
+ accounts: string
1027
+ api_keys: string
1028
+ sessions: string
1029
+ magic_links: string
1030
+ usage_daily: string
1031
+ usage_snapshots: string
1032
+ account_insights: string
1033
+ account_agent_runs: string
1034
+ account_spend_caps: string
1035
+ processed_stripe_events: string
1036
+ tenants: string
1037
+ tenant_usage_monthly: string
1038
+ tenant_compute_addons: string
1039
+ provisioning_audit_log: string
1040
+ projects: string
1041
+ team_members: string
1042
+ team_invitations: string
1043
+ chat_sessions: string
1044
+ chat_messages: string
1045
+ subscriptions: string
1046
+ subscription_outbox: string
1047
+ subscription_deliveries: string
1048
+ trigger_evaluator_state: string
1049
+ subgraphs: string
1050
+ subgraph_operations: string
1051
+ subgraph_health_snapshots: string
1052
+ subgraph_gaps: string
1053
+ subgraph_usage_daily: string
1054
+ subgraph_processing_stats: string
1055
+ subgraph_table_snapshots: string
1056
+ service_heartbeats: string
1057
+ };
951
1058
  interface DbSplitStatus {
952
1059
  /** "split" when source/target resolve to different DBs, else "single". */
953
1060
  mode: "split" | "single";
@@ -1015,4 +1122,4 @@ declare function getRawClient(role?: "source" | "target"): ReturnType<typeof pos
1015
1122
  declare function getRawClientFor(url: string): ReturnType<typeof postgres>;
1016
1123
  /** Close all DB connection pools. Call in CLI commands to allow process exit. */
1017
1124
  declare function closeDb(): Promise<void>;
1018
- export { sql, parseJsonb, jsonb, getTargetDb, getSourceDb, getRawClientFor, getRawClient, getDbSplitStatus, getDb, closeDb, assertDbSplit, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateTransaction, UpdateTenantUsageMonthly, UpdateTenantComputeAddon, UpdateTenant, UpdateSubscriptionOutbox, UpdateSubscription, UpdateSubgraphOperation, UpdateSubgraph, UpdateProject, UpdateIndexProgress, UpdateEvent, UpdateContract, UpdateChatSession, UpdateBlock, UpdateApiKey, UpdateAccountSpendCap, TriggerEvaluatorStateTable, TriggerEvaluatorState, TransactionsTable, TransactionsArchiveTable, Transaction, TenantsTable, TenantUsageMonthlyTable, TenantUsageMonthly, TenantStatus, TenantComputeAddonsTable, TenantComputeAddon, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubscriptionsTable, SubscriptionStatus, SubscriptionRuntime, SubscriptionOutboxTable, SubscriptionOutbox, SubscriptionKind, SubscriptionFormat, SubscriptionDelivery, SubscriptionDeliveriesTable, Subscription, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphProcessingStatsTable, SubgraphOperationsTable, SubgraphOperationStatus, SubgraphOperationKind, SubgraphOperation, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGap, Subgraph, SessionsTable, Session, ServiceHeartbeatsTable, SbtcTokenEventsTable, SbtcTokenEventType, SbtcSupplySnapshotsTable, SbtcEventsTable, SbtcEventTopic, SOURCE_READ_COLUMNS, ProvisioningAuditStatus, ProvisioningAuditLogTable, ProvisioningAuditLog, ProvisioningAuditEvent, ProjectsTable, Project, ProcessedStripeEventsTable, Pox4SignersDailyTable, Pox4FunctionName, Pox4CyclesDailyTable, Pox4CallsTable, OutboxStatus, NumericAsText, MempoolTransactionsTable, MempoolTransaction, MagicLinksTable, MagicLink, L2DecoderCheckpointsTable, InsertTransaction, InsertTenantUsageMonthly, InsertTenantComputeAddon, InsertTenant, InsertTeamMember, InsertTeamInvitation, InsertSubscriptionOutbox, InsertSubscriptionDelivery, InsertSubscription, InsertSubgraphUsageDaily, InsertSubgraphOperation, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProvisioningAuditLog, InsertProject, InsertMempoolTransaction, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertContract, InsertChatSession, InsertChatMessage, InsertBlock, InsertApiKey, InsertAccountSpendCap, InsertAccountInsight, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, EventsTable, EventsArchiveTable, Event, DecodedEventsTable, DeadLetterEventsTable, DbSplitStatus, DbReadRow, Database, ContractsTable, Contract, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, ChainReorgsTable, BurnBlockRewardsTable, BurnBlockRewardSlotsTable, BnsNamespacesTable, BnsNamespaceEventsTable, BnsNamespaceEventStatus, BnsNamesTable, BnsNameEventsTable, BnsNameEventTopic, BnsMarketplaceEventsTable, BnsMarketplaceAction, BlocksTable, Block, ApiKeysTable, ApiKey, AccountsTable, AccountSpendCapsTable, AccountSpendCap, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
1125
+ export { sql, setMigrationRole, parseJsonb, onControlPlane, onChainPlane, jsonb, getTargetDb, getSourceDb, getRawClientFor, getRawClient, getMigrationRole, getDbSplitStatus, getDb, closeDb, assertDbSplit, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateTransaction, UpdateTenantUsageMonthly, UpdateTenantComputeAddon, UpdateTenant, UpdateSubscriptionOutbox, UpdateSubscription, UpdateSubgraphOperation, UpdateSubgraph, UpdateProject, UpdateIndexProgress, UpdateEvent, UpdateContract, UpdateChatSession, UpdateBlock, UpdateApiKey, UpdateAccountSpendCap, TriggerEvaluatorStateTable, TriggerEvaluatorState, TransactionsTable, TransactionsArchiveTable, Transaction, TenantsTable, TenantUsageMonthlyTable, TenantUsageMonthly, TenantStatus, TenantComputeAddonsTable, TenantComputeAddon, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, TABLE_TO_DB, SubscriptionsTable, SubscriptionStatus, SubscriptionRuntime, SubscriptionOutboxTable, SubscriptionOutbox, SubscriptionKind, SubscriptionFormat, SubscriptionDelivery, SubscriptionDeliveriesTable, Subscription, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphProcessingStatsTable, SubgraphOperationsTable, SubgraphOperationStatus, SubgraphOperationKind, SubgraphOperation, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGap, Subgraph, SessionsTable, Session, ServiceHeartbeatsTable, SbtcTokenEventsTable, SbtcTokenEventType, SbtcSupplySnapshotsTable, SbtcEventsTable, SbtcEventTopic, SOURCE_READ_COLUMNS, ProvisioningAuditStatus, ProvisioningAuditLogTable, ProvisioningAuditLog, ProvisioningAuditEvent, ProjectsTable, Project, ProcessedStripeEventsTable, Pox4SignersDailyTable, Pox4FunctionName, Pox4CyclesDailyTable, Pox4CallsTable, OutboxStatus, NumericAsText, MigrationRole, MempoolTransactionsTable, MempoolTransaction, MagicLinksTable, MagicLink, L2DecoderCheckpointsTable, InsertTransaction, InsertTenantUsageMonthly, InsertTenantComputeAddon, InsertTenant, InsertTeamMember, InsertTeamInvitation, InsertSubscriptionOutbox, InsertSubscriptionDelivery, InsertSubscription, InsertSubgraphUsageDaily, InsertSubgraphOperation, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProvisioningAuditLog, InsertProject, InsertMempoolTransaction, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertContract, InsertChatSession, InsertChatMessage, InsertBlock, InsertApiKey, InsertAccountSpendCap, InsertAccountInsight, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, EventsTable, EventsArchiveTable, Event, DecodedEventsTable, DeadLetterEventsTable, DbSplitStatus, DbReadRow, DbPlane, Database, ContractsTable, Contract, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, ChainReorgsTable, BurnBlockRewardsTable, BurnBlockRewardSlotsTable, BnsNamespacesTable, BnsNamespaceEventsTable, BnsNamespaceEventStatus, BnsNamesTable, BnsNameEventsTable, BnsNameEventTopic, BnsMarketplaceEventsTable, BnsMarketplaceAction, BlocksTable, Block, ApiKeysTable, ApiKey, AccountsTable, AccountSpendCapsTable, AccountSpendCap, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
@@ -378,6 +378,81 @@ var SOURCE_READ_COLUMNS = {
378
378
  events: ["block_height", "data", "event_index", "tx_id", "type"],
379
379
  chain_reorgs: ["detected_at"]
380
380
  };
381
+ // src/db/migration-role.ts
382
+ var currentRole = "both";
383
+ function setMigrationRole(role) {
384
+ currentRole = role;
385
+ }
386
+ function getMigrationRole() {
387
+ return currentRole;
388
+ }
389
+ async function onControlPlane(fn) {
390
+ if (currentRole === "target" || currentRole === "both")
391
+ await fn();
392
+ }
393
+ async function onChainPlane(fn) {
394
+ if (currentRole === "source" || currentRole === "both")
395
+ await fn();
396
+ }
397
+ // src/db/table-plane.ts
398
+ var TABLE_TO_DB = {
399
+ blocks: "source",
400
+ transactions: "source",
401
+ events: "source",
402
+ transactions_archive: "source",
403
+ events_archive: "source",
404
+ dead_letter_events: "source",
405
+ mempool_transactions: "source",
406
+ index_progress: "source",
407
+ contracts: "source",
408
+ chain_reorgs: "source",
409
+ decoded_events: "source",
410
+ l2_decoder_checkpoints: "source",
411
+ pox4_calls: "source",
412
+ pox4_cycles_daily: "source",
413
+ pox4_signers_daily: "source",
414
+ burn_block_rewards: "source",
415
+ burn_block_reward_slots: "source",
416
+ sbtc_events: "source",
417
+ sbtc_token_events: "source",
418
+ sbtc_supply_snapshots: "source",
419
+ bns_name_events: "source",
420
+ bns_namespace_events: "source",
421
+ bns_marketplace_events: "source",
422
+ bns_names: "source",
423
+ bns_namespaces: "source",
424
+ accounts: "target",
425
+ api_keys: "target",
426
+ sessions: "target",
427
+ magic_links: "target",
428
+ usage_daily: "target",
429
+ usage_snapshots: "target",
430
+ account_insights: "target",
431
+ account_agent_runs: "target",
432
+ account_spend_caps: "target",
433
+ processed_stripe_events: "target",
434
+ tenants: "target",
435
+ tenant_usage_monthly: "target",
436
+ tenant_compute_addons: "target",
437
+ provisioning_audit_log: "target",
438
+ projects: "target",
439
+ team_members: "target",
440
+ team_invitations: "target",
441
+ chat_sessions: "target",
442
+ chat_messages: "target",
443
+ subscriptions: "target",
444
+ subscription_outbox: "target",
445
+ subscription_deliveries: "target",
446
+ trigger_evaluator_state: "target",
447
+ subgraphs: "target",
448
+ subgraph_operations: "target",
449
+ subgraph_health_snapshots: "target",
450
+ subgraph_gaps: "target",
451
+ subgraph_usage_daily: "target",
452
+ subgraph_processing_stats: "target",
453
+ subgraph_table_snapshots: "target",
454
+ service_heartbeats: "both"
455
+ };
381
456
 
382
457
  // src/db/index.ts
383
458
  var DEFAULT_URL = "postgres://postgres:postgres@localhost:5432/secondlayer_dev";
@@ -537,18 +612,23 @@ async function closeDb() {
537
612
  }
538
613
  export {
539
614
  sql2 as sql,
615
+ setMigrationRole,
540
616
  parseJsonb,
617
+ onControlPlane,
618
+ onChainPlane,
541
619
  jsonb,
542
620
  getTargetDb,
543
621
  getSourceDb,
544
622
  getRawClientFor,
545
623
  getRawClient,
624
+ getMigrationRole,
546
625
  getDbSplitStatus,
547
626
  getDb,
548
627
  closeDb,
549
628
  assertDbSplit,
629
+ TABLE_TO_DB,
550
630
  SOURCE_READ_COLUMNS
551
631
  };
552
632
 
553
- //# debugId=8E009B207AB7E55D64756E2164756E21
633
+ //# debugId=9BD00555AB68090864756E2164756E21
554
634
  //# sourceMappingURL=index.js.map
@@ -1,14 +1,16 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/env.ts", "../src/logger.ts", "../src/db/jsonb.ts", "../src/db/index.ts", "../src/db/source-read-columns.ts"],
3
+ "sources": ["../src/env.ts", "../src/logger.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"],
4
4
  "sourcesContent": [
5
5
  "import { z } from \"zod/v4\";\n\n// Parse comma-separated networks\nconst networksSchema = z.string().transform((val) => {\n\tconst networks = val\n\t\t.split(\",\")\n\t\t.map((n) => n.trim())\n\t\t.filter(Boolean);\n\tconst valid = [\"mainnet\", \"testnet\"];\n\tfor (const n of networks) {\n\t\tif (!valid.includes(n)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid network: ${n}. Must be one of: ${valid.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn networks as (\"mainnet\" | \"testnet\")[];\n});\n\ninterface EnvSchemaOutput {\n\tDATABASE_URL?: string;\n\t/**\n\t * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.\n\t * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.\n\t */\n\tSOURCE_DATABASE_URL?: string;\n\t/**\n\t * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.\n\t * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.\n\t */\n\tTARGET_DATABASE_URL?: string;\n\tNETWORK?: \"mainnet\" | \"testnet\";\n\tNETWORKS?: (\"mainnet\" | \"testnet\")[];\n\tLOG_LEVEL: \"debug\" | \"info\" | \"warn\" | \"error\";\n\tNODE_ENV: \"development\" | \"production\" | \"test\";\n}\n\n// Cast needed: z.preprocess / z.default create different _input vs _output types\n// that z.ZodType<T> can't represent without explicit input type param\nconst envSchema: z.ZodType<EnvSchemaOutput> = z.object({\n\tDATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tSOURCE_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tTARGET_DATABASE_URL: z.preprocess(\n\t\t(val) => (typeof val === \"string\" && val.length === 0 ? undefined : val),\n\t\tz.string().url().optional(),\n\t),\n\tNETWORK: z.enum([\"mainnet\", \"testnet\"]).optional(),\n\tNETWORKS: networksSchema.optional(),\n\tLOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n\tNODE_ENV: z\n\t\t.enum([\"development\", \"production\", \"test\"])\n\t\t.default(\"development\"),\n}) as unknown as z.ZodType<EnvSchemaOutput>;\n\nexport type Env = EnvSchemaOutput & {\n\tenabledNetworks: (\"mainnet\" | \"testnet\")[];\n};\n\nlet cachedEnv: Env | null = null;\n\nexport function getEnv(): Env {\n\tif (cachedEnv) {\n\t\treturn cachedEnv;\n\t}\n\n\tconst result = envSchema.safeParse(process.env);\n\n\tif (!result.success) {\n\t\tconsole.error(\"❌ Invalid environment configuration:\");\n\t\tconsole.error(z.treeifyError(result.error));\n\t\tthrow new Error(\"Invalid environment configuration\");\n\t}\n\n\t// Compute enabled networks from NETWORKS or NETWORK\n\tlet enabledNetworks: (\"mainnet\" | \"testnet\")[];\n\tif (result.data.NETWORKS && result.data.NETWORKS.length > 0) {\n\t\tenabledNetworks = result.data.NETWORKS;\n\t} else if (result.data.NETWORK) {\n\t\tenabledNetworks = [result.data.NETWORK];\n\t} else {\n\t\tenabledNetworks = [\"mainnet\"]; // Default\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\n/**\n * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the\n * public surface, so the decoder that fills `pox4_calls` runs unless explicitly\n * opted out with `POX4_DECODER_ENABLED=false` (mirrors the sBTC decoder policy).\n */\nexport function isPox4DecoderEnabled(): boolean {\n\treturn process.env.POX4_DECODER_ENABLED !== \"false\";\n}\n\n// Export for testing\nexport { envSchema };\n",
6
6
  "import { getEnv } from \"./env.ts\";\n\ntype LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n\tdebug: 0,\n\tinfo: 1,\n\twarn: 2,\n\terror: 3,\n};\n\nclass Logger {\n\tprivate _level?: LogLevel;\n\tprivate _isProduction?: boolean;\n\tprivate _initialized = false;\n\n\tprivate init() {\n\t\tif (this._initialized) return;\n\t\tthis._initialized = true;\n\t\ttry {\n\t\t\tconst env = getEnv();\n\t\t\tthis._level = env.LOG_LEVEL;\n\t\t\tthis._isProduction = env.NODE_ENV === \"production\";\n\t\t} catch {\n\t\t\t// Fallback when env is unavailable (e.g. tests without DATABASE_URL)\n\t\t\tthis._level = \"info\";\n\t\t\tthis._isProduction = false;\n\t\t}\n\t}\n\n\tprivate get level(): LogLevel {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._level!;\n\t}\n\n\tprivate get isProduction(): boolean {\n\t\tthis.init();\n\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\treturn this._isProduction!;\n\t}\n\n\tprivate shouldLog(level: LogLevel): boolean {\n\t\treturn LOG_LEVELS[level] >= LOG_LEVELS[this.level];\n\t}\n\n\tprivate formatMessage(\n\t\tlevel: LogLevel,\n\t\tmessage: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\tmeta?: Record<string, any>,\n\t) {\n\t\tconst timestamp = new Date().toISOString();\n\n\t\tif (this.isProduction) {\n\t\t\t// JSON output for production\n\t\t\treturn JSON.stringify({\n\t\t\t\ttimestamp,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\t...meta,\n\t\t\t});\n\t\t}\n\n\t\t// Human-readable output for development\n\t\tconst metaStr = meta ? ` ${JSON.stringify(meta)}` : \"\";\n\t\treturn `[${timestamp}] ${level.toUpperCase()}: ${message}${metaStr}`;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tdebug(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.debug(this.formatMessage(\"debug\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\tinfo(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.info(this.formatMessage(\"info\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\twarn(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.warn(this.formatMessage(\"warn\", message, meta));\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\terror(message: string, meta?: Record<string, any>): void {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"error\", message, meta));\n\t\t}\n\t}\n}\n\n// Export singleton instance\nexport const logger: Logger = new Logger();\n",
7
7
  "import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n",
8
- "import { Kysely } from \"kysely\";\nimport { PostgresJSDialect } from \"kysely-postgres-js\";\nimport postgres from \"postgres\";\nimport { logger } from \"../logger.ts\";\nimport type { Database } from \"./types.ts\";\n\nexport type { Database } from \"./types.ts\";\n\nconst DEFAULT_URL =\n\t\"postgres://postgres:postgres@localhost:5432/secondlayer_dev\";\n\ninterface PoolEntry {\n\tdb: Kysely<Database>;\n\trawClient: ReturnType<typeof postgres>;\n\t/** Last access (ms) — drives LRU eviction of BYO pools. */\n\tlastUsed: number;\n\t/** Monotonic counter as a tiebreaker; Date.now() can repeat under load. */\n\tseq: number;\n}\n\n/**\n * Cache of Kysely + raw postgres.js pools keyed by resolved URL.\n * Two getters resolving to the same URL share one entry (single pool) —\n * this is the single-DB backward-compat contract: when only `DATABASE_URL`\n * is set, `getSourceDb() === getTargetDb()` (zero regression vs. pre-dual-DB).\n *\n * The BYO data plane adds one pool per user-owned DB. To stop N user DBs from\n * exhausting connections/FDs, the map is bounded (`DATABASE_MAX_POOLS`, default\n * 25) with LRU eviction — the hot source/target pools are never evicted.\n */\nconst pools = new Map<string, PoolEntry>();\nlet poolSeq = 0;\n\nfunction maxPools(): number {\n\treturn Number.parseInt(process.env.DATABASE_MAX_POOLS ?? \"25\", 10);\n}\n\n/** Close the least-recently-used non-(source/target) pool when over the cap. */\nfunction evictIfNeeded(): void {\n\tif (pools.size <= maxPools()) return;\n\tconst protectedUrls = new Set([resolveSourceUrl(), resolveTargetUrl()]);\n\tlet lruUrl: string | undefined;\n\tlet lruEntry: PoolEntry | undefined;\n\tfor (const [url, entry] of pools) {\n\t\tif (protectedUrls.has(url)) continue;\n\t\tif (\n\t\t\t!lruEntry ||\n\t\t\tentry.lastUsed < lruEntry.lastUsed ||\n\t\t\t(entry.lastUsed === lruEntry.lastUsed && entry.seq < lruEntry.seq)\n\t\t) {\n\t\t\tlruUrl = url;\n\t\t\tlruEntry = entry;\n\t\t}\n\t}\n\tif (!lruUrl || !lruEntry) return;\n\tpools.delete(lruUrl);\n\tconst evicted = lruEntry;\n\t// Close in the background — never block pool creation on teardown.\n\tvoid evicted.db\n\t\t.destroy()\n\t\t.catch(() => {})\n\t\t.then(() => evicted.rawClient.end({ timeout: 5 }))\n\t\t.catch(() => {});\n}\n\nfunction resolveSourceUrl(): string {\n\treturn (\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction resolveTargetUrl(): string {\n\treturn (\n\t\tprocess.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\n/** Host[:port]/dbname for a connection URL — credentials stripped. */\nfunction describeDbUrl(url: string): string {\n\ttry {\n\t\tconst u = new URL(url);\n\t\treturn `${u.hostname}${u.port ? `:${u.port}` : \"\"}${u.pathname}`;\n\t} catch {\n\t\treturn \"invalid-url\";\n\t}\n}\n\nexport interface DbSplitStatus {\n\t/** \"split\" when source/target resolve to different DBs, else \"single\". */\n\tmode: \"split\" | \"single\";\n\t/** True when the chain/control split is live (distinct DBs). */\n\tactive: boolean;\n\t/** SOURCE host[:port]/dbname (no credentials). */\n\tsourceDb: string;\n\t/** TARGET host[:port]/dbname (no credentials). */\n\ttargetDb: string;\n}\n\n/**\n * Resolved source/target DB identity for status/health surfaces. Lets operators\n * see whether the chain/control split is live or dormant (collapsed to one DB)\n * without shelling in. Credentials are never exposed — host/db only.\n *\n * `active` is a STRING-IDENTITY check on the two URLs: it can't catch two\n * distinct URLs that alias the same physical instance (e.g. `postgres` vs\n * `127.0.0.1`, or a swapped/wrong host). Treat `active: true` as \"configured\n * for split\", not a proof of physical isolation.\n */\nexport function getDbSplitStatus(): DbSplitStatus {\n\tconst source = resolveSourceUrl();\n\tconst target = resolveTargetUrl();\n\tconst active = source !== target;\n\treturn {\n\t\tmode: active ? \"split\" : \"single\",\n\t\tactive,\n\t\tsourceDb: describeDbUrl(source),\n\t\ttargetDb: describeDbUrl(target),\n\t};\n}\n\n/**\n * Boot guard for the chain/control DB split. Surfaces three misconfigurations\n * loudly (fail-soft — logs, never throws, so a misconfig can't brick startup):\n *\n * 1. Silent wrong-DB: a split is requested (one of SOURCE_/TARGET_ set) but\n * `DATABASE_URL` is absent (the split-prod default) and the OTHER var is\n * unset, so it falls through to the built-in dev `DEFAULT_URL` — about to\n * read/write a real-but-wrong database. This is the failure mode the\n * remove-DATABASE_URL decision creates; catch it.\n * 2. Collapsed split: both vars set but resolve to the same DB (typo, or a\n * stray `DATABASE_URL` masking the intent).\n * 3. Dormant split (prod only): neither var set, so all services share one\n * Postgres failure domain. Not an error, but no longer silent.\n */\nexport function assertDbSplit(): void {\n\tconst isProd = process.env.NODE_ENV === \"production\";\n\tconst wantsSplit = !!(\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.TARGET_DATABASE_URL\n\t);\n\tconst databaseUrlSet = !!process.env.DATABASE_URL;\n\tconst source = resolveSourceUrl();\n\tconst target = resolveTargetUrl();\n\n\tif (\n\t\twantsSplit &&\n\t\t!databaseUrlSet &&\n\t\t(source === DEFAULT_URL || target === DEFAULT_URL)\n\t) {\n\t\tconst which =\n\t\t\tsource === DEFAULT_URL ? \"SOURCE_DATABASE_URL\" : \"TARGET_DATABASE_URL\";\n\t\tconst msg = `${which} unset and DATABASE_URL absent — resolving to built-in DEFAULT_URL; refusing to silently use the wrong database`;\n\t\tif (isProd) console.error(`❌ ${msg}`);\n\t\telse console.warn(`⚠️ ${msg}`);\n\t\treturn;\n\t}\n\n\tif (!wantsSplit) {\n\t\tif (isProd) {\n\t\t\tconsole.warn(\n\t\t\t\t\"⚠️ DB split dormant — all services share one Postgres failure domain (SOURCE_/TARGET_DATABASE_URL unset)\",\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (source === target) {\n\t\tconst msg =\n\t\t\t\"DB split requested but SOURCE_DATABASE_URL === TARGET_DATABASE_URL (check for a typo or a stray DATABASE_URL fallback)\";\n\t\tif (isProd) console.error(`❌ ${msg}`);\n\t\telse console.warn(`⚠️ ${msg}`);\n\t}\n}\n\nfunction getOrCreatePool(url: string): PoolEntry {\n\tconst existing = pools.get(url);\n\tif (existing) {\n\t\texisting.lastUsed = Date.now();\n\t\texisting.seq = poolSeq++;\n\t\treturn existing;\n\t}\n\n\t// \"Local\" = we skip TLS. Any Docker service alias (single-label hostname\n\t// with no dots) is on an internal network and won't serve TLS.\n\tconst host = (() => {\n\t\ttry {\n\t\t\treturn new URL(url).hostname;\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t})();\n\tconst isLocal =\n\t\thost === \"localhost\" || host === \"127.0.0.1\" || !host.includes(\".\");\n\tconst poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? \"20\", 10);\n\t// Close idle connections so a fleet of BYO pools doesn't pin connections it\n\t// no longer needs (0 = never; postgres.js default).\n\tconst idleTimeout = Number.parseInt(\n\t\tprocess.env.DATABASE_IDLE_TIMEOUT ?? \"300\",\n\t\t10,\n\t);\n\tconst rawClient = postgres(url, {\n\t\tmax: poolMax,\n\t\tidle_timeout: idleTimeout,\n\t\tssl: isLocal\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\trejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== \"0\",\n\t\t\t\t},\n\t});\n\tconst db = new Kysely<Database>({\n\t\tdialect: new PostgresJSDialect({ postgres: rawClient }),\n\t\t// Diagnostic hook: surface the failing SQL whenever postgres rejects\n\t\t// with code 42P10 (ON CONFLICT target doesn't match any unique\n\t\t// constraint). Temporary — remove once we've caught the culprit\n\t\t// query in prod logs and fixed the schema drift.\n\t\tlog: (event) => {\n\t\t\tif (event.level !== \"error\") return;\n\t\t\tconst err = event.error as {\n\t\t\t\tcode?: string;\n\t\t\t\tmessage?: string;\n\t\t\t} | null;\n\t\t\tif (err?.code !== \"42P10\") return;\n\t\t\tlogger.warn(\"db.on_conflict_constraint_missing\", {\n\t\t\t\tcode: err.code,\n\t\t\t\tmessage: err.message,\n\t\t\t\tsql: event.query.sql,\n\t\t\t\tparams: event.query.parameters,\n\t\t\t});\n\t\t},\n\t});\n\tconst entry: PoolEntry = {\n\t\tdb,\n\t\trawClient,\n\t\tlastUsed: Date.now(),\n\t\tseq: poolSeq++,\n\t};\n\tpools.set(url, entry);\n\tevictIfNeeded();\n\treturn entry;\n}\n\n/**\n * Kysely instance for the SOURCE DB (block/tx/event reads from the shared\n * indexer). Resolution: `SOURCE_DATABASE_URL || DATABASE_URL`.\n */\nexport function getSourceDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveSourceUrl()).db;\n}\n\n/**\n * Kysely instance for the TARGET DB (subgraph schemas, subgraphs table,\n * account-scoped data — tenant-side writes). Resolution:\n * `TARGET_DATABASE_URL || DATABASE_URL`.\n */\nexport function getTargetDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveTargetUrl()).db;\n}\n\n/**\n * Backward-compat alias for `getTargetDb()`. Accepts an optional\n * `connectionString` override used by seed/test helpers — when supplied,\n * bypasses env resolution and uses the provided URL directly (still cached).\n */\nexport function getDb(connectionString?: string): Kysely<Database> {\n\tif (connectionString) return getOrCreatePool(connectionString).db;\n\treturn getTargetDb();\n}\n\n/**\n * Raw postgres.js client for dynamic schema DDL (CREATE SCHEMA, DROP, etc.).\n * Defaults to the target role (tenant schemas live in the target DB).\n */\nexport function getRawClient(\n\trole: \"source\" | \"target\" = \"target\",\n): ReturnType<typeof postgres> {\n\tconst url = role === \"source\" ? resolveSourceUrl() : resolveTargetUrl();\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/**\n * Raw postgres.js client for an arbitrary connection string (cached by URL).\n * Used by the BYO data plane to run DDL / serving queries against a\n * user-owned Postgres. Distinct from {@link getRawClient}, which only knows the\n * source/target roles resolved from env.\n */\nexport function getRawClientFor(url: string): ReturnType<typeof postgres> {\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/** Close all DB connection pools. Call in CLI commands to allow process exit. */\nexport async function closeDb(): Promise<void> {\n\tfor (const entry of pools.values()) {\n\t\tawait entry.db.destroy();\n\t\tawait entry.rawClient.end();\n\t}\n\tpools.clear();\n}\n\nimport { sql } from \"kysely\";\nexport { sql };\nexport * from \"./types.ts\";\nexport type { DbReadRow, NumericAsText } from \"./read-row.ts\";\nexport { SOURCE_READ_COLUMNS } from \"./source-read-columns.ts\";\nexport { jsonb, parseJsonb } from \"./jsonb.ts\";\n",
9
- "import type { Database } from \"./types.ts\";\n\n// The physical source-table columns the public read API (packages/api) actually\n// reads via getSourceDb(). This is the read contract between the indexer (which\n// owns the write schema) and the API (which reads it raw). A column rename or\n// removal on the producer side that isn't reflected here is caught by the\n// snapshot drift test; the `satisfies` clause guarantees every entry is a real\n// table + column today.\n//\n// Computed/aliased read expressions are intentionally excluded — they are not\n// part of the producer contract: `cursor`/`block_time` where derived in SQL\n// rather than stored, window ranks (stream_event_index), and JSONB extractions\n// from `events.data`. Generated bookkeeping columns (created_at/updated_at) are\n// excluded unless a read path selects them.\nexport const SOURCE_READ_COLUMNS = {\n\tblocks: [\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"hash\",\n\t\t\"height\",\n\t\t\"parent_hash\",\n\t\t\"timestamp\",\n\t],\n\tdecoded_events: [\n\t\t\"amount\",\n\t\t\"asset_identifier\",\n\t\t\"block_height\",\n\t\t\"canonical\",\n\t\t\"contract_id\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"event_type\",\n\t\t\"memo\",\n\t\t\"payload\",\n\t\t\"recipient\",\n\t\t\"sender\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t\t\"value\",\n\t],\n\ttransactions: [\n\t\t\"block_height\",\n\t\t\"contract_id\",\n\t\t\"function_args\",\n\t\t\"function_name\",\n\t\t\"raw_result\",\n\t\t\"raw_tx\",\n\t\t\"sender\",\n\t\t\"status\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t\t\"type\",\n\t],\n\tmempool_transactions: [\n\t\t\"contract_id\",\n\t\t\"function_args\",\n\t\t\"function_name\",\n\t\t\"raw_tx\",\n\t\t\"received_at\",\n\t\t\"sender\",\n\t\t\"seq\",\n\t\t\"tx_id\",\n\t\t\"type\",\n\t],\n\tpox4_calls: [\n\t\t\"aggregated_amount_ustx\",\n\t\t\"aggregated_signer_index\",\n\t\t\"amount_ustx\",\n\t\t\"auth_allowed\",\n\t\t\"auth_id\",\n\t\t\"auth_period\",\n\t\t\"auth_topic\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"burn_block_height\",\n\t\t\"caller\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"delegate_to\",\n\t\t\"end_cycle\",\n\t\t\"function_name\",\n\t\t\"lock_period\",\n\t\t\"max_amount\",\n\t\t\"pox_addr_btc\",\n\t\t\"pox_addr_hashbytes\",\n\t\t\"pox_addr_version\",\n\t\t\"result_ok\",\n\t\t\"reward_cycle\",\n\t\t\"signer_key\",\n\t\t\"signer_signature\",\n\t\t\"source_cursor\",\n\t\t\"stacker\",\n\t\t\"start_cycle\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tsbtc_events: [\n\t\t\"amount\",\n\t\t\"bitcoin_txid\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"burn_hash\",\n\t\t\"burn_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"fee\",\n\t\t\"governance_contract_type\",\n\t\t\"governance_new_contract\",\n\t\t\"max_fee\",\n\t\t\"output_index\",\n\t\t\"recipient_btc_hashbytes\",\n\t\t\"recipient_btc_version\",\n\t\t\"request_id\",\n\t\t\"sender\",\n\t\t\"signer_address\",\n\t\t\"signer_aggregate_pubkey\",\n\t\t\"signer_bitmap\",\n\t\t\"signer_keys_count\",\n\t\t\"signer_threshold\",\n\t\t\"sweep_txid\",\n\t\t\"topic\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tsbtc_token_events: [\n\t\t\"amount\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"event_type\",\n\t\t\"memo\",\n\t\t\"recipient\",\n\t\t\"sender\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_name_events: [\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"bns_id\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"fqn\",\n\t\t\"hashed_salted_fqn_preorder\",\n\t\t\"imported_at\",\n\t\t\"name\",\n\t\t\"namespace\",\n\t\t\"owner\",\n\t\t\"preordered_by\",\n\t\t\"registered_at\",\n\t\t\"renewal_height\",\n\t\t\"stx_burn\",\n\t\t\"topic\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_namespace_events: [\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"launched_at\",\n\t\t\"lifetime\",\n\t\t\"manager\",\n\t\t\"manager_frozen\",\n\t\t\"manager_transfers_disabled\",\n\t\t\"namespace\",\n\t\t\"price_frozen\",\n\t\t\"price_function\",\n\t\t\"revealed_at\",\n\t\t\"status\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_marketplace_events: [\n\t\t\"action\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"bns_id\",\n\t\t\"canonical\",\n\t\t\"commission\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"price_ustx\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_names: [\n\t\t\"bns_id\",\n\t\t\"fqn\",\n\t\t\"last_event_at\",\n\t\t\"last_event_cursor\",\n\t\t\"name\",\n\t\t\"namespace\",\n\t\t\"owner\",\n\t\t\"registered_at\",\n\t\t\"renewal_height\",\n\t],\n\tbns_namespaces: [\n\t\t\"last_event_at\",\n\t\t\"last_event_cursor\",\n\t\t\"launched_at\",\n\t\t\"lifetime\",\n\t\t\"manager\",\n\t\t\"manager_frozen\",\n\t\t\"name_count\",\n\t\t\"namespace\",\n\t\t\"price_frozen\",\n\t],\n\tburn_block_rewards: [\n\t\t\"amount_sats\",\n\t\t\"burn_amount\",\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"recipient_btc\",\n\t\t\"reward_index\",\n\t],\n\tburn_block_reward_slots: [\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"holder_btc\",\n\t\t\"slot_index\",\n\t],\n\tevents: [\"block_height\", \"data\", \"event_index\", \"tx_id\", \"type\"],\n\tchain_reorgs: [\"detected_at\"],\n} as const satisfies {\n\treadonly [T in keyof Database]?: readonly (keyof Database[T])[];\n};\n"
8
+ "import { Kysely } from \"kysely\";\nimport { PostgresJSDialect } from \"kysely-postgres-js\";\nimport postgres from \"postgres\";\nimport { logger } from \"../logger.ts\";\nimport type { Database } from \"./types.ts\";\n\nexport type { Database } from \"./types.ts\";\n\nconst DEFAULT_URL =\n\t\"postgres://postgres:postgres@localhost:5432/secondlayer_dev\";\n\ninterface PoolEntry {\n\tdb: Kysely<Database>;\n\trawClient: ReturnType<typeof postgres>;\n\t/** Last access (ms) — drives LRU eviction of BYO pools. */\n\tlastUsed: number;\n\t/** Monotonic counter as a tiebreaker; Date.now() can repeat under load. */\n\tseq: number;\n}\n\n/**\n * Cache of Kysely + raw postgres.js pools keyed by resolved URL.\n * Two getters resolving to the same URL share one entry (single pool) —\n * this is the single-DB backward-compat contract: when only `DATABASE_URL`\n * is set, `getSourceDb() === getTargetDb()` (zero regression vs. pre-dual-DB).\n *\n * The BYO data plane adds one pool per user-owned DB. To stop N user DBs from\n * exhausting connections/FDs, the map is bounded (`DATABASE_MAX_POOLS`, default\n * 25) with LRU eviction — the hot source/target pools are never evicted.\n */\nconst pools = new Map<string, PoolEntry>();\nlet poolSeq = 0;\n\nfunction maxPools(): number {\n\treturn Number.parseInt(process.env.DATABASE_MAX_POOLS ?? \"25\", 10);\n}\n\n/** Close the least-recently-used non-(source/target) pool when over the cap. */\nfunction evictIfNeeded(): void {\n\tif (pools.size <= maxPools()) return;\n\tconst protectedUrls = new Set([resolveSourceUrl(), resolveTargetUrl()]);\n\tlet lruUrl: string | undefined;\n\tlet lruEntry: PoolEntry | undefined;\n\tfor (const [url, entry] of pools) {\n\t\tif (protectedUrls.has(url)) continue;\n\t\tif (\n\t\t\t!lruEntry ||\n\t\t\tentry.lastUsed < lruEntry.lastUsed ||\n\t\t\t(entry.lastUsed === lruEntry.lastUsed && entry.seq < lruEntry.seq)\n\t\t) {\n\t\t\tlruUrl = url;\n\t\t\tlruEntry = entry;\n\t\t}\n\t}\n\tif (!lruUrl || !lruEntry) return;\n\tpools.delete(lruUrl);\n\tconst evicted = lruEntry;\n\t// Close in the background — never block pool creation on teardown.\n\tvoid evicted.db\n\t\t.destroy()\n\t\t.catch(() => {})\n\t\t.then(() => evicted.rawClient.end({ timeout: 5 }))\n\t\t.catch(() => {});\n}\n\nfunction resolveSourceUrl(): string {\n\treturn (\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction resolveTargetUrl(): string {\n\treturn (\n\t\tprocess.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\n/** Host[:port]/dbname for a connection URL — credentials stripped. */\nfunction describeDbUrl(url: string): string {\n\ttry {\n\t\tconst u = new URL(url);\n\t\treturn `${u.hostname}${u.port ? `:${u.port}` : \"\"}${u.pathname}`;\n\t} catch {\n\t\treturn \"invalid-url\";\n\t}\n}\n\nexport interface DbSplitStatus {\n\t/** \"split\" when source/target resolve to different DBs, else \"single\". */\n\tmode: \"split\" | \"single\";\n\t/** True when the chain/control split is live (distinct DBs). */\n\tactive: boolean;\n\t/** SOURCE host[:port]/dbname (no credentials). */\n\tsourceDb: string;\n\t/** TARGET host[:port]/dbname (no credentials). */\n\ttargetDb: string;\n}\n\n/**\n * Resolved source/target DB identity for status/health surfaces. Lets operators\n * see whether the chain/control split is live or dormant (collapsed to one DB)\n * without shelling in. Credentials are never exposed — host/db only.\n *\n * `active` is a STRING-IDENTITY check on the two URLs: it can't catch two\n * distinct URLs that alias the same physical instance (e.g. `postgres` vs\n * `127.0.0.1`, or a swapped/wrong host). Treat `active: true` as \"configured\n * for split\", not a proof of physical isolation.\n */\nexport function getDbSplitStatus(): DbSplitStatus {\n\tconst source = resolveSourceUrl();\n\tconst target = resolveTargetUrl();\n\tconst active = source !== target;\n\treturn {\n\t\tmode: active ? \"split\" : \"single\",\n\t\tactive,\n\t\tsourceDb: describeDbUrl(source),\n\t\ttargetDb: describeDbUrl(target),\n\t};\n}\n\n/**\n * Boot guard for the chain/control DB split. Surfaces three misconfigurations\n * loudly (fail-soft — logs, never throws, so a misconfig can't brick startup):\n *\n * 1. Silent wrong-DB: a split is requested (one of SOURCE_/TARGET_ set) but\n * `DATABASE_URL` is absent (the split-prod default) and the OTHER var is\n * unset, so it falls through to the built-in dev `DEFAULT_URL` — about to\n * read/write a real-but-wrong database. This is the failure mode the\n * remove-DATABASE_URL decision creates; catch it.\n * 2. Collapsed split: both vars set but resolve to the same DB (typo, or a\n * stray `DATABASE_URL` masking the intent).\n * 3. Dormant split (prod only): neither var set, so all services share one\n * Postgres failure domain. Not an error, but no longer silent.\n */\nexport function assertDbSplit(): void {\n\tconst isProd = process.env.NODE_ENV === \"production\";\n\tconst wantsSplit = !!(\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.TARGET_DATABASE_URL\n\t);\n\tconst databaseUrlSet = !!process.env.DATABASE_URL;\n\tconst source = resolveSourceUrl();\n\tconst target = resolveTargetUrl();\n\n\tif (\n\t\twantsSplit &&\n\t\t!databaseUrlSet &&\n\t\t(source === DEFAULT_URL || target === DEFAULT_URL)\n\t) {\n\t\tconst which =\n\t\t\tsource === DEFAULT_URL ? \"SOURCE_DATABASE_URL\" : \"TARGET_DATABASE_URL\";\n\t\tconst msg = `${which} unset and DATABASE_URL absent — resolving to built-in DEFAULT_URL; refusing to silently use the wrong database`;\n\t\tif (isProd) console.error(`❌ ${msg}`);\n\t\telse console.warn(`⚠️ ${msg}`);\n\t\treturn;\n\t}\n\n\tif (!wantsSplit) {\n\t\tif (isProd) {\n\t\t\tconsole.warn(\n\t\t\t\t\"⚠️ DB split dormant — all services share one Postgres failure domain (SOURCE_/TARGET_DATABASE_URL unset)\",\n\t\t\t);\n\t\t}\n\t\treturn;\n\t}\n\n\tif (source === target) {\n\t\tconst msg =\n\t\t\t\"DB split requested but SOURCE_DATABASE_URL === TARGET_DATABASE_URL (check for a typo or a stray DATABASE_URL fallback)\";\n\t\tif (isProd) console.error(`❌ ${msg}`);\n\t\telse console.warn(`⚠️ ${msg}`);\n\t}\n}\n\nfunction getOrCreatePool(url: string): PoolEntry {\n\tconst existing = pools.get(url);\n\tif (existing) {\n\t\texisting.lastUsed = Date.now();\n\t\texisting.seq = poolSeq++;\n\t\treturn existing;\n\t}\n\n\t// \"Local\" = we skip TLS. Any Docker service alias (single-label hostname\n\t// with no dots) is on an internal network and won't serve TLS.\n\tconst host = (() => {\n\t\ttry {\n\t\t\treturn new URL(url).hostname;\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t})();\n\tconst isLocal =\n\t\thost === \"localhost\" || host === \"127.0.0.1\" || !host.includes(\".\");\n\tconst poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? \"20\", 10);\n\t// Close idle connections so a fleet of BYO pools doesn't pin connections it\n\t// no longer needs (0 = never; postgres.js default).\n\tconst idleTimeout = Number.parseInt(\n\t\tprocess.env.DATABASE_IDLE_TIMEOUT ?? \"300\",\n\t\t10,\n\t);\n\tconst rawClient = postgres(url, {\n\t\tmax: poolMax,\n\t\tidle_timeout: idleTimeout,\n\t\tssl: isLocal\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\trejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== \"0\",\n\t\t\t\t},\n\t});\n\tconst db = new Kysely<Database>({\n\t\tdialect: new PostgresJSDialect({ postgres: rawClient }),\n\t\t// Diagnostic hook: surface the failing SQL whenever postgres rejects\n\t\t// with code 42P10 (ON CONFLICT target doesn't match any unique\n\t\t// constraint). Temporary — remove once we've caught the culprit\n\t\t// query in prod logs and fixed the schema drift.\n\t\tlog: (event) => {\n\t\t\tif (event.level !== \"error\") return;\n\t\t\tconst err = event.error as {\n\t\t\t\tcode?: string;\n\t\t\t\tmessage?: string;\n\t\t\t} | null;\n\t\t\tif (err?.code !== \"42P10\") return;\n\t\t\tlogger.warn(\"db.on_conflict_constraint_missing\", {\n\t\t\t\tcode: err.code,\n\t\t\t\tmessage: err.message,\n\t\t\t\tsql: event.query.sql,\n\t\t\t\tparams: event.query.parameters,\n\t\t\t});\n\t\t},\n\t});\n\tconst entry: PoolEntry = {\n\t\tdb,\n\t\trawClient,\n\t\tlastUsed: Date.now(),\n\t\tseq: poolSeq++,\n\t};\n\tpools.set(url, entry);\n\tevictIfNeeded();\n\treturn entry;\n}\n\n/**\n * Kysely instance for the SOURCE DB (block/tx/event reads from the shared\n * indexer). Resolution: `SOURCE_DATABASE_URL || DATABASE_URL`.\n */\nexport function getSourceDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveSourceUrl()).db;\n}\n\n/**\n * Kysely instance for the TARGET DB (subgraph schemas, subgraphs table,\n * account-scoped data — tenant-side writes). Resolution:\n * `TARGET_DATABASE_URL || DATABASE_URL`.\n */\nexport function getTargetDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveTargetUrl()).db;\n}\n\n/**\n * Backward-compat alias for `getTargetDb()`. Accepts an optional\n * `connectionString` override used by seed/test helpers — when supplied,\n * bypasses env resolution and uses the provided URL directly (still cached).\n */\nexport function getDb(connectionString?: string): Kysely<Database> {\n\tif (connectionString) return getOrCreatePool(connectionString).db;\n\treturn getTargetDb();\n}\n\n/**\n * Raw postgres.js client for dynamic schema DDL (CREATE SCHEMA, DROP, etc.).\n * Defaults to the target role (tenant schemas live in the target DB).\n */\nexport function getRawClient(\n\trole: \"source\" | \"target\" = \"target\",\n): ReturnType<typeof postgres> {\n\tconst url = role === \"source\" ? resolveSourceUrl() : resolveTargetUrl();\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/**\n * Raw postgres.js client for an arbitrary connection string (cached by URL).\n * Used by the BYO data plane to run DDL / serving queries against a\n * user-owned Postgres. Distinct from {@link getRawClient}, which only knows the\n * source/target roles resolved from env.\n */\nexport function getRawClientFor(url: string): ReturnType<typeof postgres> {\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/** Close all DB connection pools. Call in CLI commands to allow process exit. */\nexport async function closeDb(): Promise<void> {\n\tfor (const entry of pools.values()) {\n\t\tawait entry.db.destroy();\n\t\tawait entry.rawClient.end();\n\t}\n\tpools.clear();\n}\n\nimport { sql } from \"kysely\";\nexport { sql };\nexport * from \"./types.ts\";\nexport type { DbReadRow, NumericAsText } from \"./read-row.ts\";\nexport { SOURCE_READ_COLUMNS } from \"./source-read-columns.ts\";\nexport { jsonb, parseJsonb } from \"./jsonb.ts\";\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",
9
+ "import type { Database } from \"./types.ts\";\n\n// The physical source-table columns the public read API (packages/api) actually\n// reads via getSourceDb(). This is the read contract between the indexer (which\n// owns the write schema) and the API (which reads it raw). A column rename or\n// removal on the producer side that isn't reflected here is caught by the\n// snapshot drift test; the `satisfies` clause guarantees every entry is a real\n// table + column today.\n//\n// Computed/aliased read expressions are intentionally excluded — they are not\n// part of the producer contract: `cursor`/`block_time` where derived in SQL\n// rather than stored, window ranks (stream_event_index), and JSONB extractions\n// from `events.data`. Generated bookkeeping columns (created_at/updated_at) are\n// excluded unless a read path selects them.\nexport const SOURCE_READ_COLUMNS = {\n\tblocks: [\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"hash\",\n\t\t\"height\",\n\t\t\"parent_hash\",\n\t\t\"timestamp\",\n\t],\n\tdecoded_events: [\n\t\t\"amount\",\n\t\t\"asset_identifier\",\n\t\t\"block_height\",\n\t\t\"canonical\",\n\t\t\"contract_id\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"event_type\",\n\t\t\"memo\",\n\t\t\"payload\",\n\t\t\"recipient\",\n\t\t\"sender\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t\t\"value\",\n\t],\n\ttransactions: [\n\t\t\"block_height\",\n\t\t\"contract_id\",\n\t\t\"function_args\",\n\t\t\"function_name\",\n\t\t\"raw_result\",\n\t\t\"raw_tx\",\n\t\t\"sender\",\n\t\t\"status\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t\t\"type\",\n\t],\n\tmempool_transactions: [\n\t\t\"contract_id\",\n\t\t\"function_args\",\n\t\t\"function_name\",\n\t\t\"raw_tx\",\n\t\t\"received_at\",\n\t\t\"sender\",\n\t\t\"seq\",\n\t\t\"tx_id\",\n\t\t\"type\",\n\t],\n\tpox4_calls: [\n\t\t\"aggregated_amount_ustx\",\n\t\t\"aggregated_signer_index\",\n\t\t\"amount_ustx\",\n\t\t\"auth_allowed\",\n\t\t\"auth_id\",\n\t\t\"auth_period\",\n\t\t\"auth_topic\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"burn_block_height\",\n\t\t\"caller\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"delegate_to\",\n\t\t\"end_cycle\",\n\t\t\"function_name\",\n\t\t\"lock_period\",\n\t\t\"max_amount\",\n\t\t\"pox_addr_btc\",\n\t\t\"pox_addr_hashbytes\",\n\t\t\"pox_addr_version\",\n\t\t\"result_ok\",\n\t\t\"reward_cycle\",\n\t\t\"signer_key\",\n\t\t\"signer_signature\",\n\t\t\"source_cursor\",\n\t\t\"stacker\",\n\t\t\"start_cycle\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tsbtc_events: [\n\t\t\"amount\",\n\t\t\"bitcoin_txid\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"burn_hash\",\n\t\t\"burn_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"fee\",\n\t\t\"governance_contract_type\",\n\t\t\"governance_new_contract\",\n\t\t\"max_fee\",\n\t\t\"output_index\",\n\t\t\"recipient_btc_hashbytes\",\n\t\t\"recipient_btc_version\",\n\t\t\"request_id\",\n\t\t\"sender\",\n\t\t\"signer_address\",\n\t\t\"signer_aggregate_pubkey\",\n\t\t\"signer_bitmap\",\n\t\t\"signer_keys_count\",\n\t\t\"signer_threshold\",\n\t\t\"sweep_txid\",\n\t\t\"topic\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tsbtc_token_events: [\n\t\t\"amount\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"event_type\",\n\t\t\"memo\",\n\t\t\"recipient\",\n\t\t\"sender\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_name_events: [\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"bns_id\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"fqn\",\n\t\t\"hashed_salted_fqn_preorder\",\n\t\t\"imported_at\",\n\t\t\"name\",\n\t\t\"namespace\",\n\t\t\"owner\",\n\t\t\"preordered_by\",\n\t\t\"registered_at\",\n\t\t\"renewal_height\",\n\t\t\"stx_burn\",\n\t\t\"topic\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_namespace_events: [\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"launched_at\",\n\t\t\"lifetime\",\n\t\t\"manager\",\n\t\t\"manager_frozen\",\n\t\t\"manager_transfers_disabled\",\n\t\t\"namespace\",\n\t\t\"price_frozen\",\n\t\t\"price_function\",\n\t\t\"revealed_at\",\n\t\t\"status\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_marketplace_events: [\n\t\t\"action\",\n\t\t\"block_height\",\n\t\t\"block_time\",\n\t\t\"bns_id\",\n\t\t\"canonical\",\n\t\t\"commission\",\n\t\t\"cursor\",\n\t\t\"event_index\",\n\t\t\"price_ustx\",\n\t\t\"tx_id\",\n\t\t\"tx_index\",\n\t],\n\tbns_names: [\n\t\t\"bns_id\",\n\t\t\"fqn\",\n\t\t\"last_event_at\",\n\t\t\"last_event_cursor\",\n\t\t\"name\",\n\t\t\"namespace\",\n\t\t\"owner\",\n\t\t\"registered_at\",\n\t\t\"renewal_height\",\n\t],\n\tbns_namespaces: [\n\t\t\"last_event_at\",\n\t\t\"last_event_cursor\",\n\t\t\"launched_at\",\n\t\t\"lifetime\",\n\t\t\"manager\",\n\t\t\"manager_frozen\",\n\t\t\"name_count\",\n\t\t\"namespace\",\n\t\t\"price_frozen\",\n\t],\n\tburn_block_rewards: [\n\t\t\"amount_sats\",\n\t\t\"burn_amount\",\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"recipient_btc\",\n\t\t\"reward_index\",\n\t],\n\tburn_block_reward_slots: [\n\t\t\"burn_block_hash\",\n\t\t\"burn_block_height\",\n\t\t\"canonical\",\n\t\t\"cursor\",\n\t\t\"holder_btc\",\n\t\t\"slot_index\",\n\t],\n\tevents: [\"block_height\", \"data\", \"event_index\", \"tx_id\", \"type\"],\n\tchain_reorgs: [\"detected_at\"],\n} as const satisfies {\n\treadonly [T in keyof Database]?: readonly (keyof Database[T])[];\n};\n",
10
+ "/**\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",
11
+ "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\ttransactions_archive: \"source\",\n\tevents_archive: \"source\",\n\tdead_letter_events: \"source\",\n\tmempool_transactions: \"source\",\n\tindex_progress: \"source\",\n\tcontracts: \"source\",\n\tchain_reorgs: \"source\",\n\t// ── SOURCE: decoded (L2) ──\n\tdecoded_events: \"source\",\n\tl2_decoder_checkpoints: \"source\",\n\tpox4_calls: \"source\",\n\tpox4_cycles_daily: \"source\",\n\tpox4_signers_daily: \"source\",\n\tburn_block_rewards: \"source\",\n\tburn_block_reward_slots: \"source\",\n\tsbtc_events: \"source\",\n\tsbtc_token_events: \"source\",\n\tsbtc_supply_snapshots: \"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\taccounts: \"target\",\n\tapi_keys: \"target\",\n\tsessions: \"target\",\n\tmagic_links: \"target\",\n\tusage_daily: \"target\",\n\tusage_snapshots: \"target\",\n\taccount_insights: \"target\",\n\taccount_agent_runs: \"target\",\n\taccount_spend_caps: \"target\",\n\tprocessed_stripe_events: \"target\",\n\ttenants: \"target\",\n\ttenant_usage_monthly: \"target\",\n\ttenant_compute_addons: \"target\",\n\tprovisioning_audit_log: \"target\",\n\tprojects: \"target\",\n\tteam_members: \"target\",\n\tteam_invitations: \"target\",\n\tchat_sessions: \"target\",\n\tchat_messages: \"target\",\n\t// ── TARGET: subscriptions ──\n\tsubscriptions: \"target\",\n\tsubscription_outbox: \"target\",\n\tsubscription_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_usage_daily: \"target\",\n\tsubgraph_processing_stats: \"target\",\n\tsubgraph_table_snapshots: \"target\",\n\t// ── BOTH ──\n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AAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,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,E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ACA;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,I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,MAAM,UAAU,IAAI;AAAA,EAC3B;AAAA,EACA,MAAM,MAAM;AAAA;",
14
+ "debugId": "9BD00555AB68090864756E2164756E21",
13
15
  "names": []
14
16
  }
@@ -378,6 +378,81 @@ var SOURCE_READ_COLUMNS = {
378
378
  events: ["block_height", "data", "event_index", "tx_id", "type"],
379
379
  chain_reorgs: ["detected_at"]
380
380
  };
381
+ // src/db/migration-role.ts
382
+ var currentRole = "both";
383
+ function setMigrationRole(role) {
384
+ currentRole = role;
385
+ }
386
+ function getMigrationRole() {
387
+ return currentRole;
388
+ }
389
+ async function onControlPlane(fn) {
390
+ if (currentRole === "target" || currentRole === "both")
391
+ await fn();
392
+ }
393
+ async function onChainPlane(fn) {
394
+ if (currentRole === "source" || currentRole === "both")
395
+ await fn();
396
+ }
397
+ // src/db/table-plane.ts
398
+ var TABLE_TO_DB = {
399
+ blocks: "source",
400
+ transactions: "source",
401
+ events: "source",
402
+ transactions_archive: "source",
403
+ events_archive: "source",
404
+ dead_letter_events: "source",
405
+ mempool_transactions: "source",
406
+ index_progress: "source",
407
+ contracts: "source",
408
+ chain_reorgs: "source",
409
+ decoded_events: "source",
410
+ l2_decoder_checkpoints: "source",
411
+ pox4_calls: "source",
412
+ pox4_cycles_daily: "source",
413
+ pox4_signers_daily: "source",
414
+ burn_block_rewards: "source",
415
+ burn_block_reward_slots: "source",
416
+ sbtc_events: "source",
417
+ sbtc_token_events: "source",
418
+ sbtc_supply_snapshots: "source",
419
+ bns_name_events: "source",
420
+ bns_namespace_events: "source",
421
+ bns_marketplace_events: "source",
422
+ bns_names: "source",
423
+ bns_namespaces: "source",
424
+ accounts: "target",
425
+ api_keys: "target",
426
+ sessions: "target",
427
+ magic_links: "target",
428
+ usage_daily: "target",
429
+ usage_snapshots: "target",
430
+ account_insights: "target",
431
+ account_agent_runs: "target",
432
+ account_spend_caps: "target",
433
+ processed_stripe_events: "target",
434
+ tenants: "target",
435
+ tenant_usage_monthly: "target",
436
+ tenant_compute_addons: "target",
437
+ provisioning_audit_log: "target",
438
+ projects: "target",
439
+ team_members: "target",
440
+ team_invitations: "target",
441
+ chat_sessions: "target",
442
+ chat_messages: "target",
443
+ subscriptions: "target",
444
+ subscription_outbox: "target",
445
+ subscription_deliveries: "target",
446
+ trigger_evaluator_state: "target",
447
+ subgraphs: "target",
448
+ subgraph_operations: "target",
449
+ subgraph_health_snapshots: "target",
450
+ subgraph_gaps: "target",
451
+ subgraph_usage_daily: "target",
452
+ subgraph_processing_stats: "target",
453
+ subgraph_table_snapshots: "target",
454
+ service_heartbeats: "both"
455
+ };
381
456
 
382
457
  // src/db/index.ts
383
458
  var DEFAULT_URL = "postgres://postgres:postgres@localhost:5432/secondlayer_dev";
@@ -641,5 +716,5 @@ export {
641
716
  encodeChainReorgCursor
642
717
  };
643
718
 
644
- //# debugId=CC17506FFD38A9EE64756E2164756E21
719
+ //# debugId=BEE1DBFF45D8B87B64756E2164756E21
645
720
  //# sourceMappingURL=chain-reorgs.js.map