@secondlayer/shared 11.8.0 → 11.9.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 (43) hide show
  1. package/dist/src/archive/range-digest.d.ts +31 -0
  2. package/dist/src/archive/semantic-digest-builder.d.ts +31 -0
  3. package/dist/src/coverage/index.d.ts +31 -0
  4. package/dist/src/coverage/index.js +13 -1
  5. package/dist/src/coverage/index.js.map +3 -3
  6. package/dist/src/db/index.d.ts +36 -1
  7. package/dist/src/db/index.js +2 -1
  8. package/dist/src/db/index.js.map +3 -3
  9. package/dist/src/db/queries/chain-reorgs.d.ts +31 -0
  10. package/dist/src/db/queries/chain-reorgs.js +2 -1
  11. package/dist/src/db/queries/chain-reorgs.js.map +3 -3
  12. package/dist/src/db/queries/contracts.d.ts +31 -0
  13. package/dist/src/db/queries/instance.d.ts +31 -0
  14. package/dist/src/db/queries/integrity.d.ts +31 -0
  15. package/dist/src/db/queries/subgraph-gaps.d.ts +31 -0
  16. package/dist/src/db/queries/subgraph-operations.d.ts +31 -0
  17. package/dist/src/db/queries/subgraphs.d.ts +31 -0
  18. package/dist/src/db/queries/sync-scope.d.ts +31 -0
  19. package/dist/src/db/queries/webhooks.d.ts +31 -0
  20. package/dist/src/db/schema.d.ts +35 -1
  21. package/dist/src/errors.d.ts +3 -3
  22. package/dist/src/errors.js.map +1 -1
  23. package/dist/src/index-http.js +2 -2
  24. package/dist/src/index-http.js.map +3 -3
  25. package/dist/src/index-internal-auth.d.ts +3 -6
  26. package/dist/src/index-internal-auth.js +2 -2
  27. package/dist/src/index-internal-auth.js.map +3 -3
  28. package/dist/src/index.d.ts +56 -5
  29. package/dist/src/index.js +60 -5
  30. package/dist/src/index.js.map +7 -7
  31. package/dist/src/node/local-client.d.ts +31 -0
  32. package/dist/src/schemas/index.d.ts +8 -1
  33. package/dist/src/schemas/index.js +46 -5
  34. package/dist/src/schemas/index.js.map +4 -4
  35. package/dist/src/schemas/subgraphs.d.ts +1 -1
  36. package/dist/src/schemas/subgraphs.js.map +1 -1
  37. package/dist/src/schemas/webhooks.d.ts +19 -1
  38. package/dist/src/schemas/webhooks.js +51 -6
  39. package/dist/src/schemas/webhooks.js.map +3 -3
  40. package/migrations/0137_webhook_outbox_last_error.ts +27 -0
  41. package/migrations/0138_usage_ledger.ts +46 -0
  42. package/migrations/0139_webhook_outbox_block_time.ts +28 -0
  43. package/package.json +1 -1
@@ -781,6 +781,7 @@ interface Database {
781
781
  coverage_segments: CoverageSegmentsTable;
782
782
  stage_failures: StageFailuresTable;
783
783
  archive_fetches: ArchiveFetchesTable;
784
+ usage_ledger: UsageLedgerTable;
784
785
  waitlists: WaitlistsTable;
785
786
  waitlist_signups: WaitlistSignupsTable;
786
787
  }
@@ -834,6 +835,30 @@ interface ArchiveFetchesTable {
834
835
  type ArchiveFetch = Selectable<ArchiveFetchesTable>;
835
836
  type InsertArchiveFetch = Insertable<ArchiveFetchesTable>;
836
837
  type UpdateArchiveFetch = Updateable<ArchiveFetchesTable>;
838
+ /**
839
+ * One metered ledger for every billable unit (archive partitions, hosted
840
+ * Index/Streams rows, and future hosted-stack meters). Append-only, written
841
+ * only by `meter()`. `idempotency_key` is UNIQUE so a retried submission
842
+ * no-ops instead of double-charging. `debited` is false when the balance
843
+ * (or a spend cap) refused the charge — the row still exists so the gap is
844
+ * visible, never silently dropped. `usd_micros` is negative for a Stripe
845
+ * top-up (`unit: "topup"`).
846
+ */
847
+ interface UsageLedgerTable {
848
+ id: Generated<string>;
849
+ account_id: string;
850
+ unit: string;
851
+ quantity: string | number | bigint;
852
+ usd_micros: string | number | bigint;
853
+ debited: Generated<boolean>;
854
+ source: string;
855
+ idempotency_key: string;
856
+ occurred_at: Generated<Date>;
857
+ recorded_at: Generated<Date>;
858
+ }
859
+ type UsageLedgerRow = Selectable<UsageLedgerTable>;
860
+ type InsertUsageLedgerRow = Insertable<UsageLedgerTable>;
861
+ type UpdateUsageLedgerRow = Updateable<UsageLedgerTable>;
837
862
  type Block = Selectable<BlocksTable>;
838
863
  type InsertBlock = Insertable<BlocksTable>;
839
864
  type UpdateBlock = Updateable<BlocksTable>;
@@ -934,10 +959,19 @@ interface WebhookOutboxTable {
934
959
  next_attempt_at: Generated<Date>;
935
960
  status: ColumnType<OutboxStatus, OutboxStatus | undefined, OutboxStatus>;
936
961
  is_replay: Generated<boolean>;
962
+ /** The chain block_time of the matched event/tx. Null for rows written
963
+ * before this column existed, and for the settlement scan path (not yet
964
+ * wired). Lets `delivered_at - block_time` measure end-to-end webhook
965
+ * latency without a join to SOURCE-plane `blocks`. */
966
+ block_time: Date | null;
937
967
  delivered_at: Date | null;
938
968
  failed_at: Date | null;
939
969
  locked_by: string | null;
940
970
  locked_until: Date | null;
971
+ /** Set when a reorg marks an in-flight row `dead` instead of retrying it
972
+ * into an orphaned fork. Null otherwise — delivery failures track their
973
+ * history on `webhooks.last_error`, not per-row. */
974
+ last_error: string | null;
941
975
  created_at: Generated<Date>;
942
976
  }
943
977
  type WebhookOutbox = Selectable<WebhookOutboxTable>;
@@ -2005,6 +2039,7 @@ declare const TABLE_TO_DB: {
2005
2039
  subgraph_processing_stats: string
2006
2040
  account_credits: string
2007
2041
  archive_fetches: string
2042
+ usage_ledger: string
2008
2043
  waitlists: string
2009
2044
  waitlist_signups: string
2010
2045
  service_heartbeats: string
@@ -2132,9 +2167,9 @@ declare class RateLimitError extends SecondLayerError {
2132
2167
  constructor(message: string);
2133
2168
  }
2134
2169
  /**
2135
- * HTTP 402. Carries the x402 challenge (or a retry-later reason) in `details` so
2136
- * the global error handler emits it in the body. The wire `PAYMENT-REQUIRED`
2137
- * header is set separately by the x402 middleware on the challenge path.
2170
+ * HTTP 402: insufficient credits. Carries a machine-readable reason (e.g.
2171
+ * `insufficient_credits`, `UPGRADE_REQUIRED`) in `details` so the global
2172
+ * error handler emits it in the body, alongside a top-up hint/link.
2138
2173
  */
2139
2174
  declare class PaymentRequiredError extends SecondLayerError {
2140
2175
  constructor(message: string, details?: Record<string, unknown>);
@@ -2205,6 +2240,15 @@ declare function encodeStreamsCursor(cursor: StreamsCursor): string;
2205
2240
  declare function decodeStreamsCursor(cursor: string): StreamsCursor;
2206
2241
  declare function compareStreamsCursor(a: StreamsCursor, b: StreamsCursor): number;
2207
2242
  declare function isEmptyRangeCursor(cursor: StreamsCursor): boolean;
2243
+ /**
2244
+ * Highest height a cursor has fully committed. Mid-block (`H:n`, n not the
2245
+ * empty-range sentinel) means the rest of H is still in flight — the
2246
+ * committed floor is H-1. Sentinel `H:2147483647` means H is done. One
2247
+ * implementation shared by every reader of a decoder/consumer checkpoint
2248
+ * (Subgraphs' `decoderBoundTip`, the Index `/public/status` route) so the
2249
+ * rule can never drift between them.
2250
+ */
2251
+ declare function committedHeight(cursor: string | null | undefined): number | null;
2208
2252
  /** Exclusive end of every event that can live in `height`. */
2209
2253
  declare function blockEndCursor(height: number): StreamsCursor;
2210
2254
  declare class Logger {
@@ -2397,7 +2441,7 @@ interface SubgraphQueryParams {
2397
2441
  filters?: Record<string, string>;
2398
2442
  }
2399
2443
  /**
2400
- * Request shape for `GET /api/subgraphs/:subgraphName/:tableName/aggregate`.
2444
+ * Request shape for `GET /v1/subgraphs/:subgraphName/:tableName/aggregate`.
2401
2445
  * `filters` reuses the list/count where-surface; the rest name the columns to
2402
2446
  * aggregate. SUM/MIN/MAX columns must be numeric (uint/int, plus `_block_height`).
2403
2447
  */
@@ -2645,6 +2689,13 @@ interface WebhookDetail extends WebhookSummary {
2645
2689
  circuitFailures: number;
2646
2690
  circuitOpenedAt: string | null;
2647
2691
  lastError: string | null;
2692
+ /** Set on a `kind="chain"` webhook when this instance's chain-trigger
2693
+ * evaluator isn't running (`SUBGRAPH_SOURCE` != `streams-index`) — the
2694
+ * webhook will never fire until that's fixed. Null otherwise. Surfaced
2695
+ * on create (so it's seen immediately) and on every read (so `secondlayer
2696
+ * webhooks doctor` reports it for a webhook created before the mismatch,
2697
+ * or on an instance whose config changed since). */
2698
+ warning: string | null;
2648
2699
  }
2649
2700
  interface CreateWebhookResponse {
2650
2701
  webhook: WebhookDetail;
@@ -3046,4 +3097,4 @@ declare function publicKeyPemFromPrivate(privateKeyPem: string): string;
3046
3097
  declare function ed25519KeyId(publicKeyPem: string): string;
3047
3098
  declare function signEd25519(payload: string, privateKey: KeyObject): string;
3048
3099
  declare function verifyEd25519(payload: string, signatureBase64: string, publicKey: KeyObject): boolean;
3049
- export { Account, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiKey, ApiKeysTable, 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, 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, DeadRow, DecodedEventType2 as DecodedEventType, DecodedEventsTable, DecoderCheckpointsTable, DeliveryRow, DeploySubgraphRequest, DeploySubgraphRequestSchema, DeploySubgraphResponse, EMPTY_RANGE_EVENT_INDEX_SENTINEL, Env, ErrorCode, ErrorCodes, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, ForbiddenError, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountCredits, InsertAccountSpendCap, InsertApiKey, InsertArchiveFetch, InsertBlock, InsertContract, InsertEvent, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, InstancesTable, KeyRotatedError, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NotFoundError, NumericAsText, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, ParsedCreateWebhookRequest, ParsedReplayWebhookRequest, ParsedUpdateWebhookRequest, PaymentRequiredError, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, RateLimitError, ReindexResponse, RepairMode, ReplayResult, ReplayWebhookRequest, ReplayWebhookRequestSchema, RetryState, RotateSecretResponse, RunStatus, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, STREAMS_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_TO_DB_EVENT_TYPES, SbtcDepositEvent, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SbtcWithdrawalEvent, SbtcWithdrawalSweptConfirmedEvent, SecondLayerError, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StreamsCursor, StreamsDbEventType, StreamsEventType, Subgraph, SubgraphAgentSchema, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphGap, SubgraphGapEntry, SubgraphGapRange, SubgraphGapsResponse, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphQueryParams, SubgraphSpecFormat, SubgraphSpecOptions, SubgraphSummary, SubgraphSyncInfo, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, TenantSuspendedError, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSubgraph, UpdateSubgraphOperation, UpdateTransaction, UpdateVmEvent, UpdateWebhook, UpdateWebhookOutbox, UpdateWebhookRequest, UpdateWebhookRequestSchema, 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_FILTER_OPERATORS, WEBHOOK_FORMATS, WEBHOOK_RUNTIMES, WEBHOOK_STATUSES, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDetail, WebhookFilter, WebhookFilterClause, WebhookFilterClauseSchema, WebhookFilterOperator, WebhookFilterOperatorSchema, WebhookFilterPrimitive, WebhookFilterPrimitiveSchema, WebhookFilterSchema, WebhookFormat, WebhookFormatSchema, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookRuntime, WebhookRuntimeSchema, WebhookSchemaColumn, WebhookSchemaTable, WebhookSchemaTables, WebhookStatus, WebhookStatusSchema, WebhookSummary, WebhooksTable, applicationDatabaseUrl, assertDbSplit, blockEndCursor, closeDb, compareStreamsCursor, exports_hmac as crypto, decodeStreamsCursor, exports_ed25519 as ed25519, encodeStreamsCursor, finalizedBurnHeight, formatWebhookSchemaErrors, generateSubgraphAgentSchema, generateSubgraphMarkdown, generateSubgraphOpenApi, generateSubgraphSpec, getDb, getDbSplitStatus, getEnv, getErrorMessage, getMigrationRole, getRawClient, getRawClientFor, getSourceDb, getTargetDb, isBnsDecoderEnabled, isEmptyRangeCursor, isPox4DecoderEnabled, isPox5DecoderEnabled, isSbtcDecoderEnabled, jsonb, logger, onChainPlane, onControlPlane, parseJsonb, setMigrationRole, sql, validateWebhookFilterForTable };
3100
+ export { Account, AccountCredits, AccountCreditsTable, AccountSpendCap, AccountSpendCapsTable, AccountsTable, ApiKey, ApiKeysTable, 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, 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, DeadRow, DecodedEventType2 as DecodedEventType, DecodedEventsTable, DecoderCheckpointsTable, DeliveryRow, DeploySubgraphRequest, DeploySubgraphRequestSchema, DeploySubgraphResponse, EMPTY_RANGE_EVENT_INDEX_SENTINEL, Env, ErrorCode, ErrorCodes, Event, EventsArchiveTable, EventsTable, FailureClass, FailureUnit, ForbiddenError, IndexColumn, IndexColumnType, IndexPrimaryKey, IndexProgress, IndexProgressTable, InsertAccount, InsertAccountCredits, InsertAccountSpendCap, InsertApiKey, InsertArchiveFetch, InsertBlock, InsertContract, InsertEvent, InsertIndexProgress, InsertMagicLink, InsertMempoolTransaction, InsertSession, InsertSubgraph, InsertSubgraphGap, InsertSubgraphHealthSnapshot, InsertSubgraphOperation, InsertTransaction, InsertUsageLedgerRow, InsertVmEvent, InsertWaitlistSignup, InsertWebhook, InsertWebhookDelivery, InsertWebhookOutbox, InstancesTable, KeyRotatedError, MagicLink, MagicLinksTable, MempoolTransaction, MempoolTransactionsTable, MigrationRole, NativeClock, NotFoundError, NumericAsText, ObserverJournalStatus, ObserverJournalTable, OutboxStatus, ParsedCreateWebhookRequest, ParsedReplayWebhookRequest, ParsedUpdateWebhookRequest, PaymentRequiredError, PendingForkBlocksTable, Pox4CallsTable, Pox4FunctionName, Pox5EventTopic, Pox5EventsTable, ProcessedStripeEventsTable, RateLimitError, ReindexResponse, RepairMode, ReplayResult, ReplayWebhookRequest, ReplayWebhookRequestSchema, RetryState, RotateSecretResponse, RunStatus, SOURCE_READ_COLUMNS, SOURCE_READ_PKS, SOURCE_READ_TYPES, STREAMS_DB_EVENT_TYPES, STREAMS_EVENT_TYPES, STREAMS_TO_DB_EVENT_TYPES, SbtcDepositEvent, SbtcEventTopic, SbtcEventsTable, SbtcSettlementsTable, SbtcTokenEventType, SbtcTokenEventsTable, SbtcWithdrawalEvent, SbtcWithdrawalSweptConfirmedEvent, SecondLayerError, ServiceHeartbeatsTable, Session, SessionsTable, StageBlockReceiptsTable, StageFailuresTable, StageKind, StageRegistryTable, StageRunsTable, StreamsCursor, StreamsDbEventType, StreamsEventType, Subgraph, SubgraphAgentSchema, SubgraphAggregateParams, SubgraphAggregateResponse, SubgraphDetail, SubgraphGap, SubgraphGapEntry, SubgraphGapRange, SubgraphGapsResponse, SubgraphGapsTable, SubgraphHealthSnapshot, SubgraphHealthSnapshotsTable, SubgraphOperation, SubgraphOperationKind, SubgraphOperationStatus, SubgraphOperationsTable, SubgraphProcessingStatsTable, SubgraphQueryParams, SubgraphSpecFormat, SubgraphSpecOptions, SubgraphSummary, SubgraphSyncInfo, SubgraphViolationsTable, SubgraphsTable, SyncScopesTable, TABLE_TO_DB, TenantSuspendedError, Transaction, TransactionsArchiveTable, TransactionsTable, TriggerEvaluatorState, TriggerEvaluatorStateTable, UpdateAccountCredits, UpdateAccountSpendCap, UpdateApiKey, UpdateArchiveFetch, UpdateBlock, UpdateContract, UpdateEvent, UpdateIndexProgress, UpdateSubgraph, UpdateSubgraphOperation, 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_FILTER_OPERATORS, WEBHOOK_FORMATS, WEBHOOK_RUNTIMES, WEBHOOK_STATUSES, Waitlist, WaitlistSignup, WaitlistSignupsTable, WaitlistsTable, Webhook, WebhookDeliveriesTable, WebhookDelivery, WebhookDetail, WebhookFilter, WebhookFilterClause, WebhookFilterClauseSchema, WebhookFilterOperator, WebhookFilterOperatorSchema, WebhookFilterPrimitive, WebhookFilterPrimitiveSchema, WebhookFilterSchema, WebhookFormat, WebhookFormatSchema, WebhookKind, WebhookOutbox, WebhookOutboxTable, WebhookRuntime, WebhookRuntimeSchema, WebhookSchemaColumn, WebhookSchemaTable, WebhookSchemaTables, WebhookStatus, WebhookStatusSchema, WebhookSummary, WebhooksTable, applicationDatabaseUrl, assertDbSplit, blockEndCursor, closeDb, committedHeight, compareStreamsCursor, exports_hmac as crypto, decodeStreamsCursor, exports_ed25519 as ed25519, encodeStreamsCursor, finalizedBurnHeight, formatWebhookSchemaErrors, generateSubgraphAgentSchema, generateSubgraphMarkdown, generateSubgraphOpenApi, generateSubgraphSpec, getDb, getDbSplitStatus, getEnv, getErrorMessage, getMigrationRole, getRawClient, getRawClientFor, getSourceDb, getTargetDb, isBnsDecoderEnabled, isEmptyRangeCursor, isPox4DecoderEnabled, isPox5DecoderEnabled, isSbtcDecoderEnabled, jsonb, logger, onChainPlane, onControlPlane, parseJsonb, setMigrationRole, sql, validateWebhookFilterForTable };
package/dist/src/index.js CHANGED
@@ -847,6 +847,7 @@ var TABLE_TO_DB = {
847
847
  subgraph_processing_stats: "target",
848
848
  account_credits: "target",
849
849
  archive_fetches: "target",
850
+ usage_ledger: "target",
850
851
  waitlists: "target",
851
852
  waitlist_signups: "target",
852
853
  service_heartbeats: "both"
@@ -1200,6 +1201,18 @@ function compareStreamsCursor(a, b) {
1200
1201
  function isEmptyRangeCursor(cursor) {
1201
1202
  return cursor.event_index === EMPTY_RANGE_EVENT_INDEX_SENTINEL;
1202
1203
  }
1204
+ function committedHeight(cursor) {
1205
+ if (!cursor)
1206
+ return null;
1207
+ try {
1208
+ const decoded = decodeStreamsCursor(cursor);
1209
+ if (isEmptyRangeCursor(decoded))
1210
+ return decoded.block_height;
1211
+ return Math.max(0, decoded.block_height - 1);
1212
+ } catch {
1213
+ return null;
1214
+ }
1215
+ }
1203
1216
  function blockEndCursor(height) {
1204
1217
  return {
1205
1218
  block_height: height,
@@ -1235,6 +1248,47 @@ var WEBHOOK_RUNTIMES = [
1235
1248
  "node"
1236
1249
  ];
1237
1250
  var WEBHOOK_STATUSES = ["active", "paused", "error"];
1251
+ var WEBHOOK_MAX_RETRIES_CEILING_DEFAULT = 100;
1252
+ var WEBHOOK_TIMEOUT_MS_CEILING_DEFAULT = 300000;
1253
+ function ceilingFromEnv(envVar, fallback) {
1254
+ const raw = process.env[envVar];
1255
+ if (raw === undefined)
1256
+ return fallback;
1257
+ const parsed = Number.parseInt(raw, 10);
1258
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
1259
+ }
1260
+ function webhookMaxRetriesCeiling() {
1261
+ return ceilingFromEnv("WEBHOOK_MAX_RETRIES_CEILING", WEBHOOK_MAX_RETRIES_CEILING_DEFAULT);
1262
+ }
1263
+ function webhookTimeoutMsCeiling() {
1264
+ return ceilingFromEnv("WEBHOOK_TIMEOUT_MS_CEILING", WEBHOOK_TIMEOUT_MS_CEILING_DEFAULT);
1265
+ }
1266
+ function maxRetriesField() {
1267
+ return z3.number().int().min(0).optional().superRefine((v, ctx) => {
1268
+ if (v === undefined)
1269
+ return;
1270
+ const ceiling = webhookMaxRetriesCeiling();
1271
+ if (v > ceiling) {
1272
+ ctx.addIssue({
1273
+ code: "custom",
1274
+ message: `maxRetries exceeds ceiling (${ceiling})`
1275
+ });
1276
+ }
1277
+ });
1278
+ }
1279
+ function timeoutMsField() {
1280
+ return z3.number().int().min(100).optional().superRefine((v, ctx) => {
1281
+ if (v === undefined)
1282
+ return;
1283
+ const ceiling = webhookTimeoutMsCeiling();
1284
+ if (v > ceiling) {
1285
+ ctx.addIssue({
1286
+ code: "custom",
1287
+ message: `timeoutMs exceeds ceiling (${ceiling})`
1288
+ });
1289
+ }
1290
+ });
1291
+ }
1238
1292
  var WEBHOOK_FILTER_OPERATORS = [
1239
1293
  "eq",
1240
1294
  "neq",
@@ -1455,8 +1509,8 @@ var CreateWebhookRequestSchema = z3.object({
1455
1509
  format: WebhookFormatSchema.default("standard-webhooks"),
1456
1510
  runtime: WebhookRuntimeSchema.nullable().optional(),
1457
1511
  authConfig: z3.record(z3.string(), z3.unknown()).optional(),
1458
- maxRetries: z3.number().int().min(0).max(100).optional(),
1459
- timeoutMs: z3.number().int().min(100).max(300000).optional(),
1512
+ maxRetries: maxRetriesField(),
1513
+ timeoutMs: timeoutMsField(),
1460
1514
  concurrency: z3.number().int().min(1).max(100).optional()
1461
1515
  }).refine((v) => {
1462
1516
  const subgraphMode = v.subgraphName !== undefined || v.tableName !== undefined;
@@ -1479,8 +1533,8 @@ var UpdateWebhookRequestSchema = z3.object({
1479
1533
  format: WebhookFormatSchema.optional(),
1480
1534
  runtime: WebhookRuntimeSchema.nullable().optional(),
1481
1535
  authConfig: z3.record(z3.string(), z3.unknown()).optional(),
1482
- maxRetries: z3.number().int().min(0).max(100).optional(),
1483
- timeoutMs: z3.number().int().min(100).max(300000).optional(),
1536
+ maxRetries: maxRetriesField(),
1537
+ timeoutMs: timeoutMsField(),
1484
1538
  concurrency: z3.number().int().min(1).max(100).optional()
1485
1539
  }).refine((value) => Object.keys(value).length > 0, {
1486
1540
  message: "At least one field must be provided"
@@ -2113,6 +2167,7 @@ export {
2113
2167
  assertDbSplit,
2114
2168
  blockEndCursor,
2115
2169
  closeDb,
2170
+ committedHeight,
2116
2171
  compareStreamsCursor,
2117
2172
  exports_hmac as crypto,
2118
2173
  decodeStreamsCursor,
@@ -2148,5 +2203,5 @@ export {
2148
2203
  validateWebhookFilterForTable
2149
2204
  };
2150
2205
 
2151
- //# debugId=920042D17F4879CF64756E2164756E21
2206
+ //# debugId=180D1AC51668CDD164756E2164756E21
2152
2207
  //# sourceMappingURL=index.js.map