@secondlayer/shared 15.3.3 → 15.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/src/archive/range-digest.d.ts +7 -0
  2. package/dist/src/archive/semantic-digest-builder.d.ts +7 -0
  3. package/dist/src/classify/index.js +16 -2
  4. package/dist/src/classify/index.js.map +3 -3
  5. package/dist/src/coverage/index.d.ts +15 -1
  6. package/dist/src/coverage/index.js +57 -2
  7. package/dist/src/coverage/index.js.map +4 -4
  8. package/dist/src/crypto/secondlayer-webhook.js +16 -2
  9. package/dist/src/crypto/secondlayer-webhook.js.map +3 -3
  10. package/dist/src/crypto/secrets.d.ts +8 -2
  11. package/dist/src/crypto/secrets.js +21 -7
  12. package/dist/src/crypto/secrets.js.map +3 -3
  13. package/dist/src/db/index.d.ts +15 -1
  14. package/dist/src/db/index.js +29 -7
  15. package/dist/src/db/index.js.map +5 -5
  16. package/dist/src/db/queries/chain-reorgs.d.ts +7 -0
  17. package/dist/src/db/queries/chain-reorgs.js +27 -7
  18. package/dist/src/db/queries/chain-reorgs.js.map +5 -5
  19. package/dist/src/db/queries/contracts.d.ts +21 -1
  20. package/dist/src/db/queries/contracts.js +23 -1
  21. package/dist/src/db/queries/contracts.js.map +4 -4
  22. package/dist/src/db/queries/instance.d.ts +33 -5
  23. package/dist/src/db/queries/instance.js +224 -14
  24. package/dist/src/db/queries/instance.js.map +6 -5
  25. package/dist/src/db/queries/integrity.d.ts +84 -1
  26. package/dist/src/db/queries/integrity.js +430 -15
  27. package/dist/src/db/queries/integrity.js.map +8 -6
  28. package/dist/src/db/queries/subgraph-gaps.d.ts +18 -6
  29. package/dist/src/db/queries/subgraph-gaps.js +81 -14
  30. package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
  31. package/dist/src/db/queries/subgraph-operations.d.ts +10 -1
  32. package/dist/src/db/queries/subgraph-operations.js +9 -5
  33. package/dist/src/db/queries/subgraph-operations.js.map +3 -3
  34. package/dist/src/db/queries/subgraphs.d.ts +11 -4
  35. package/dist/src/db/queries/subgraphs.js +13 -6
  36. package/dist/src/db/queries/subgraphs.js.map +4 -4
  37. package/dist/src/db/queries/sync-scope.d.ts +7 -0
  38. package/dist/src/db/queries/webhook-replays.d.ts +7 -0
  39. package/dist/src/db/queries/webhook-replays.js +20 -7
  40. package/dist/src/db/queries/webhook-replays.js.map +3 -3
  41. package/dist/src/db/queries/webhooks.d.ts +7 -0
  42. package/dist/src/db/queries/webhooks.js +20 -7
  43. package/dist/src/db/queries/webhooks.js.map +3 -3
  44. package/dist/src/db/schema.d.ts +7 -0
  45. package/dist/src/db/schema.js.map +2 -2
  46. package/dist/src/email/index.js +16 -2
  47. package/dist/src/email/index.js.map +3 -3
  48. package/dist/src/env.d.ts +8 -1
  49. package/dist/src/env.js +18 -3
  50. package/dist/src/env.js.map +3 -3
  51. package/dist/src/index.d.ts +59 -1
  52. package/dist/src/index.js +71 -8
  53. package/dist/src/index.js.map +8 -8
  54. package/dist/src/insights/index.d.ts +7 -0
  55. package/dist/src/insights/index.js +16 -2
  56. package/dist/src/insights/index.js.map +3 -3
  57. package/dist/src/leader.js +915 -27
  58. package/dist/src/leader.js.map +13 -6
  59. package/dist/src/logger.js +16 -2
  60. package/dist/src/logger.js.map +3 -3
  61. package/dist/src/node/local-client.d.ts +7 -0
  62. package/dist/src/node/tx-summary.js +16 -2
  63. package/dist/src/node/tx-summary.js.map +3 -3
  64. package/dist/src/queue/listener.js +27 -7
  65. package/dist/src/queue/listener.js.map +5 -5
  66. package/dist/src/schemas/index.js +2 -2
  67. package/dist/src/schemas/index.js.map +3 -3
  68. package/dist/src/schemas/subgraphs.js +2 -2
  69. package/dist/src/schemas/subgraphs.js.map +3 -3
  70. package/dist/src/types.d.ts +3 -0
  71. package/migrations/0197_subgraph_last_block_hash.ts +67 -0
  72. package/migrations/0198_blocks_event_count.ts +24 -0
  73. package/migrations/0199_transactions_height_tx_index_uniq.ts +77 -0
  74. package/migrations/0200_subgraphs_schema_name_unique.ts +39 -0
  75. package/migrations/0201_subgraph_gaps_range_check.ts +47 -0
  76. package/migrations/0202_instances_secrets_key_canary.ts +36 -0
  77. package/package.json +2 -2
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/env.ts"],
4
4
  "sourcesContent": [
5
- "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"
5
+ "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\tconst named = stacksNetwork();\n\t\tenabledNetworks = named === \"testnet\" ? [\"testnet\"] : [\"mainnet\"];\n\t}\n\n\tcachedEnv = { ...result.data, enabledNetworks };\n\treturn cachedEnv;\n}\n\nlet warnedNetworkFallback = false;\n\n/**\n * The Stacks network this process serves, and the only place that decides it:\n * `STACKS_NETWORK`, else the deprecated `NETWORK` (warned once so a deployment\n * that only sets it is not silently re-keyed), else mainnet. Not validated;\n * `instanceNetworkFromEnv` is the strict form.\n */\nexport function stacksNetwork(env: NodeJS.ProcessEnv = process.env): string {\n\tif (env.STACKS_NETWORK) return env.STACKS_NETWORK;\n\tif (env.NETWORK) {\n\t\tif (!warnedNetworkFallback) {\n\t\t\twarnedNetworkFallback = true;\n\t\t\tconsole.warn(\"NETWORK is deprecated: set STACKS_NETWORK instead\");\n\t\t}\n\t\treturn env.NETWORK;\n\t}\n\treturn \"mainnet\";\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
6
  ],
7
- "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,O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AA,IAC/B,kBAAkB,CAAC,OAAO,KAAK,OAAO;AAAA,EACvC,EAAO;AAAA,IACN,MAAM,QAAQ,cAAc;AAAA,IAC5B,kBAAkB,UAAU,YAAY,CAAC,SAAS,IAAI,CAAC,SAAS;AAAA;AAAA,EAGjE,YAAY,KAAK,OAAO,MAAM,gBAAgB;AAAA,EAC9C,OAAO;AAAA;AAGR,IAAI,wBAAwB;AAQrB,SAAS,aAAa,CAAC,MAAyB,QAAQ,KAAa;AAAA,EAC3E,IAAI,IAAI;AAAA,IAAgB,OAAO,IAAI;AAAA,EACnC,IAAI,IAAI,SAAS;AAAA,IAChB,IAAI,CAAC,uBAAuB;AAAA,MAC3B,wBAAwB;AAAA,MACxB,QAAQ,KAAK,mDAAmD;AAAA,IACjE;AAAA,IACA,OAAO,IAAI;AAAA,EACZ;AAAA,EACA,OAAO;AAAA;AAeD,SAAS,eAAe,GAAY;AAAA,EAE1C,OAAO,QAAQ,IAAI,gBAAgB;AAAA;AAU7B,SAAS,oBAAoB,CAAC,MAAc,QAAQ,KAAc;AAAA,EACxE,OAAO,IAAI,yBAAyB;AAAA;AAS9B,SAAS,oBAAoB,CAAC,MAAc,QAAQ,KAAc;AAAA,EACxE,OAAO,IAAI,yBAAyB;AAAA;AAI9B,SAAS,oBAAoB,CAAC,MAAc,QAAQ,KAAc;AAAA,EACxE,OAAO,IAAI,yBAAyB;AAAA;AAI9B,SAAS,mBAAmB,CAAC,MAAc,QAAQ,KAAc;AAAA,EACvE,OAAO,IAAI,wBAAwB;AAAA;",
8
+ "debugId": "5CAECF233D46AD1C64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -293,6 +293,9 @@ interface BlocksTable {
293
293
  /** Tx count `persistBlock` was handed for this height. Null on rows
294
294
  * ingested before this column existed. */
295
295
  tx_count: ColumnType<number | null, number | null | undefined, number | null>;
296
+ /** Event count `persistBlock` was handed for this height. Null on rows
297
+ * ingested before this column existed. */
298
+ event_count: ColumnType<number | null, number | null | undefined, number | null>;
296
299
  created_at: Generated<Date>;
297
300
  }
298
301
  interface TransactionsTable {
@@ -426,6 +429,8 @@ interface SubgraphsTable {
426
429
  schema_name: string | null;
427
430
  start_block: Generated<number>;
428
431
  last_processed_block: Generated<number>;
432
+ /** Hash of the block at `last_processed_block`; NULL = unknown (see 0197). */
433
+ last_processed_block_hash: Generated<string | null>;
429
434
  reindex_from_block: number | null;
430
435
  reindex_to_block: number | null;
431
436
  last_error: string | null;
@@ -550,6 +555,8 @@ interface ApiKeysTable {
550
555
  interface InstancesTable {
551
556
  id: Generated<string>;
552
557
  network: string;
558
+ /** `SECONDLAYER_SECRETS_KEY` sealed under itself; see `ensureSecretsKeyCanary`. */
559
+ secrets_key_canary: ColumnType<string | null, string | null | undefined, string | null>;
553
560
  created_at: Generated<Date>;
554
561
  }
555
562
  interface AccountsTable {
@@ -1814,6 +1821,13 @@ type Env = EnvSchemaOutput & {
1814
1821
  enabledNetworks: ("mainnet" | "testnet")[]
1815
1822
  };
1816
1823
  declare function getEnv(): Env;
1824
+ /**
1825
+ * The Stacks network this process serves, and the only place that decides it:
1826
+ * `STACKS_NETWORK`, else the deprecated `NETWORK` (warned once so a deployment
1827
+ * that only sets it is not silently re-keyed), else mainnet. Not validated;
1828
+ * `instanceNetworkFromEnv` is the strict form.
1829
+ */
1830
+ declare function stacksNetwork(env?: NodeJS.ProcessEnv): string;
1817
1831
  type EnvMap = NodeJS.ProcessEnv;
1818
1832
  /**
1819
1833
  * PoX-4 stacking decoder is ON by default — `/v1/index/stacking` is part of the
@@ -1854,6 +1868,15 @@ type StreamsEventType = DecodedEventType;
1854
1868
  */
1855
1869
  declare const RUNE_EVENT_TYPES: readonly ["rune_etch", "rune_mint", "rune_transfer", "rune_burn"];
1856
1870
  type RuneEventType = (typeof RUNE_EVENT_TYPES)[number];
1871
+ /**
1872
+ * Version of the cursor ordinal contract. A Streams cursor is
1873
+ * `block_height:stream_event_index`, where the index is a dense ordinal over
1874
+ * every event of the block whose type is in `STREAMS_DB_EVENT_TYPES`. Adding,
1875
+ * removing or reordering a type shifts the ordinal of every later event in any
1876
+ * block that holds one, silently invalidating saved cursors. Change the list
1877
+ * only together with a bump of this number; `db-event-types.test.ts` pins both.
1878
+ */
1879
+ declare const STREAMS_CURSOR_VERSION = 1;
1857
1880
  declare const STREAMS_DB_EVENT_TYPES: readonly ["stx_transfer_event", "stx_mint_event", "stx_burn_event", "stx_lock_event", "ft_transfer_event", "ft_mint_event", "ft_burn_event", "nft_transfer_event", "nft_mint_event", "nft_burn_event", "smart_contract_event", "contract_event"];
1858
1881
  type StreamsDbEventType = (typeof STREAMS_DB_EVENT_TYPES)[number];
1859
1882
  declare const DB_TO_STREAMS_EVENT_TYPE: Record<StreamsDbEventType, StreamsEventType>;
@@ -2862,6 +2885,13 @@ declare function applicationDatabaseUrl(): string;
2862
2885
  declare function resolveSourceUrl(): string;
2863
2886
  /** Canonical target-DB URL — see {@link resolveSourceUrl}. */
2864
2887
  declare function resolveTargetUrl(): string;
2888
+ /** The source URL the environment actually names, or undefined: unlike
2889
+ * {@link resolveSourceUrl} it never falls back to the dev default, so a tool
2890
+ * that writes (migrate) can refuse instead of touching a database nobody
2891
+ * configured. */
2892
+ declare function configuredSourceUrl(): string | undefined;
2893
+ /** See {@link configuredSourceUrl}. */
2894
+ declare function configuredTargetUrl(): string | undefined;
2865
2895
  /** Host[:port]/dbname for a connection URL — credentials stripped. Exported
2866
2896
  * so anything logging which database it connected to (a LISTEN channel's
2867
2897
  * startup log, an ops health check) can describe it without ever printing a
@@ -3075,6 +3105,34 @@ type StreamsCursor = {
3075
3105
  declare const EMPTY_RANGE_EVENT_INDEX_SENTINEL = 2147483647;
3076
3106
  declare function encodeStreamsCursor(cursor: StreamsCursor): string;
3077
3107
  declare function decodeStreamsCursor(cursor: string): StreamsCursor;
3108
+ /**
3109
+ * Which feed a cursor belongs to. Classic Stacks Streams cursors stay bare
3110
+ * `<h>:<n>` (the 1.0 contract); the Bitcoin and vm feeds are prefixed so a
3111
+ * cursor from one feed can never silently resume another.
3112
+ */
3113
+ type StreamsCursorFeed = "stacks" | "btc" | "vm";
3114
+ /** Raised when a cursor carries another feed's tag. */
3115
+ declare class StreamsCursorFeedMismatchError extends Error {
3116
+ readonly expected: StreamsCursorFeed;
3117
+ readonly actual: StreamsCursorFeed;
3118
+ constructor(expected: StreamsCursorFeed, actual: StreamsCursorFeed);
3119
+ }
3120
+ /** Encode for a feed: `btc:`/`vm:` prefix, bare for classic Stacks. */
3121
+ declare function encodeFeedCursor(feed: StreamsCursorFeed, cursor: StreamsCursor): string;
3122
+ /**
3123
+ * Decode a cursor, reporting its tag. Untagged reports `feed: null` (the bare
3124
+ * form every feed has always accepted). Throws on malformed input.
3125
+ */
3126
+ declare function decodeTaggedStreamsCursor(raw: string): {
3127
+ feed: "btc" | "vm" | null
3128
+ cursor: StreamsCursor
3129
+ };
3130
+ /**
3131
+ * Decode a cursor for a specific feed. Untagged is accepted by every feed (the
3132
+ * legacy spelling); a tag for another feed throws
3133
+ * {@link StreamsCursorFeedMismatchError}.
3134
+ */
3135
+ declare function decodeFeedCursor(raw: string, feed: StreamsCursorFeed): StreamsCursor;
3078
3136
  declare function compareStreamsCursor(a: StreamsCursor, b: StreamsCursor): number;
3079
3137
  declare function isEmptyRangeCursor(cursor: StreamsCursor): boolean;
3080
3138
  /**
@@ -3969,4 +4027,4 @@ declare function publicKeyPemFromPrivate(privateKeyPem: string): string;
3969
4027
  declare function ed25519KeyId(publicKeyPem: string): string;
3970
4028
  declare function signEd25519(payload: string, privateKey: KeyObject): string;
3971
4029
  declare function verifyEd25519(payload: string, signatureBase64: string, publicKey: KeyObject): boolean;
3972
- export { ABI_STATUSES, AbiStatus, Account, AccountBalanceAlerts, AccountBalanceAlertsTable, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiFailedRequest, ApiFailedRequestsTable, ApiKey, ApiKeyExpiredError, ApiKeyRevokedError, ApiKeyStatus, ApiKeysTable, ApiRequestLogRow, ApiRequestLogTable, ArchiveFetch, ArchiveFetchesTable, AuthenticationError, AuthorizationError, Block, BlocksTable, BnsMarketplaceAction, BnsMarketplaceEventsTable, BnsNameEventTopic, BnsNameEventsTable, BnsNamesTable, BnsNamespaceEventStatus, BnsNamespaceEventsTable, BnsNamespacesTable, BurnBlockRewardSlotsTable, BurnBlockRewardsTable, CHAIN_TRIGGER_FIELDS, CHAIN_TRIGGER_TYPES, CODE_TO_STATUS, ChainApplyDeliveryOf, ChainApplyEnvelope, ChainApplyEnvelopeOf, ChainEventEnvelope, ChainFtBurnData, ChainFtMintData, ChainFtTransferData, ChainNftBurnData, ChainNftMintData, ChainNftTransferData, ChainPrintEventData, ChainReadCacheTable, ChainReorgOrphanedEntry, ChainReorgRollbackDelivery, ChainReorgRollbackEnvelope, ChainReorgsTable, ChainStxBurnData, ChainStxLockData, ChainStxMintData, ChainStxTransferData, ChainTestDelivery, ChainTxLevelEvent, ChainWebhookDelivery, ChainWebhookEnvelope, CliDeviceLogin, CliDeviceLoginStatus, CliDeviceLoginsTable, CliDeviceProduct, ContactRequest, ContactRequestsTable, Contract, ContractsTable, CoverageSegmentsTable, CreateWebhookRequest, CreateWebhookRequestSchema, CreateWebhookResponse, DB_TO_STREAMS_EVENT_TYPE, DECODED_EVENT_TYPES2 as DECODED_EVENT_TYPES, DEFAULT_BTC_CONFIRMATIONS, Database, DatabaseError, DbPlane, DbReadRow, DbSplitStatus, DeadLetterEventsTable, DeadReason, DeadRow, DecodedEventType2 as DecodedEventType, DecodedEventsTable, DecoderCheckpointsTable, DeliveryRow, DeploySubgraphRequest, DeploySubgraphRequestSchema, DeploySubgraphResponse, EMPTY_RANGE_EVENT_INDEX_SENTINEL, Env, ErrorCode, ErrorCodes, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, FeedbackTicket, FeedbackTicketsTable, ForbiddenError, GapReason, HealthHour, HealthSnapshotPoint, HostedStackStateTable, INSIGHT_SEVERITIES, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountBalanceAlerts, InsertAccountCredits, InsertAccountSpendCap, InsertApiFailedRequest, InsertApiKey, InsertApiRequestLogRow, InsertArchiveFetch, InsertBlock, InsertContactRequest, InsertContract, InsertEvent, InsertFeedbackTicket, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertStateWrite, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertUpdateSubscriber, InsertUsageLedgerRow, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, Insight, InsightEvidence, InsightEvidenceSchema, InsightListResponse, InsightListResponseSchema, InsightMutesTable, InsightResourceKind, InsightResourceKindSchema, InsightSchema, InsightSeverity, InsightSeveritySchema, InsightsTable, InstancesTable, KeyRotatedError, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NotFoundError, NumericAsText, OBSERVER_JOURNAL_STATUSES, OauthClient, OauthClientsTable, OauthCodesTable, OauthGrant, OauthGrantsTable, OauthRefreshRetiredTable, OauthRequestStatus, OauthRequestsTable, OauthTokenKind, OauthTokensTable, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, ParsedCreateWebhookRequest, ParsedReplayWebhookRequest, ParsedUpdateWebhookRequest, PaymentRequiredError, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5CycleSignersTable, Pox5CyclesTable, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, PushPrefs, PushPrefsTable, PushSentTable, PushSubscription, PushSubscriptionsTable, RUNE_EVENT_TYPES, RateLimitError, ReindexResponse, RepairMode, ReplayResult, ReplayWebhookRequest, ReplayWebhookRequestSchema, RetryState, RotateSecretResponse, RunStatus, RuneApplyDeliveryOf, RuneApplyEnvelope, RuneEventType, SEVERITY_ORDER, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, STREAMS_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_TO_DB_EVENT_TYPES, SUBGRAPH_STATES, SbtcDepositEvent, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SbtcWithdrawalEvent, SbtcWithdrawalSweptConfirmedEvent, SecondLayerError, SentinelAccount, SentinelAccountsTable, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StateWrite, StateWritesArchiveTable, StateWritesTable, StreamsCursor, StreamsDbEventType, StreamsEventType, Subgraph, SubgraphAgentSchema, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphErrorGroupsTable, SubgraphGap, SubgraphGapEntry, SubgraphGapRange, SubgraphGapsResponse, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphQueryParams, SubgraphSpecFormat, SubgraphSpecOptions, SubgraphStatus, SubgraphSummary, SubgraphSyncInfo, SubgraphSyncState, SubgraphVerification, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, TenantSuspendedError, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountBalanceAlerts, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSendsTable, UpdateSubgraph, UpdateSubgraphOperation, UpdateSubscriber, UpdateSubscribersTable, UpdateTransaction, UpdateUsageLedgerRow, UpdateVmEvent, UpdateWebhook, UpdateWebhookOutbox, UpdateWebhookRequest, UpdateWebhookRequestSchema, UsageLedgerRow, UsageLedgerTable, VM_EVENT_TYPES, VM_NODE_TO_STORED_TYPE2 as VM_NODE_TO_STORED_TYPE, VM_STORED_TO_NODE_TYPE, ValidationError, VersionConflictError, VmEvent, VmEventType, VmEventsArchiveTable, VmEventsTable, VmNodeEventType, WEBHOOK_FORMATS, WEBHOOK_STATUSES, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDeliveryHoursTable, WebhookDetail, WebhookFormat, WebhookFormatSchema, WebhookIncidentAlert, WebhookIncidentAlertsTable, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookPauseReason, WebhookReplay, WebhookReplayStatus, WebhookReplaysTable, WebhookStatus, WebhookStatusSchema, WebhookSummary, WebhooksTable, applicationDatabaseUrl, assertDbSplit, blockEndCursor, bucketHourly, closeDb, closeDbOrTimeout, committedHeight, compareStreamsCursor, exports_hmac as crypto, decodeStreamsCursor, describeDbUrl, exports_ed25519 as ed25519, encodeStreamsCursor, finalizedBurnHeight, formatWebhookSchemaErrors, generateSubgraphAgentSchema, generateSubgraphMarkdown, generateSubgraphOpenApi, generateSubgraphSpec, getDb, getDbSplitStatus, getEnv, getErrorMessage, getMigrationRole, getRawClient, getSourceDb, getTargetDb, isBnsDecoderEnabled, isEmptyRangeCursor, isPox4DecoderEnabled, isPox5DecoderEnabled, isSbtcDecoderEnabled, jsonb, logger, onChainPlane, onControlPlane, parseJsonb, resolveSourceUrl, resolveTargetUrl, setMigrationRole, sql, syncState };
4030
+ export { ABI_STATUSES, AbiStatus, Account, AccountBalanceAlerts, AccountBalanceAlertsTable, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiFailedRequest, ApiFailedRequestsTable, ApiKey, ApiKeyExpiredError, ApiKeyRevokedError, ApiKeyStatus, ApiKeysTable, ApiRequestLogRow, ApiRequestLogTable, ArchiveFetch, ArchiveFetchesTable, AuthenticationError, AuthorizationError, Block, BlocksTable, BnsMarketplaceAction, BnsMarketplaceEventsTable, BnsNameEventTopic, BnsNameEventsTable, BnsNamesTable, BnsNamespaceEventStatus, BnsNamespaceEventsTable, BnsNamespacesTable, BurnBlockRewardSlotsTable, BurnBlockRewardsTable, CHAIN_TRIGGER_FIELDS, CHAIN_TRIGGER_TYPES, CODE_TO_STATUS, ChainApplyDeliveryOf, ChainApplyEnvelope, ChainApplyEnvelopeOf, ChainEventEnvelope, ChainFtBurnData, ChainFtMintData, ChainFtTransferData, ChainNftBurnData, ChainNftMintData, ChainNftTransferData, ChainPrintEventData, ChainReadCacheTable, ChainReorgOrphanedEntry, ChainReorgRollbackDelivery, ChainReorgRollbackEnvelope, ChainReorgsTable, ChainStxBurnData, ChainStxLockData, ChainStxMintData, ChainStxTransferData, ChainTestDelivery, ChainTxLevelEvent, ChainWebhookDelivery, ChainWebhookEnvelope, CliDeviceLogin, CliDeviceLoginStatus, CliDeviceLoginsTable, CliDeviceProduct, ContactRequest, ContactRequestsTable, Contract, ContractsTable, CoverageSegmentsTable, CreateWebhookRequest, CreateWebhookRequestSchema, CreateWebhookResponse, DB_TO_STREAMS_EVENT_TYPE, DECODED_EVENT_TYPES2 as DECODED_EVENT_TYPES, DEFAULT_BTC_CONFIRMATIONS, Database, DatabaseError, DbPlane, DbReadRow, DbSplitStatus, DeadLetterEventsTable, DeadReason, DeadRow, DecodedEventType2 as DecodedEventType, DecodedEventsTable, DecoderCheckpointsTable, DeliveryRow, DeploySubgraphRequest, DeploySubgraphRequestSchema, DeploySubgraphResponse, EMPTY_RANGE_EVENT_INDEX_SENTINEL, Env, ErrorCode, ErrorCodes, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, FeedbackTicket, FeedbackTicketsTable, ForbiddenError, GapReason, HealthHour, HealthSnapshotPoint, HostedStackStateTable, INSIGHT_SEVERITIES, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountBalanceAlerts, InsertAccountCredits, InsertAccountSpendCap, InsertApiFailedRequest, InsertApiKey, InsertApiRequestLogRow, InsertArchiveFetch, InsertBlock, InsertContactRequest, InsertContract, InsertEvent, InsertFeedbackTicket, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertStateWrite, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertUpdateSubscriber, InsertUsageLedgerRow, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, Insight, InsightEvidence, InsightEvidenceSchema, InsightListResponse, InsightListResponseSchema, InsightMutesTable, InsightResourceKind, InsightResourceKindSchema, InsightSchema, InsightSeverity, InsightSeveritySchema, InsightsTable, InstancesTable, KeyRotatedError, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NotFoundError, NumericAsText, OBSERVER_JOURNAL_STATUSES, OauthClient, OauthClientsTable, OauthCodesTable, OauthGrant, OauthGrantsTable, OauthRefreshRetiredTable, OauthRequestStatus, OauthRequestsTable, OauthTokenKind, OauthTokensTable, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, ParsedCreateWebhookRequest, ParsedReplayWebhookRequest, ParsedUpdateWebhookRequest, PaymentRequiredError, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5CycleSignersTable, Pox5CyclesTable, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, PushPrefs, PushPrefsTable, PushSentTable, PushSubscription, PushSubscriptionsTable, RUNE_EVENT_TYPES, RateLimitError, ReindexResponse, RepairMode, ReplayResult, ReplayWebhookRequest, ReplayWebhookRequestSchema, RetryState, RotateSecretResponse, RunStatus, RuneApplyDeliveryOf, RuneApplyEnvelope, RuneEventType, SEVERITY_ORDER, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, STREAMS_CURSOR_VERSION, STREAMS_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_TO_DB_EVENT_TYPES, SUBGRAPH_STATES, SbtcDepositEvent, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SbtcWithdrawalEvent, SbtcWithdrawalSweptConfirmedEvent, SecondLayerError, SentinelAccount, SentinelAccountsTable, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StateWrite, StateWritesArchiveTable, StateWritesTable, StreamsCursor, StreamsCursorFeed, StreamsCursorFeedMismatchError, StreamsDbEventType, StreamsEventType, Subgraph, SubgraphAgentSchema, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphErrorGroupsTable, SubgraphGap, SubgraphGapEntry, SubgraphGapRange, SubgraphGapsResponse, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphQueryParams, SubgraphSpecFormat, SubgraphSpecOptions, SubgraphStatus, SubgraphSummary, SubgraphSyncInfo, SubgraphSyncState, SubgraphVerification, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, TenantSuspendedError, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountBalanceAlerts, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSendsTable, UpdateSubgraph, UpdateSubgraphOperation, UpdateSubscriber, UpdateSubscribersTable, UpdateTransaction, UpdateUsageLedgerRow, UpdateVmEvent, UpdateWebhook, UpdateWebhookOutbox, UpdateWebhookRequest, UpdateWebhookRequestSchema, UsageLedgerRow, UsageLedgerTable, VM_EVENT_TYPES, VM_NODE_TO_STORED_TYPE2 as VM_NODE_TO_STORED_TYPE, VM_STORED_TO_NODE_TYPE, ValidationError, VersionConflictError, VmEvent, VmEventType, VmEventsArchiveTable, VmEventsTable, VmNodeEventType, WEBHOOK_FORMATS, WEBHOOK_STATUSES, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDeliveryHoursTable, WebhookDetail, WebhookFormat, WebhookFormatSchema, WebhookIncidentAlert, WebhookIncidentAlertsTable, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookPauseReason, WebhookReplay, WebhookReplayStatus, WebhookReplaysTable, WebhookStatus, WebhookStatusSchema, WebhookSummary, WebhooksTable, applicationDatabaseUrl, assertDbSplit, blockEndCursor, bucketHourly, closeDb, closeDbOrTimeout, committedHeight, compareStreamsCursor, configuredSourceUrl, configuredTargetUrl, exports_hmac as crypto, decodeFeedCursor, decodeStreamsCursor, decodeTaggedStreamsCursor, describeDbUrl, exports_ed25519 as ed25519, encodeFeedCursor, encodeStreamsCursor, finalizedBurnHeight, formatWebhookSchemaErrors, generateSubgraphAgentSchema, generateSubgraphMarkdown, generateSubgraphOpenApi, generateSubgraphSpec, getDb, getDbSplitStatus, getEnv, getErrorMessage, getMigrationRole, getRawClient, getSourceDb, getTargetDb, isBnsDecoderEnabled, isEmptyRangeCursor, isPox4DecoderEnabled, isPox5DecoderEnabled, isSbtcDecoderEnabled, jsonb, logger, onChainPlane, onControlPlane, parseJsonb, resolveSourceUrl, resolveTargetUrl, setMigrationRole, sql, stacksNetwork, syncState };
package/dist/src/index.js CHANGED
@@ -59,6 +59,7 @@ var RUNE_EVENT_TYPES = [
59
59
  "rune_burn"
60
60
  ];
61
61
  // src/db-event-types.ts
62
+ var STREAMS_CURSOR_VERSION = 1;
62
63
  var STREAMS_DB_EVENT_TYPES = [
63
64
  "stx_transfer_event",
64
65
  "stx_mint_event",
@@ -143,11 +144,25 @@ function getEnv() {
143
144
  } else if (result.data.NETWORK) {
144
145
  enabledNetworks = [result.data.NETWORK];
145
146
  } else {
146
- enabledNetworks = ["mainnet"];
147
+ const named = stacksNetwork();
148
+ enabledNetworks = named === "testnet" ? ["testnet"] : ["mainnet"];
147
149
  }
148
150
  cachedEnv = { ...result.data, enabledNetworks };
149
151
  return cachedEnv;
150
152
  }
153
+ var warnedNetworkFallback = false;
154
+ function stacksNetwork(env = process.env) {
155
+ if (env.STACKS_NETWORK)
156
+ return env.STACKS_NETWORK;
157
+ if (env.NETWORK) {
158
+ if (!warnedNetworkFallback) {
159
+ warnedNetworkFallback = true;
160
+ console.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
161
+ }
162
+ return env.NETWORK;
163
+ }
164
+ return "mainnet";
165
+ }
151
166
  function isProductionEnv() {
152
167
  return process.env["NODE_ENV"] === "production";
153
168
  }
@@ -982,14 +997,20 @@ function applicationDatabaseUrl() {
982
997
  return process.env.DATABASE_URL || DEFAULT_URL;
983
998
  }
984
999
  function resolveSourceUrl() {
985
- if (!isPlatformMode())
986
- return applicationDatabaseUrl();
987
- return process.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL;
1000
+ return configuredSourceUrl() ?? DEFAULT_URL;
988
1001
  }
989
1002
  function resolveTargetUrl() {
1003
+ return configuredTargetUrl() ?? DEFAULT_URL;
1004
+ }
1005
+ function configuredSourceUrl() {
1006
+ if (!isPlatformMode())
1007
+ return process.env.DATABASE_URL || undefined;
1008
+ return process.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || undefined;
1009
+ }
1010
+ function configuredTargetUrl() {
990
1011
  if (!isPlatformMode())
991
- return applicationDatabaseUrl();
992
- return process.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL;
1012
+ return process.env.DATABASE_URL || undefined;
1013
+ return process.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || undefined;
993
1014
  }
994
1015
  function describeDbUrl(url) {
995
1016
  try {
@@ -1302,6 +1323,40 @@ function decodeStreamsCursor(cursor) {
1302
1323
  }
1303
1324
  return decoded;
1304
1325
  }
1326
+ var FEED_TAGS = ["btc", "vm"];
1327
+
1328
+ class StreamsCursorFeedMismatchError extends Error {
1329
+ expected;
1330
+ actual;
1331
+ constructor(expected, actual) {
1332
+ super(`cursor belongs to the ${actual} feed; this request reads the ${expected} feed`);
1333
+ this.expected = expected;
1334
+ this.actual = actual;
1335
+ this.name = "StreamsCursorFeedMismatchError";
1336
+ }
1337
+ }
1338
+ function encodeFeedCursor(feed, cursor) {
1339
+ const bare = encodeStreamsCursor(cursor);
1340
+ return feed === "stacks" ? bare : `${feed}:${bare}`;
1341
+ }
1342
+ function decodeTaggedStreamsCursor(raw) {
1343
+ for (const tag of FEED_TAGS) {
1344
+ if (raw.startsWith(`${tag}:`)) {
1345
+ return {
1346
+ feed: tag,
1347
+ cursor: decodeStreamsCursor(raw.slice(tag.length + 1))
1348
+ };
1349
+ }
1350
+ }
1351
+ return { feed: null, cursor: decodeStreamsCursor(raw) };
1352
+ }
1353
+ function decodeFeedCursor(raw, feed) {
1354
+ const decoded = decodeTaggedStreamsCursor(raw);
1355
+ if (decoded.feed !== null && decoded.feed !== feed) {
1356
+ throw new StreamsCursorFeedMismatchError(feed, decoded.feed);
1357
+ }
1358
+ return decoded.cursor;
1359
+ }
1305
1360
  function compareStreamsCursor(a, b) {
1306
1361
  if (a.block_height !== b.block_height) {
1307
1362
  return a.block_height < b.block_height ? -1 : 1;
@@ -1335,7 +1390,7 @@ function blockEndCursor(height) {
1335
1390
  // src/schemas/subgraphs.ts
1336
1391
  import { z as z2 } from "zod";
1337
1392
  var DeploySubgraphRequestSchema = z2.object({
1338
- name: z2.string().regex(/^[a-z0-9-]+$/, "lowercase alphanumeric + hyphens only").max(63),
1393
+ name: z2.string().regex(/^[a-z0-9-]+$/, "lowercase alphanumeric + hyphens only").max(54),
1339
1394
  description: z2.string().optional(),
1340
1395
  sources: z2.record(z2.string(), z2.record(z2.string(), z2.unknown())).refine((s) => Object.keys(s).length > 0, "Must have at least one source"),
1341
1396
  schema: z2.record(z2.string(), z2.unknown()),
@@ -2420,11 +2475,13 @@ export {
2420
2475
  SOURCE_READ_COLUMNS,
2421
2476
  SOURCE_READ_PKS,
2422
2477
  SOURCE_READ_TYPES,
2478
+ STREAMS_CURSOR_VERSION,
2423
2479
  STREAMS_DB_EVENT_TYPES,
2424
2480
  STREAMS_EVENT_TYPES,
2425
2481
  STREAMS_TO_DB_EVENT_TYPES,
2426
2482
  SUBGRAPH_STATES,
2427
2483
  SecondLayerError,
2484
+ StreamsCursorFeedMismatchError,
2428
2485
  TABLE_TO_DB,
2429
2486
  TenantSuspendedError,
2430
2487
  UpdateWebhookRequestSchema,
@@ -2445,10 +2502,15 @@ export {
2445
2502
  closeDbOrTimeout,
2446
2503
  committedHeight,
2447
2504
  compareStreamsCursor,
2505
+ configuredSourceUrl,
2506
+ configuredTargetUrl,
2448
2507
  exports_hmac as crypto,
2508
+ decodeFeedCursor,
2449
2509
  decodeStreamsCursor,
2510
+ decodeTaggedStreamsCursor,
2450
2511
  describeDbUrl,
2451
2512
  exports_ed25519 as ed25519,
2513
+ encodeFeedCursor,
2452
2514
  encodeStreamsCursor,
2453
2515
  finalizedBurnHeight,
2454
2516
  formatWebhookSchemaErrors,
@@ -2478,8 +2540,9 @@ export {
2478
2540
  resolveTargetUrl,
2479
2541
  setMigrationRole,
2480
2542
  sql2 as sql,
2543
+ stacksNetwork,
2481
2544
  syncState
2482
2545
  };
2483
2546
 
2484
- //# debugId=C1E5434557BE72FF64756E2164756E21
2547
+ //# debugId=1EF625DDF5B5DD6864756E2164756E21
2485
2548
  //# sourceMappingURL=index.js.map