@secondlayer/subgraphs 3.2.1 → 3.3.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 (36) hide show
  1. package/README.md +81 -0
  2. package/dist/src/index.d.ts +71 -9
  3. package/dist/src/index.js +461 -54
  4. package/dist/src/index.js.map +11 -9
  5. package/dist/src/runtime/block-processor.d.ts +37 -9
  6. package/dist/src/runtime/block-processor.js +127 -37
  7. package/dist/src/runtime/block-processor.js.map +5 -5
  8. package/dist/src/runtime/catchup.d.ts +34 -8
  9. package/dist/src/runtime/catchup.js +125 -36
  10. package/dist/src/runtime/catchup.js.map +5 -5
  11. package/dist/src/runtime/context.d.ts +27 -1
  12. package/dist/src/runtime/context.js +13 -2
  13. package/dist/src/runtime/context.js.map +3 -3
  14. package/dist/src/runtime/processor.js +143 -39
  15. package/dist/src/runtime/processor.js.map +8 -8
  16. package/dist/src/runtime/reindex.d.ts +34 -8
  17. package/dist/src/runtime/reindex.js +131 -36
  18. package/dist/src/runtime/reindex.js.map +6 -6
  19. package/dist/src/runtime/reorg.d.ts +34 -8
  20. package/dist/src/runtime/reorg.js +131 -39
  21. package/dist/src/runtime/reorg.js.map +6 -6
  22. package/dist/src/runtime/runner.d.ts +43 -9
  23. package/dist/src/runtime/source-matcher.d.ts +19 -10
  24. package/dist/src/runtime/source-matcher.js +26 -6
  25. package/dist/src/runtime/source-matcher.js.map +3 -3
  26. package/dist/src/schema/index.d.ts +42 -8
  27. package/dist/src/schema/index.js +57 -19
  28. package/dist/src/schema/index.js.map +5 -5
  29. package/dist/src/service.js +143 -39
  30. package/dist/src/service.js.map +8 -8
  31. package/dist/src/triggers/index.d.ts +16 -8
  32. package/dist/src/types.d.ts +35 -9
  33. package/dist/src/validate.d.ts +34 -8
  34. package/dist/src/validate.js +10 -3
  35. package/dist/src/validate.js.map +3 -3
  36. package/package.json +3 -3
@@ -2,12 +2,12 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/validate.ts", "../src/schema/generator.ts", "../src/schema/utils.ts", "../src/schema/deployer.ts"],
4
4
  "sourcesContent": [
5
- "import { z } from \"zod/v4\";\nimport type {\n\tColumnType,\n\tSubgraphColumn,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n\tSubgraphTable,\n} from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63)\n\t.regex(\n\t\t/^[a-z][a-z0-9-]*$/,\n\t\t\"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n\t);\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n\ttype: ColumnTypeSchema,\n\tnullable: z.boolean().optional(),\n\tindexed: z.boolean().optional(),\n\tsearch: z.boolean().optional(),\n\tdefault: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n\tcolumns: z\n\t\t.record(z.string(), SubgraphColumnSchema)\n\t\t.refine(\n\t\t\t(c) => Object.keys(c).length > 0,\n\t\t\t\"Table must have at least one column\",\n\t\t),\n\tindexes: z.array(z.array(z.string())).optional(),\n\tuniqueKeys: z.array(z.array(z.string())).optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n\t.record(z.string(), SubgraphTableSchema)\n\t.refine(\n\t\t(s) => Object.keys(s).length > 0,\n\t\t\"Schema must have at least one table\",\n\t) as z.ZodType<Record<string, SubgraphTable>>;\n\nconst VALID_FILTER_TYPES = [\n\t\"stx_transfer\",\n\t\"stx_mint\",\n\t\"stx_burn\",\n\t\"stx_lock\",\n\t\"ft_transfer\",\n\t\"ft_mint\",\n\t\"ft_burn\",\n\t\"nft_transfer\",\n\t\"nft_mint\",\n\t\"nft_burn\",\n\t\"contract_call\",\n\t\"contract_deploy\",\n\t\"print_event\",\n] as const;\n\nexport const SubgraphFilterSchema: z.ZodType<SubgraphFilter> = z\n\t.object({\n\t\ttype: z.enum(VALID_FILTER_TYPES),\n\t\t// All optional fields across all filter types\n\t\tsender: z.string().optional(),\n\t\trecipient: z.string().optional(),\n\t\tminAmount: z.bigint().optional(),\n\t\tmaxAmount: z.bigint().optional(),\n\t\tassetIdentifier: z.string().optional(),\n\t\tcontractId: z.string().optional(),\n\t\tfunctionName: z.string().optional(),\n\t\tcaller: z.string().optional(),\n\t\tdeployer: z.string().optional(),\n\t\tcontractName: z.string().optional(),\n\t\ttopic: z.string().optional(),\n\t\tlockedAddress: z.string().optional(),\n\t\tabi: z.record(z.string(), z.any()).optional(),\n\t})\n\t.strict() as unknown as z.ZodType<SubgraphFilter>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object(\n\t{\n\t\tname: SubgraphNameSchema,\n\t\tversion: z.string().optional(),\n\t\tdescription: z.string().optional(),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), SubgraphFilterSchema)\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: SubgraphSchemaSchema,\n\t\thandlers: z.record(z.string(), z.any()),\n\t},\n) as unknown as z.ZodType<SubgraphDefinition>;\n\n/**\n * Validates a subgraph definition, returning the parsed result or throwing on failure.\n */\nexport function validateSubgraphDefinition(def: unknown): SubgraphDefinition {\n\treturn SubgraphDefinitionSchema.parse(def);\n}\n",
6
- "import { createHash } from \"node:crypto\";\nimport type { ColumnType, SubgraphDefinition } from \"../types.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\nexport const TYPE_MAP: Record<ColumnType, string> = {\n\ttext: \"TEXT\",\n\tuint: \"NUMERIC\",\n\tint: \"NUMERIC\",\n\tprincipal: \"TEXT\",\n\tboolean: \"BOOLEAN\",\n\ttimestamp: \"TIMESTAMPTZ\",\n\tjsonb: \"JSONB\",\n};\n\nexport interface GeneratedSQL {\n\tstatements: string[];\n\thash: string;\n}\n\nfunction escapeLiteralDefault(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Generates PostgreSQL DDL statements for a subgraph definition.\n * Creates a dedicated schema `subgraph_<name>` with one table per schema entry,\n * each with auto-columns and indexes.\n */\nexport function generateSubgraphSQL(\n\tdef: SubgraphDefinition,\n\tschemaNameOverride?: string,\n): GeneratedSQL {\n\tconst schemaName = schemaNameOverride ?? pgSchemaName(def.name);\n\tconst statements: string[] = [];\n\n\t// Check if any column uses search (trigram)\n\tconst needsTrgm = Object.values(def.schema).some((table) =>\n\t\tObject.values(table.columns).some((col) => col.search),\n\t);\n\n\tif (needsTrgm) {\n\t\tstatements.push(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\");\n\t}\n\n\t// Schema namespace\n\tstatements.push(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);\n\n\t// One table per schema entry\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\n\t\t// Auto-columns + user columns\n\t\tconst columnDefs: string[] = [\n\t\t\t\"_id BIGSERIAL PRIMARY KEY\",\n\t\t\t\"_block_height BIGINT NOT NULL\",\n\t\t\t\"_tx_id TEXT NOT NULL\",\n\t\t\t\"_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\",\n\t\t];\n\n\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\tconst nullable = col.nullable ? \"\" : \" NOT NULL\";\n\t\t\tlet colDef = `${colName} ${sqlType}${nullable}`;\n\t\t\tif (col.default !== undefined) {\n\t\t\t\tcolDef += ` DEFAULT ${escapeLiteralDefault(col.default)}`;\n\t\t\t}\n\t\t\tcolumnDefs.push(colDef);\n\t\t}\n\n\t\tstatements.push(\n\t\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${columnDefs.join(\",\\n \")}\\n)`,\n\t\t);\n\n\t\t// Auto-indexes on meta columns\n\t\tstatements.push(\n\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`,\n\t\t);\n\t\tstatements.push(\n\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`,\n\t\t);\n\n\t\t// Single-column indexes\n\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\tif (col.indexed) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Trigram GIN indexes for search columns\n\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\tif (col.search) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Composite indexes\n\t\tif (tableDef.indexes) {\n\t\t\tfor (let i = 0; i < tableDef.indexes.length; i++) {\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\tconst cols = tableDef.indexes[i]!;\n\t\t\t\tconst idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.join(\", \")})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Unique constraints (required for upsert ON CONFLICT)\n\t\tif (tableDef.uniqueKeys) {\n\t\t\tfor (let i = 0; i < tableDef.uniqueKeys.length; i++) {\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\tconst cols = tableDef.uniqueKeys[i]!;\n\t\t\t\tconst constraintName = `uq_${schemaName}_${tableName}_${cols.join(\"_\")}`;\n\t\t\t\tstatements.push(\n\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.join(\", \")})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Hash based on schema structure only — version intentionally excluded\n\t// so server-managed version bumps don't look like schema changes\n\tconst hashInput = JSON.stringify(\n\t\t{\n\t\t\tname: def.name,\n\t\t\tschema: def.schema,\n\t\t\tsources: def.sources,\n\t\t},\n\t\t(_key, value) => (typeof value === \"bigint\" ? value.toString() : value),\n\t);\n\t// node crypto (not Bun.hash) so the published node-runtime `sl` CLI can\n\t// compute schema hashes too (e.g. `sl subgraphs inspect`).\n\tconst hash = createHash(\"sha256\").update(hashInput).digest(\"hex\");\n\n\treturn { statements, hash };\n}\n",
5
+ "import { z } from \"zod/v4\";\nimport type {\n\tColumnType,\n\tSubgraphColumn,\n\tSubgraphDefinition,\n\tSubgraphFilter,\n\tSubgraphTable,\n} from \"./types.ts\";\n\nexport const SubgraphNameSchema: z.ZodType<string> = z\n\t.string()\n\t.min(1)\n\t.max(63)\n\t.regex(\n\t\t/^[a-z][a-z0-9-]*$/,\n\t\t\"Must start with lowercase letter, contain only lowercase alphanumeric and hyphens\",\n\t);\n\nexport const ColumnTypeSchema: z.ZodType<ColumnType> = z.enum([\n\t\"text\",\n\t\"uint\",\n\t\"int\",\n\t\"principal\",\n\t\"boolean\",\n\t\"timestamp\",\n\t\"jsonb\",\n]);\n\nexport const SubgraphColumnSchema: z.ZodType<SubgraphColumn> = z.object({\n\ttype: ColumnTypeSchema,\n\tnullable: z.boolean().optional(),\n\tindexed: z.boolean().optional(),\n\tsearch: z.boolean().optional(),\n\tdefault: z.union([z.string(), z.number(), z.boolean()]).optional(),\n}) as z.ZodType<SubgraphColumn>;\n\nexport const SubgraphTableSchema: z.ZodType<SubgraphTable> = z.object({\n\tcolumns: z\n\t\t.record(z.string(), SubgraphColumnSchema)\n\t\t.refine(\n\t\t\t(c) => Object.keys(c).length > 0,\n\t\t\t\"Table must have at least one column\",\n\t\t),\n\tindexes: z.array(z.array(z.string())).optional(),\n\tuniqueKeys: z.array(z.array(z.string())).optional(),\n\trelations: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: z.string(),\n\t\t\t\treferences: z.string(),\n\t\t\t\tfields: z.array(z.string()).min(1),\n\t\t\t\treferencedColumns: z.array(z.string()).min(1),\n\t\t\t}),\n\t\t)\n\t\t.optional(),\n}) as z.ZodType<SubgraphTable>;\n\nexport const SubgraphSchemaSchema: z.ZodType<Record<string, SubgraphTable>> = z\n\t.record(z.string(), SubgraphTableSchema)\n\t.refine(\n\t\t(s) => Object.keys(s).length > 0,\n\t\t\"Schema must have at least one table\",\n\t) as z.ZodType<Record<string, SubgraphTable>>;\n\nconst VALID_FILTER_TYPES = [\n\t\"stx_transfer\",\n\t\"stx_mint\",\n\t\"stx_burn\",\n\t\"stx_lock\",\n\t\"ft_transfer\",\n\t\"ft_mint\",\n\t\"ft_burn\",\n\t\"nft_transfer\",\n\t\"nft_mint\",\n\t\"nft_burn\",\n\t\"contract_call\",\n\t\"contract_deploy\",\n\t\"print_event\",\n] as const;\n\nexport const SubgraphFilterSchema: z.ZodType<SubgraphFilter> = z\n\t.object({\n\t\ttype: z.enum(VALID_FILTER_TYPES),\n\t\t// All optional fields across all filter types\n\t\tsender: z.string().optional(),\n\t\trecipient: z.string().optional(),\n\t\tminAmount: z.bigint().optional(),\n\t\tmaxAmount: z.bigint().optional(),\n\t\tassetIdentifier: z.string().optional(),\n\t\tcontractId: z.string().optional(),\n\t\tfunctionName: z.string().optional(),\n\t\tcaller: z.string().optional(),\n\t\tdeployer: z.string().optional(),\n\t\tcontractName: z.string().optional(),\n\t\ttopic: z.string().optional(),\n\t\tlockedAddress: z.string().optional(),\n\t\tabi: z.record(z.string(), z.any()).optional(),\n\t\ttrait: z.string().optional(),\n\t})\n\t.strict() as unknown as z.ZodType<SubgraphFilter>;\n\nexport const SubgraphDefinitionSchema: z.ZodType<SubgraphDefinition> = z.object(\n\t{\n\t\tname: SubgraphNameSchema,\n\t\tversion: z.string().optional(),\n\t\tdescription: z.string().optional(),\n\t\tstartBlock: z.number().int().nonnegative().optional(),\n\t\tsources: z\n\t\t\t.record(z.string(), SubgraphFilterSchema)\n\t\t\t.refine(\n\t\t\t\t(s) => Object.keys(s).length > 0,\n\t\t\t\t\"Must have at least one source\",\n\t\t\t),\n\t\tschema: SubgraphSchemaSchema,\n\t\thandlers: z.record(z.string(), z.any()),\n\t},\n) as unknown as z.ZodType<SubgraphDefinition>;\n\n/**\n * Validates a subgraph definition, returning the parsed result or throwing on failure.\n */\nexport function validateSubgraphDefinition(def: unknown): SubgraphDefinition {\n\treturn SubgraphDefinitionSchema.parse(def);\n}\n",
6
+ "import { createHash } from \"node:crypto\";\nimport type { ColumnType, SubgraphDefinition } from \"../types.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\nexport const TYPE_MAP: Record<ColumnType, string> = {\n\ttext: \"TEXT\",\n\tuint: \"NUMERIC\",\n\tint: \"NUMERIC\",\n\tprincipal: \"TEXT\",\n\tboolean: \"BOOLEAN\",\n\ttimestamp: \"TIMESTAMPTZ\",\n\tjsonb: \"JSONB\",\n};\n\nexport interface GeneratedSQL {\n\tstatements: string[];\n\thash: string;\n}\n\nfunction escapeLiteralDefault(value: unknown): string {\n\tif (value === null || value === undefined) return \"NULL\";\n\tif (typeof value === \"number\" || typeof value === \"bigint\")\n\t\treturn String(value);\n\tif (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n\treturn `'${String(value).replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Generates PostgreSQL DDL statements for a subgraph definition.\n * Creates a dedicated schema `subgraph_<name>` with one table per schema entry,\n * each with auto-columns and indexes.\n */\nexport function generateSubgraphSQL(\n\tdef: SubgraphDefinition,\n\tschemaNameOverride?: string,\n): GeneratedSQL {\n\tconst schemaName = schemaNameOverride ?? pgSchemaName(def.name);\n\tconst statements: string[] = [];\n\n\t// Check if any column uses search (trigram)\n\tconst needsTrgm = Object.values(def.schema).some((table) =>\n\t\tObject.values(table.columns).some((col) => col.search),\n\t);\n\n\tif (needsTrgm) {\n\t\tstatements.push(\"CREATE EXTENSION IF NOT EXISTS pg_trgm\");\n\t}\n\n\t// Schema namespace\n\tstatements.push(`CREATE SCHEMA IF NOT EXISTS ${schemaName}`);\n\n\t// One table per schema entry\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\n\t\t// Auto-columns + user columns\n\t\tconst columnDefs: string[] = [\n\t\t\t\"_id BIGSERIAL PRIMARY KEY\",\n\t\t\t\"_block_height BIGINT NOT NULL\",\n\t\t\t\"_tx_id TEXT NOT NULL\",\n\t\t\t\"_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\",\n\t\t];\n\n\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\tconst nullable = col.nullable ? \"\" : \" NOT NULL\";\n\t\t\tlet colDef = `${colName} ${sqlType}${nullable}`;\n\t\t\tif (col.default !== undefined) {\n\t\t\t\tcolDef += ` DEFAULT ${escapeLiteralDefault(col.default)}`;\n\t\t\t}\n\t\t\tcolumnDefs.push(colDef);\n\t\t}\n\n\t\tstatements.push(\n\t\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${columnDefs.join(\",\\n \")}\\n)`,\n\t\t);\n\n\t\t// Auto-indexes on meta columns\n\t\tstatements.push(\n\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`,\n\t\t);\n\t\tstatements.push(\n\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`,\n\t\t);\n\n\t\t// Single-column indexes\n\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\tif (col.indexed) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Trigram GIN indexes for search columns\n\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\tif (col.search) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Composite indexes\n\t\tif (tableDef.indexes) {\n\t\t\tfor (let i = 0; i < tableDef.indexes.length; i++) {\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\tconst cols = tableDef.indexes[i]!;\n\t\t\t\tconst idxName = `idx_${schemaName}_${tableName}_composite_${i}`;\n\t\t\t\tstatements.push(\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualifiedName} (${cols.join(\", \")})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Unique constraints (required for upsert ON CONFLICT)\n\t\tif (tableDef.uniqueKeys) {\n\t\t\tfor (let i = 0; i < tableDef.uniqueKeys.length; i++) {\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\tconst cols = tableDef.uniqueKeys[i]!;\n\t\t\t\tconst constraintName = `uq_${schemaName}_${tableName}_${cols.join(\"_\")}`;\n\t\t\t\tstatements.push(\n\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD CONSTRAINT ${constraintName} UNIQUE (${cols.join(\", \")})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Foreign keys are added in a second pass so every referenced table exists.\n\t// These mirror the ORM relations emitted by the codegen (no drift) and require\n\t// the referenced columns to be a UNIQUE key on the target table.\n\tfor (const [tableName, tableDef] of Object.entries(def.schema)) {\n\t\tfor (const rel of tableDef.relations ?? []) {\n\t\t\tconst constraintName = `fk_${schemaName}_${tableName}_${rel.name}`;\n\t\t\tstatements.push(\n\t\t\t\t`ALTER TABLE ${schemaName}.${tableName} ADD CONSTRAINT ${constraintName} ` +\n\t\t\t\t\t`FOREIGN KEY (${rel.fields.join(\", \")}) ` +\n\t\t\t\t\t`REFERENCES ${schemaName}.${rel.references} (${rel.referencedColumns.join(\", \")})`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Hash based on schema structure only — version intentionally excluded\n\t// so server-managed version bumps don't look like schema changes\n\tconst hashInput = JSON.stringify(\n\t\t{\n\t\t\tname: def.name,\n\t\t\tschema: def.schema,\n\t\t\tsources: def.sources,\n\t\t},\n\t\t(_key, value) => (typeof value === \"bigint\" ? value.toString() : value),\n\t);\n\t// node crypto (not Bun.hash) so the published node-runtime `sl` CLI can\n\t// compute schema hashes too (e.g. `sl subgraphs inspect`).\n\tconst hash = createHash(\"sha256\").update(hashInput).digest(\"hex\");\n\n\treturn { statements, hash };\n}\n",
7
7
  "// Re-export canonical pgSchemaName from shared\nexport { pgSchemaName } from \"@secondlayer/shared/db/queries/subgraphs\";\n",
8
- "import type { Database } from \"@secondlayer/shared/db\";\nimport { type Kysely, sql } from \"kysely\";\nimport type { SubgraphDefinition, SubgraphSchema } from \"../types.ts\";\nimport { validateSubgraphDefinition } from \"../validate.ts\";\nimport { TYPE_MAP, generateSubgraphSQL } from \"./generator.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\ntype AnyDb = Kysely<Database>;\n\n/** Deep-clone an object, converting BigInts to strings for JSON serialization. */\nfunction toJsonSafe(obj: unknown): unknown {\n\treturn JSON.parse(\n\t\tJSON.stringify(obj, (_key, value) =>\n\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t),\n\t);\n}\n\nexport interface TableDiff {\n\t/** Tables added to the schema */\n\taddedTables: string[];\n\t/** Tables removed from the schema */\n\tremovedTables: string[];\n\t/** Per-table column diffs (only for tables present in both) */\n\ttables: Record<string, ColumnDiff>;\n}\n\nexport interface ColumnDiff {\n\tadded: string[];\n\tremoved: string[];\n\tchanged: string[];\n}\n\n/**\n * Compare two multi-table subgraph schemas and return differences.\n */\nexport function diffSchema(\n\texisting: SubgraphSchema,\n\tincoming: SubgraphSchema,\n): TableDiff {\n\tconst existingTables = new Set(Object.keys(existing));\n\tconst incomingTables = new Set(Object.keys(incoming));\n\n\tconst addedTables = [...incomingTables].filter((t) => !existingTables.has(t));\n\tconst removedTables = [...existingTables].filter(\n\t\t(t) => !incomingTables.has(t),\n\t);\n\n\tconst tables: Record<string, ColumnDiff> = {};\n\tfor (const tableName of incomingTables) {\n\t\tif (!existingTables.has(tableName)) continue;\n\t\tconst existingCols = existing[tableName]?.columns;\n\t\tconst incomingCols = incoming[tableName]?.columns;\n\n\t\tconst existingKeys = new Set(Object.keys(existingCols));\n\t\tconst incomingKeys = new Set(Object.keys(incomingCols));\n\n\t\ttables[tableName] = {\n\t\t\tadded: [...incomingKeys].filter((k) => !existingKeys.has(k)),\n\t\t\tremoved: [...existingKeys].filter((k) => !incomingKeys.has(k)),\n\t\t\tchanged: [...incomingKeys].filter((k) => {\n\t\t\t\tif (!existingKeys.has(k)) return false;\n\t\t\t\tconst sortedStringify = (o: unknown) =>\n\t\t\t\t\tJSON.stringify(o, Object.keys(o as object).sort());\n\t\t\t\treturn (\n\t\t\t\t\tsortedStringify(existingCols[k]) !== sortedStringify(incomingCols[k])\n\t\t\t\t);\n\t\t\t}),\n\t\t};\n\t}\n\n\treturn { addedTables, removedTables, tables };\n}\n\n/**\n * Returns true if the diff contains any breaking changes\n * (removed tables, removed columns, or changed column types).\n */\nfunction hasBreakingChanges(diff: TableDiff): {\n\tbreaking: boolean;\n\treasons: string[];\n} {\n\tconst reasons: string[] = [];\n\tif (diff.removedTables.length > 0) {\n\t\treasons.push(`removed tables: [${diff.removedTables.join(\", \")}]`);\n\t}\n\tfor (const [table, colDiff] of Object.entries(diff.tables)) {\n\t\tif (colDiff.removed.length > 0) {\n\t\t\treasons.push(`${table}: removed columns [${colDiff.removed.join(\", \")}]`);\n\t\t}\n\t\tif (colDiff.changed.length > 0) {\n\t\t\treasons.push(`${table}: changed columns [${colDiff.changed.join(\", \")}]`);\n\t\t}\n\t}\n\treturn { breaking: reasons.length > 0, reasons };\n}\n\n/** Increment the patch segment of a semver string. \"1.0.2\" → \"1.0.3\" */\nfunction bumpPatch(version: string): string {\n\tconst parts = version.split(\".\");\n\tif (parts.length !== 3) return \"1.0.1\";\n\tconst patch = Number.parseInt(parts[2] ?? \"0\", 10);\n\treturn `${parts[0]}.${parts[1]}.${Number.isNaN(patch) ? 1 : patch + 1}`;\n}\n\nexport interface DeployDiff {\n\taddedTables: string[];\n\tremovedTables: string[];\n\taddedColumns: Record<string, string[]>;\n\tbreakingChanges: string[];\n}\n\n/**\n * Deploy a subgraph schema to the database.\n * - New subgraph → CREATE SCHEMA + tables + register\n * - Same hash → no-op (handler path updated)\n * - Additive change → ALTER TABLE ADD COLUMN / CREATE TABLE for new tables\n * - Breaking change → auto-reindex (drop + recreate)\n */\nexport async function deploySchema(\n\tdb: AnyDb,\n\tdef: SubgraphDefinition,\n\thandlerPath: string,\n\topts?: {\n\t\tforceReindex?: boolean;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tversion?: string;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t},\n): Promise<{\n\taction: \"created\" | \"unchanged\" | \"handler_updated\" | \"updated\" | \"reindexed\";\n\tsubgraphId: string;\n\tversion: string;\n\tdiff?: DeployDiff;\n}> {\n\tvalidateSubgraphDefinition(def);\n\n\tconst { statements, hash } = generateSubgraphSQL(def, opts?.schemaName);\n\tconst { getSubgraph, registerSubgraph } = await import(\n\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t);\n\n\tconst existing = await getSubgraph(db, def.name, opts?.accountId);\n\n\tconst schemaName = opts?.schemaName ?? pgSchemaName(def.name);\n\n\t// Server owns versioning: use explicit flag, bump patch from existing, or start at 1.0.0\n\tconst newVersion =\n\t\topts?.version ?? (existing ? bumpPatch(existing.version) : \"1.0.0\");\n\n\tconst regData = {\n\t\tname: def.name,\n\t\tversion: newVersion,\n\t\tdefinition: toJsonSafe({\n\t\t\tname: def.name,\n\t\t\tversion: def.version,\n\t\t\tdescription: def.description,\n\t\t\tstartBlock: def.startBlock,\n\t\t\tsources: def.sources,\n\t\t\tschema: def.schema,\n\t\t}) as Record<string, unknown>,\n\t\tschemaHash: hash,\n\t\thandlerPath,\n\t\tapiKeyId: opts?.apiKeyId,\n\t\taccountId: opts?.accountId,\n\t\thandlerCode: opts?.handlerCode,\n\t\tsourceCode: opts?.sourceCode,\n\t\tschemaName,\n\t\tstartBlock: def.startBlock,\n\t};\n\n\tif (existing) {\n\t\t// Guard against zombie rows: registry entry exists but PG schema was dropped\n\t\t// (e.g. partial delete or manual cleanup). Treat as a new subgraph.\n\t\tconst schemaExists = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS (\n\t\t\t\tSELECT 1 FROM information_schema.schemata\n\t\t\t\tWHERE schema_name = ${schemaName}\n\t\t\t) AS \"exists\"\n\t\t`\n\t\t\t.execute(db)\n\t\t\t.then((r) => r.rows[0]?.exists ?? false);\n\n\t\tif (!schemaExists) {\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(db);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.schema_hash === hash && !opts?.forceReindex) {\n\t\t\t// Update handler path and code in case file moved or handler changed.\n\t\t\tconst handlerChanged =\n\t\t\t\topts?.handlerCode != null && opts.handlerCode !== existing.handler_code;\n\t\t\tconst { updateSubgraphHandlerPath } = await import(\n\t\t\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t\t\t);\n\t\t\tawait updateSubgraphHandlerPath(db, def.name, handlerPath, {\n\t\t\t\thandlerCode: opts?.handlerCode,\n\t\t\t\tsourceCode: opts?.sourceCode,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\taction: handlerChanged ? \"handler_updated\" : \"unchanged\",\n\t\t\t\tsubgraphId: existing.id,\n\t\t\t\tversion: existing.version,\n\t\t\t};\n\t\t}\n\n\t\tif (existing.schema_hash === hash && opts?.forceReindex) {\n\t\t\t// Same schema but force reindex requested — drop and recreate\n\t\t\tawait sql\n\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t.execute(db);\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(db);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.definition.schema) {\n\t\t\tconst diff = diffSchema(\n\t\t\t\texisting.definition.schema as SubgraphSchema,\n\t\t\t\tdef.schema,\n\t\t\t);\n\t\t\tconst { breaking, reasons } = hasBreakingChanges(diff);\n\n\t\t\tif (breaking || opts?.forceReindex) {\n\t\t\t\t// Breaking change or forced: drop schema, recreate, register\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t\t.execute(db);\n\t\t\t\tfor (const stmt of statements) {\n\t\t\t\t\tawait sql.raw(stmt).execute(db);\n\t\t\t\t}\n\t\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\t\tconst deployDiff: DeployDiff = {\n\t\t\t\t\taddedTables: diff.addedTables,\n\t\t\t\t\tremovedTables: diff.removedTables,\n\t\t\t\t\taddedColumns: Object.fromEntries(\n\t\t\t\t\t\tObject.entries(diff.tables)\n\t\t\t\t\t\t\t.filter(([, c]) => c.added.length > 0)\n\t\t\t\t\t\t\t.map(([t, c]) => [t, c.added]),\n\t\t\t\t\t),\n\t\t\t\t\tbreakingChanges: reasons,\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\taction: \"reindexed\",\n\t\t\t\t\tsubgraphId: sg.id,\n\t\t\t\t\tversion: newVersion,\n\t\t\t\t\tdiff: deployDiff,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Create new tables\n\t\t\tfor (const tableName of diff.addedTables) {\n\t\t\t\tconst tableDef = def.schema[tableName];\n\t\t\t\tif (!tableDef) continue;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tconst colDefs = [\n\t\t\t\t\t\"_id BIGSERIAL PRIMARY KEY\",\n\t\t\t\t\t\"_block_height BIGINT NOT NULL\",\n\t\t\t\t\t\"_tx_id TEXT NOT NULL\",\n\t\t\t\t\t\"_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\",\n\t\t\t\t];\n\t\t\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\t\t\tconst nullable = col.nullable ? \"\" : \" NOT NULL\";\n\t\t\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\t\t\tif (!sqlType) continue;\n\t\t\t\t\tcolDefs.push(`${colName} ${sqlType}${nullable}`);\n\t\t\t\t}\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${colDefs.join(\",\\n \")}\\n)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(db);\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(db);\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(db);\n\t\t\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\t\t\tif (col.indexed) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(db);\n\t\t\t\t\t}\n\t\t\t\t\tif (col.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(db);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add columns to existing tables\n\t\t\tfor (const [tableName, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif (colDiff.added.length === 0) continue;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tconst tableDef = def.schema[tableName];\n\t\t\t\tif (!tableDef) continue;\n\t\t\t\tfor (const colName of colDiff.added) {\n\t\t\t\t\tconst col = tableDef.columns[colName];\n\t\t\t\t\tif (!col) continue;\n\t\t\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\t\t\tif (!sqlType) continue;\n\t\t\t\t\tconst nullable = col.nullable\n\t\t\t\t\t\t? \"\"\n\t\t\t\t\t\t: ` NOT NULL DEFAULT ${getDefault(col.type)}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD COLUMN ${colName} ${sqlType}${nullable}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute(db);\n\t\t\t\t\tif (col.indexed) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(db);\n\t\t\t\t\t}\n\t\t\t\t\tif (col.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(db);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\tconst addedCols: Record<string, string[]> = {};\n\t\t\tfor (const [t, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif ((colDiff as ColumnDiff).added.length > 0)\n\t\t\t\t\taddedCols[t] = (colDiff as ColumnDiff).added;\n\t\t\t}\n\t\t\tconst deployDiff: DeployDiff = {\n\t\t\t\taddedTables: diff.addedTables,\n\t\t\t\tremovedTables: [],\n\t\t\t\taddedColumns: addedCols,\n\t\t\t\tbreakingChanges: [],\n\t\t\t};\n\t\t\treturn {\n\t\t\t\taction: \"updated\",\n\t\t\t\tsubgraphId: sg.id,\n\t\t\t\tversion: newVersion,\n\t\t\t\tdiff: deployDiff,\n\t\t\t};\n\t\t}\n\t}\n\n\t// New subgraph — execute all DDL\n\tfor (const stmt of statements) {\n\t\tawait sql.raw(stmt).execute(db);\n\t}\n\n\tconst sg = await registerSubgraph(db, regData);\n\treturn { action: \"created\", subgraphId: sg.id, version: newVersion };\n}\n\nfunction getDefault(type: string): string {\n\tswitch (type) {\n\t\tcase \"text\":\n\t\tcase \"principal\":\n\t\t\treturn \"''\";\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\t\treturn \"0\";\n\t\tcase \"boolean\":\n\t\t\treturn \"false\";\n\t\tcase \"timestamp\":\n\t\t\treturn \"NOW()\";\n\t\tcase \"jsonb\":\n\t\t\treturn \"'{}'\";\n\t\tdefault:\n\t\t\treturn \"''\";\n\t}\n}\n"
8
+ "import type { Database } from \"@secondlayer/shared/db\";\nimport { type Kysely, sql } from \"kysely\";\nimport type { SubgraphDefinition, SubgraphSchema } from \"../types.ts\";\nimport { validateSubgraphDefinition } from \"../validate.ts\";\nimport { TYPE_MAP, generateSubgraphSQL } from \"./generator.ts\";\nimport { pgSchemaName } from \"./utils.ts\";\n\ntype AnyDb = Kysely<Database>;\n\n/** Deep-clone an object, converting BigInts to strings for JSON serialization. */\nfunction toJsonSafe(obj: unknown): unknown {\n\treturn JSON.parse(\n\t\tJSON.stringify(obj, (_key, value) =>\n\t\t\ttypeof value === \"bigint\" ? value.toString() : value,\n\t\t),\n\t);\n}\n\nexport interface TableDiff {\n\t/** Tables added to the schema */\n\taddedTables: string[];\n\t/** Tables removed from the schema */\n\tremovedTables: string[];\n\t/** Per-table column diffs (only for tables present in both) */\n\ttables: Record<string, ColumnDiff>;\n}\n\nexport interface ColumnDiff {\n\tadded: string[];\n\tremoved: string[];\n\tchanged: string[];\n}\n\n/**\n * Compare two multi-table subgraph schemas and return differences.\n */\nexport function diffSchema(\n\texisting: SubgraphSchema,\n\tincoming: SubgraphSchema,\n): TableDiff {\n\tconst existingTables = new Set(Object.keys(existing));\n\tconst incomingTables = new Set(Object.keys(incoming));\n\n\tconst addedTables = [...incomingTables].filter((t) => !existingTables.has(t));\n\tconst removedTables = [...existingTables].filter(\n\t\t(t) => !incomingTables.has(t),\n\t);\n\n\tconst tables: Record<string, ColumnDiff> = {};\n\tfor (const tableName of incomingTables) {\n\t\tif (!existingTables.has(tableName)) continue;\n\t\tconst existingCols = existing[tableName]?.columns;\n\t\tconst incomingCols = incoming[tableName]?.columns;\n\n\t\tconst existingKeys = new Set(Object.keys(existingCols));\n\t\tconst incomingKeys = new Set(Object.keys(incomingCols));\n\n\t\ttables[tableName] = {\n\t\t\tadded: [...incomingKeys].filter((k) => !existingKeys.has(k)),\n\t\t\tremoved: [...existingKeys].filter((k) => !incomingKeys.has(k)),\n\t\t\tchanged: [...incomingKeys].filter((k) => {\n\t\t\t\tif (!existingKeys.has(k)) return false;\n\t\t\t\tconst sortedStringify = (o: unknown) =>\n\t\t\t\t\tJSON.stringify(o, Object.keys(o as object).sort());\n\t\t\t\treturn (\n\t\t\t\t\tsortedStringify(existingCols[k]) !== sortedStringify(incomingCols[k])\n\t\t\t\t);\n\t\t\t}),\n\t\t};\n\t}\n\n\treturn { addedTables, removedTables, tables };\n}\n\n/**\n * Returns true if the diff contains any breaking changes\n * (removed tables, removed columns, or changed column types).\n */\nfunction hasBreakingChanges(diff: TableDiff): {\n\tbreaking: boolean;\n\treasons: string[];\n} {\n\tconst reasons: string[] = [];\n\tif (diff.removedTables.length > 0) {\n\t\treasons.push(`removed tables: [${diff.removedTables.join(\", \")}]`);\n\t}\n\tfor (const [table, colDiff] of Object.entries(diff.tables)) {\n\t\tif (colDiff.removed.length > 0) {\n\t\t\treasons.push(`${table}: removed columns [${colDiff.removed.join(\", \")}]`);\n\t\t}\n\t\tif (colDiff.changed.length > 0) {\n\t\t\treasons.push(`${table}: changed columns [${colDiff.changed.join(\", \")}]`);\n\t\t}\n\t}\n\treturn { breaking: reasons.length > 0, reasons };\n}\n\n/** Increment the patch segment of a semver string. \"1.0.2\" → \"1.0.3\" */\nfunction bumpPatch(version: string): string {\n\tconst parts = version.split(\".\");\n\tif (parts.length !== 3) return \"1.0.1\";\n\tconst patch = Number.parseInt(parts[2] ?? \"0\", 10);\n\treturn `${parts[0]}.${parts[1]}.${Number.isNaN(patch) ? 1 : patch + 1}`;\n}\n\nexport interface DeployDiff {\n\taddedTables: string[];\n\tremovedTables: string[];\n\taddedColumns: Record<string, string[]>;\n\tbreakingChanges: string[];\n}\n\nexport interface DeployPlan {\n\tschemaName: string;\n\t/** DDL Secondlayer will run against your database. */\n\tstatements: string[];\n\t/** Least-privilege grant script to run once, before deploying. */\n\tgrantScript: string;\n}\n\n/**\n * Render the DDL + grant script a BYO deploy would run, without executing.\n * Powers `--dry-run`: the user reviews exactly what touches their DB first.\n */\nexport function renderDeployPlan(\n\tdef: SubgraphDefinition,\n\tschemaName?: string,\n): DeployPlan {\n\tvalidateSubgraphDefinition(def);\n\tconst { statements } = generateSubgraphSQL(def, schemaName);\n\tconst schema = schemaName ?? pgSchemaName(def.name);\n\tconst grantScript = [\n\t\t\"-- Run once on YOUR database as an owner/superuser, replacing <role>\",\n\t\t\"-- with the role whose credentials you give Secondlayer.\",\n\t\t\"-- Secondlayer then creates and owns only this one schema:\",\n\t\t`GRANT CREATE ON DATABASE current_database() TO <role>;`,\n\t\t`-- (after first deploy <role> owns \"${schema}\"; no further grants needed)`,\n\t].join(\"\\n\");\n\treturn { schemaName: schema, statements, grantScript };\n}\n\n/**\n * Deploy a subgraph schema to the database.\n * - New subgraph → CREATE SCHEMA + tables + register\n * - Same hash → no-op (handler path updated)\n * - Additive change → ALTER TABLE ADD COLUMN / CREATE TABLE for new tables\n * - Breaking change → auto-reindex (drop + recreate)\n */\nexport async function deploySchema(\n\tdb: AnyDb,\n\tdef: SubgraphDefinition,\n\thandlerPath: string,\n\topts?: {\n\t\tforceReindex?: boolean;\n\t\tapiKeyId?: string;\n\t\taccountId?: string;\n\t\tschemaName?: string;\n\t\tversion?: string;\n\t\thandlerCode?: string;\n\t\tsourceCode?: string;\n\t\t/**\n\t\t * BYO data plane: when set, schema DDL (CREATE/ALTER/index) runs against\n\t\t * the user-owned DB while the subgraphs registry row stays on `db`\n\t\t * (managed). Defaults to `db` — managed deploys are unchanged.\n\t\t */\n\t\tdataDb?: AnyDb;\n\t\t/** Encrypted user-DB connection string to persist on the registry row. */\n\t\tdatabaseUrlEnc?: Buffer | null;\n\t},\n): Promise<{\n\taction: \"created\" | \"unchanged\" | \"handler_updated\" | \"updated\" | \"reindexed\";\n\tsubgraphId: string;\n\tversion: string;\n\tdiff?: DeployDiff;\n}> {\n\tvalidateSubgraphDefinition(def);\n\n\tconst { statements, hash } = generateSubgraphSQL(def, opts?.schemaName);\n\tconst { getSubgraph, registerSubgraph } = await import(\n\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t);\n\n\t// DDL target: the user's DB for BYO, else the managed DB. The registry\n\t// (getSubgraph/registerSubgraph) always stays on `db`.\n\tconst ddlDb = opts?.dataDb ?? db;\n\tconst byo = opts?.dataDb != null;\n\tconst refuseDestructiveOnByo = (reason: string): never => {\n\t\tthrow new Error(\n\t\t\t`Breaking schema change on a BYO subgraph (${reason}) would drop data ` +\n\t\t\t\t`in your database. Drop the schema \"${opts?.schemaName ?? pgSchemaName(def.name)}\" ` +\n\t\t\t\t`manually and re-deploy to rebuild.`,\n\t\t);\n\t};\n\n\tconst existing = await getSubgraph(db, def.name, opts?.accountId);\n\n\tconst schemaName = opts?.schemaName ?? pgSchemaName(def.name);\n\n\t// Server owns versioning: use explicit flag, bump patch from existing, or start at 1.0.0\n\tconst newVersion =\n\t\topts?.version ?? (existing ? bumpPatch(existing.version) : \"1.0.0\");\n\n\tconst regData = {\n\t\tname: def.name,\n\t\tversion: newVersion,\n\t\tdefinition: toJsonSafe({\n\t\t\tname: def.name,\n\t\t\tversion: def.version,\n\t\t\tdescription: def.description,\n\t\t\tstartBlock: def.startBlock,\n\t\t\tsources: def.sources,\n\t\t\tschema: def.schema,\n\t\t}) as Record<string, unknown>,\n\t\tschemaHash: hash,\n\t\thandlerPath,\n\t\tapiKeyId: opts?.apiKeyId,\n\t\taccountId: opts?.accountId,\n\t\thandlerCode: opts?.handlerCode,\n\t\tsourceCode: opts?.sourceCode,\n\t\tschemaName,\n\t\tstartBlock: def.startBlock,\n\t\tdatabaseUrlEnc: opts?.databaseUrlEnc ?? null,\n\t};\n\n\tif (existing) {\n\t\t// Guard against zombie rows: registry entry exists but PG schema was dropped\n\t\t// (e.g. partial delete or manual cleanup). Treat as a new subgraph. The\n\t\t// schema lives on the data-plane DB (user DB for BYO), so check there.\n\t\tconst schemaExists = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS (\n\t\t\t\tSELECT 1 FROM information_schema.schemata\n\t\t\t\tWHERE schema_name = ${schemaName}\n\t\t\t) AS \"exists\"\n\t\t`\n\t\t\t.execute(ddlDb)\n\t\t\t.then((r) => r.rows[0]?.exists ?? false);\n\n\t\tif (!schemaExists) {\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.schema_hash === hash && !opts?.forceReindex) {\n\t\t\t// Update handler path and code in case file moved or handler changed.\n\t\t\tconst handlerChanged =\n\t\t\t\topts?.handlerCode != null && opts.handlerCode !== existing.handler_code;\n\t\t\tconst { updateSubgraphHandlerPath } = await import(\n\t\t\t\t\"@secondlayer/shared/db/queries/subgraphs\"\n\t\t\t);\n\t\t\tawait updateSubgraphHandlerPath(db, def.name, handlerPath, {\n\t\t\t\thandlerCode: opts?.handlerCode,\n\t\t\t\tsourceCode: opts?.sourceCode,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\taction: handlerChanged ? \"handler_updated\" : \"unchanged\",\n\t\t\t\tsubgraphId: existing.id,\n\t\t\t\tversion: existing.version,\n\t\t\t};\n\t\t}\n\n\t\tif (existing.schema_hash === hash && opts?.forceReindex) {\n\t\t\t// Same schema but force reindex requested — drop and recreate.\n\t\t\tif (byo) refuseDestructiveOnByo(\"force reindex\");\n\t\t\tawait sql\n\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t.execute(ddlDb);\n\t\t\tfor (const stmt of statements) {\n\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t}\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\treturn { action: \"reindexed\", subgraphId: sg.id, version: newVersion };\n\t\t}\n\n\t\tif (existing.definition.schema) {\n\t\t\tconst diff = diffSchema(\n\t\t\t\texisting.definition.schema as SubgraphSchema,\n\t\t\t\tdef.schema,\n\t\t\t);\n\t\t\tconst { breaking, reasons } = hasBreakingChanges(diff);\n\n\t\t\tif (breaking || opts?.forceReindex) {\n\t\t\t\t// Breaking change or forced: drop schema, recreate, register\n\t\t\t\tif (byo) {\n\t\t\t\t\trefuseDestructiveOnByo(\n\t\t\t\t\t\treasons.length > 0 ? reasons.join(\"; \") : \"force reindex\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(`DROP SCHEMA IF EXISTS \"${schemaName}\" CASCADE`)\n\t\t\t\t\t.execute(ddlDb);\n\t\t\t\tfor (const stmt of statements) {\n\t\t\t\t\tawait sql.raw(stmt).execute(ddlDb);\n\t\t\t\t}\n\t\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\t\tconst deployDiff: DeployDiff = {\n\t\t\t\t\taddedTables: diff.addedTables,\n\t\t\t\t\tremovedTables: diff.removedTables,\n\t\t\t\t\taddedColumns: Object.fromEntries(\n\t\t\t\t\t\tObject.entries(diff.tables)\n\t\t\t\t\t\t\t.filter(([, c]) => c.added.length > 0)\n\t\t\t\t\t\t\t.map(([t, c]) => [t, c.added]),\n\t\t\t\t\t),\n\t\t\t\t\tbreakingChanges: reasons,\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\taction: \"reindexed\",\n\t\t\t\t\tsubgraphId: sg.id,\n\t\t\t\t\tversion: newVersion,\n\t\t\t\t\tdiff: deployDiff,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Create new tables\n\t\t\tfor (const tableName of diff.addedTables) {\n\t\t\t\tconst tableDef = def.schema[tableName];\n\t\t\t\tif (!tableDef) continue;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tconst colDefs = [\n\t\t\t\t\t\"_id BIGSERIAL PRIMARY KEY\",\n\t\t\t\t\t\"_block_height BIGINT NOT NULL\",\n\t\t\t\t\t\"_tx_id TEXT NOT NULL\",\n\t\t\t\t\t\"_created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\",\n\t\t\t\t];\n\t\t\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\t\t\tconst nullable = col.nullable ? \"\" : \" NOT NULL\";\n\t\t\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\t\t\tif (!sqlType) continue;\n\t\t\t\t\tcolDefs.push(`${colName} ${sqlType}${nullable}`);\n\t\t\t\t}\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedName} (\\n ${colDefs.join(\",\\n \")}\\n)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(ddlDb);\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_block_height ON ${qualifiedName} (_block_height)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(ddlDb);\n\t\t\t\tawait sql\n\t\t\t\t\t.raw(\n\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_tx_id ON ${qualifiedName} (_tx_id)`,\n\t\t\t\t\t)\n\t\t\t\t\t.execute(ddlDb);\n\t\t\t\tfor (const [colName, col] of Object.entries(tableDef.columns)) {\n\t\t\t\t\tif (col.indexed) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t\tif (col.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add columns to existing tables\n\t\t\tfor (const [tableName, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif (colDiff.added.length === 0) continue;\n\t\t\t\tconst qualifiedName = `${schemaName}.${tableName}`;\n\t\t\t\tconst tableDef = def.schema[tableName];\n\t\t\t\tif (!tableDef) continue;\n\t\t\t\tfor (const colName of colDiff.added) {\n\t\t\t\t\tconst col = tableDef.columns[colName];\n\t\t\t\t\tif (!col) continue;\n\t\t\t\t\tconst sqlType = TYPE_MAP[col.type];\n\t\t\t\t\tif (!sqlType) continue;\n\t\t\t\t\tconst nullable = col.nullable\n\t\t\t\t\t\t? \"\"\n\t\t\t\t\t\t: ` NOT NULL DEFAULT ${getDefault(col.type)}`;\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t`ALTER TABLE ${qualifiedName} ADD COLUMN ${colName} ${sqlType}${nullable}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\tif (col.indexed) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName} ON ${qualifiedName} (${colName})`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t\tif (col.search) {\n\t\t\t\t\t\tawait sql\n\t\t\t\t\t\t\t.raw(\n\t\t\t\t\t\t\t\t`CREATE INDEX IF NOT EXISTS idx_${schemaName}_${tableName}_${colName}_trgm ON ${qualifiedName} USING gin (${colName} gin_trgm_ops)`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.execute(ddlDb);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst sg = await registerSubgraph(db, regData);\n\t\t\tconst addedCols: Record<string, string[]> = {};\n\t\t\tfor (const [t, colDiff] of Object.entries(diff.tables)) {\n\t\t\t\tif ((colDiff as ColumnDiff).added.length > 0)\n\t\t\t\t\taddedCols[t] = (colDiff as ColumnDiff).added;\n\t\t\t}\n\t\t\tconst deployDiff: DeployDiff = {\n\t\t\t\taddedTables: diff.addedTables,\n\t\t\t\tremovedTables: [],\n\t\t\t\taddedColumns: addedCols,\n\t\t\t\tbreakingChanges: [],\n\t\t\t};\n\t\t\treturn {\n\t\t\t\taction: \"updated\",\n\t\t\t\tsubgraphId: sg.id,\n\t\t\t\tversion: newVersion,\n\t\t\t\tdiff: deployDiff,\n\t\t\t};\n\t\t}\n\t}\n\n\t// New subgraph — execute all DDL\n\tfor (const stmt of statements) {\n\t\tawait sql.raw(stmt).execute(ddlDb);\n\t}\n\n\tconst sg = await registerSubgraph(db, regData);\n\treturn { action: \"created\", subgraphId: sg.id, version: newVersion };\n}\n\nfunction getDefault(type: string): string {\n\tswitch (type) {\n\t\tcase \"text\":\n\t\tcase \"principal\":\n\t\t\treturn \"''\";\n\t\tcase \"uint\":\n\t\tcase \"int\":\n\t\t\treturn \"0\";\n\t\tcase \"boolean\":\n\t\t\treturn \"false\";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AI,OAAO;AAAA,EAC7C,OAAO,EAAE,QAAQ,WAAW,YAAY,GAAG,IAAI,SAAS,WAAW;AAAA;AAGpE,SAAS,UAAU,CAAC,MAAsB;AAAA,EACzC,QAAQ;AAAA,SACF;AAAA,SACA;AAAA,MACJ,OAAO;AAAA,SACH;AAAA,SACA;AAAA,MACJ,OAAO;AAAA,SACH;AAAA,MACJ,OAAO;AAAA,SACH;AAAA,MACJ,OAAO;AAAA,SACH;AAAA,MACJ,OAAO;AAAA;AAAA,MAEP,OAAO;AAAA;AAAA;",
11
+ "debugId": "6726D9DC9065FAAD64756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -18,12 +18,14 @@ class SubgraphContext {
18
18
  pgSchemaName;
19
19
  subgraphSchema;
20
20
  ops = [];
21
- constructor(db, pgSchemaName, subgraphSchema, block, tx) {
21
+ byo;
22
+ constructor(db, pgSchemaName, subgraphSchema, block, tx, byo = false) {
22
23
  this.db = db;
23
24
  this.pgSchemaName = pgSchemaName;
24
25
  this.subgraphSchema = subgraphSchema;
25
26
  this.block = block;
26
27
  this._tx = tx;
28
+ this.byo = byo;
27
29
  }
28
30
  get tx() {
29
31
  return this._tx;
@@ -218,6 +220,15 @@ class SubgraphContext {
218
220
  }
219
221
  buildStatements(ops) {
220
222
  const statements = [];
223
+ if (this.byo) {
224
+ const insertTables = new Set;
225
+ for (const op of ops)
226
+ if (op.kind === "insert")
227
+ insertTables.add(op.table);
228
+ for (const table of insertTables) {
229
+ statements.push(`DELETE FROM "${this.pgSchemaName}"."${table}" WHERE "_block_height" = ${this.block.height}`);
230
+ }
231
+ }
221
232
  let currentBatch = null;
222
233
  let currentBatchKey = "";
223
234
  const flushInsertBatch = () => {
@@ -711,7 +722,19 @@ function matchPattern(value, pattern) {
711
722
  }
712
723
  return re.test(value);
713
724
  }
714
- function matchFilter(filter, transactions, eventsByTx) {
725
+ var EMPTY_SET = new Set;
726
+ function traitAllows(filter, contractId, traitContracts) {
727
+ const trait = filter.trait;
728
+ if (!trait)
729
+ return true;
730
+ if (!contractId)
731
+ return false;
732
+ return (traitContracts.get(trait) ?? EMPTY_SET).has(contractId);
733
+ }
734
+ function assetContract(assetId) {
735
+ return assetId?.split("::")[0];
736
+ }
737
+ function matchFilter(filter, transactions, eventsByTx, traitContracts) {
715
738
  const results = [];
716
739
  switch (filter.type) {
717
740
  case "stx_transfer":
@@ -775,6 +798,8 @@ function matchFilter(filter, transactions, eventsByTx) {
775
798
  if (!assetId || !matchPattern(assetId, filter.assetIdentifier))
776
799
  return false;
777
800
  }
801
+ if (!traitAllows(filter, assetContract(data.asset_identifier), traitContracts))
802
+ return false;
778
803
  if ("sender" in filter && filter.sender) {
779
804
  if (!matchPattern(data.sender, filter.sender))
780
805
  return false;
@@ -813,6 +838,8 @@ function matchFilter(filter, transactions, eventsByTx) {
813
838
  if (!assetId || !matchPattern(assetId, filter.assetIdentifier))
814
839
  return false;
815
840
  }
841
+ if (!traitAllows(filter, assetContract(data.asset_identifier), traitContracts))
842
+ return false;
816
843
  if ("sender" in filter && filter.sender) {
817
844
  if (!matchPattern(data.sender, filter.sender))
818
845
  return false;
@@ -845,6 +872,8 @@ function matchFilter(filter, transactions, eventsByTx) {
845
872
  if (!matchPattern(tx.sender, filter.caller))
846
873
  continue;
847
874
  }
875
+ if (!traitAllows(filter, tx.contract_id, traitContracts))
876
+ continue;
848
877
  const txEvents = eventsByTx.get(tx.tx_id) ?? [];
849
878
  results.push({ tx, events: txEvents });
850
879
  }
@@ -879,11 +908,13 @@ function matchFilter(filter, transactions, eventsByTx) {
879
908
  return false;
880
909
  if (data.topic !== "print")
881
910
  return false;
911
+ const printContractId = data.contract_identifier ?? data.contract_id;
882
912
  if (filter.contractId) {
883
- const contractId = data.contract_identifier ?? data.contract_id;
884
- if (!contractId || !matchPattern(contractId, filter.contractId))
913
+ if (!printContractId || !matchPattern(printContractId, filter.contractId))
885
914
  return false;
886
915
  }
916
+ if (!traitAllows(filter, printContractId, traitContracts))
917
+ return false;
887
918
  return true;
888
919
  });
889
920
  if (matched.length > 0) {
@@ -895,7 +926,7 @@ function matchFilter(filter, transactions, eventsByTx) {
895
926
  }
896
927
  return results;
897
928
  }
898
- function matchSources(sources, transactions, events) {
929
+ function matchSources(sources, transactions, events, traitContracts = new Map) {
899
930
  const eventsByTx = new Map;
900
931
  for (const event of events) {
901
932
  const list = eventsByTx.get(event.tx_id) ?? [];
@@ -905,7 +936,7 @@ function matchSources(sources, transactions, events) {
905
936
  const seen = new Set;
906
937
  const results = [];
907
938
  for (const [sourceName, filter] of Object.entries(sources)) {
908
- const matches = matchFilter(filter, transactions, eventsByTx);
939
+ const matches = matchFilter(filter, transactions, eventsByTx, traitContracts);
909
940
  for (const match of matches) {
910
941
  const dedupeKey = `${match.tx.tx_id}:${sourceName}`;
911
942
  if (!seen.has(dedupeKey)) {
@@ -922,8 +953,11 @@ import {
922
953
  getSourceDb,
923
954
  getTargetDb
924
955
  } from "@secondlayer/shared/db";
956
+ import { resolveTraitContractIds } from "@secondlayer/shared/db/queries/contracts";
925
957
  import {
958
+ isByoSubgraph,
926
959
  recordSubgraphProcessed,
960
+ resolveSubgraphDb,
927
961
  updateSubgraphStatus
928
962
  } from "@secondlayer/shared/db/queries/subgraphs";
929
963
  import { logger as logger4 } from "@secondlayer/shared/logger";
@@ -1161,7 +1195,38 @@ async function refreshMatcher(db) {
1161
1195
  }
1162
1196
 
1163
1197
  // src/runtime/block-processor.ts
1164
- var schemaNameCache = new Map;
1198
+ var routeCache = new Map;
1199
+ async function resolveRoute(subgraphName, targetDb) {
1200
+ const cached = routeCache.get(subgraphName);
1201
+ if (cached)
1202
+ return cached;
1203
+ const row = await targetDb.selectFrom("subgraphs").selectAll().where("name", "=", subgraphName).executeTakeFirst();
1204
+ const byo = row ? isByoSubgraph(row) : false;
1205
+ const route = {
1206
+ schemaName: row?.schema_name ?? pgSchemaName(subgraphName),
1207
+ dataDb: row && byo ? resolveSubgraphDb(row) : targetDb,
1208
+ byo
1209
+ };
1210
+ routeCache.set(subgraphName, route);
1211
+ return route;
1212
+ }
1213
+ function invalidateSubgraphRoute(subgraphName) {
1214
+ routeCache.delete(subgraphName);
1215
+ }
1216
+ async function resolveTraitContracts(subgraph, blockHeight, db) {
1217
+ const traits = new Set;
1218
+ for (const source of Object.values(subgraph.sources)) {
1219
+ const trait = source.trait;
1220
+ if (trait)
1221
+ traits.add(trait);
1222
+ }
1223
+ const resolved = new Map;
1224
+ for (const trait of traits) {
1225
+ const ids = await resolveTraitContractIds(db, trait, blockHeight);
1226
+ resolved.set(trait, new Set(ids));
1227
+ }
1228
+ return resolved;
1229
+ }
1165
1230
  async function processBlock(subgraph, subgraphName, blockHeight, opts) {
1166
1231
  const sourceDb = getSourceDb();
1167
1232
  const targetDb = getTargetDb();
@@ -1201,7 +1266,8 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
1201
1266
  txs = await sourceDb.selectFrom("transactions").selectAll().where("block_height", "=", blockHeight).execute();
1202
1267
  evts = await sourceDb.selectFrom("events").selectAll().where("block_height", "=", blockHeight).execute();
1203
1268
  }
1204
- const matched = matchSources(subgraph.sources, txs, evts);
1269
+ const traitContracts = await resolveTraitContracts(subgraph, blockHeight, targetDb);
1270
+ const matched = matchSources(subgraph.sources, txs, evts, traitContracts);
1205
1271
  result.matched = matched.length;
1206
1272
  if (matched.length === 0) {
1207
1273
  if (!opts?.skipProgressUpdate) {
@@ -1209,12 +1275,8 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
1209
1275
  }
1210
1276
  return result;
1211
1277
  }
1212
- let schemaName = schemaNameCache.get(subgraphName);
1213
- if (!schemaName) {
1214
- const subgraphRecord = await targetDb.selectFrom("subgraphs").select("schema_name").where("name", "=", subgraphName).executeTakeFirst();
1215
- schemaName = subgraphRecord?.schema_name ?? pgSchemaName(subgraphName);
1216
- schemaNameCache.set(subgraphName, schemaName);
1217
- }
1278
+ const route = await resolveRoute(subgraphName, targetDb);
1279
+ const schemaName = route.schemaName;
1218
1280
  const blockMeta = {
1219
1281
  height: block.height,
1220
1282
  hash: block.hash,
@@ -1229,30 +1291,57 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
1229
1291
  };
1230
1292
  let handlerMs = 0;
1231
1293
  let flushMs = 0;
1232
- await targetDb.transaction().execute(async (tx) => {
1233
- const ctx = new SubgraphContext(tx, schemaName, subgraph.schema, blockMeta, initialTx);
1234
- const handlerStart = performance.now();
1235
- const runResult = await runHandlers(subgraph, matched, ctx);
1236
- handlerMs = performance.now() - handlerStart;
1294
+ const applyProgress = async (tx, rr) => {
1295
+ if (opts?.skipProgressUpdate)
1296
+ return;
1297
+ const status = rr.errors > 0 && rr.processed === 0 ? "error" : "active";
1298
+ await updateSubgraphStatus(tx, subgraphName, status, blockHeight);
1299
+ if (rr.processed > 0 || rr.errors > 0) {
1300
+ const lastError = rr.errors > 0 ? `${rr.errors} error(s) at block ${blockHeight}` : undefined;
1301
+ await recordSubgraphProcessed(tx, subgraphName, rr.processed, rr.errors, lastError);
1302
+ }
1303
+ };
1304
+ if (route.byo) {
1305
+ let runResult = { processed: 0, errors: 0 };
1306
+ let manifest;
1307
+ await route.dataDb.transaction().execute(async (tx) => {
1308
+ const ctx = new SubgraphContext(tx, schemaName, subgraph.schema, blockMeta, initialTx, true);
1309
+ const handlerStart = performance.now();
1310
+ runResult = await runHandlers(subgraph, matched, ctx);
1311
+ handlerMs = performance.now() - handlerStart;
1312
+ if (ctx.pendingOps > 0) {
1313
+ const flushStart = performance.now();
1314
+ manifest = await ctx.flush();
1315
+ flushMs = performance.now() - flushStart;
1316
+ }
1317
+ });
1237
1318
  result.processed = runResult.processed;
1238
1319
  result.errors = runResult.errors;
1239
- if (ctx.pendingOps > 0) {
1240
- const flushStart = performance.now();
1241
- const manifest = await ctx.flush();
1242
- if (manifest.count > 0) {
1320
+ await targetDb.transaction().execute(async (tx) => {
1321
+ if (manifest && manifest.count > 0) {
1243
1322
  await emitSubscriptionOutbox(tx, subgraphName, manifest, matcher, block.height);
1244
1323
  }
1245
- flushMs = performance.now() - flushStart;
1246
- }
1247
- if (!opts?.skipProgressUpdate) {
1248
- const status = runResult.errors > 0 && runResult.processed === 0 ? "error" : "active";
1249
- await updateSubgraphStatus(tx, subgraphName, status, blockHeight);
1250
- }
1251
- if (!opts?.skipProgressUpdate && (runResult.processed > 0 || runResult.errors > 0)) {
1252
- const lastError = runResult.errors > 0 ? `${runResult.errors} error(s) at block ${blockHeight}` : undefined;
1253
- await recordSubgraphProcessed(tx, subgraphName, runResult.processed, runResult.errors, lastError);
1254
- }
1255
- });
1324
+ await applyProgress(tx, runResult);
1325
+ });
1326
+ } else {
1327
+ await targetDb.transaction().execute(async (tx) => {
1328
+ const ctx = new SubgraphContext(tx, schemaName, subgraph.schema, blockMeta, initialTx);
1329
+ const handlerStart = performance.now();
1330
+ const runResult = await runHandlers(subgraph, matched, ctx);
1331
+ handlerMs = performance.now() - handlerStart;
1332
+ result.processed = runResult.processed;
1333
+ result.errors = runResult.errors;
1334
+ if (ctx.pendingOps > 0) {
1335
+ const flushStart = performance.now();
1336
+ const manifest = await ctx.flush();
1337
+ if (manifest.count > 0) {
1338
+ await emitSubscriptionOutbox(tx, subgraphName, manifest, matcher, block.height);
1339
+ }
1340
+ flushMs = performance.now() - flushStart;
1341
+ }
1342
+ await applyProgress(tx, runResult);
1343
+ });
1344
+ }
1256
1345
  const totalMs = performance.now() - blockStart;
1257
1346
  result.timing = {
1258
1347
  totalMs: Math.round(totalMs),
@@ -1263,7 +1352,7 @@ async function processBlock(subgraph, subgraphName, blockHeight, opts) {
1263
1352
  try {
1264
1353
  const tables = Object.keys(subgraph.schema);
1265
1354
  for (const table of tables) {
1266
- const { rows } = await sql3.raw(`SELECT n_live_tup AS count FROM pg_stat_user_tables WHERE schemaname = '${schemaName}' AND relname = '${table}'`).execute(targetDb);
1355
+ const { rows } = await sql3.raw(`SELECT n_live_tup AS count FROM pg_stat_user_tables WHERE schemaname = '${schemaName}' AND relname = '${table}'`).execute(route.dataDb);
1267
1356
  const count = Number(rows[0]?.count ?? 0);
1268
1357
  if (count >= 1e7) {
1269
1358
  logger4.warn("Subgraph table exceeds 10M rows (estimate)", {
@@ -1435,6 +1524,12 @@ function generateSubgraphSQL(def, schemaNameOverride) {
1435
1524
  }
1436
1525
  }
1437
1526
  }
1527
+ for (const [tableName, tableDef] of Object.entries(def.schema)) {
1528
+ for (const rel of tableDef.relations ?? []) {
1529
+ const constraintName = `fk_${schemaName}_${tableName}_${rel.name}`;
1530
+ statements.push(`ALTER TABLE ${schemaName}.${tableName} ADD CONSTRAINT ${constraintName} ` + `FOREIGN KEY (${rel.fields.join(", ")}) ` + `REFERENCES ${schemaName}.${rel.references} (${rel.referencedColumns.join(", ")})`);
1531
+ }
1532
+ }
1438
1533
  const hashInput = JSON.stringify({
1439
1534
  name: def.name,
1440
1535
  schema: def.schema,
@@ -2093,12 +2188,14 @@ async function catchUpSubgraph(subgraph, subgraphName) {
2093
2188
 
2094
2189
  // src/runtime/reorg.ts
2095
2190
  import { getErrorMessage as getErrorMessage3 } from "@secondlayer/shared";
2096
- import { getRawClient as getRawClient2, getTargetDb as getTargetDb4 } from "@secondlayer/shared/db";
2097
- import { listSubgraphs } from "@secondlayer/shared/db/queries/subgraphs";
2191
+ import { getTargetDb as getTargetDb4 } from "@secondlayer/shared/db";
2192
+ import {
2193
+ listSubgraphs,
2194
+ resolveSubgraphRawClient
2195
+ } from "@secondlayer/shared/db/queries/subgraphs";
2098
2196
  import { logger as logger7 } from "@secondlayer/shared/logger";
2099
2197
  async function handleSubgraphReorg(blockHeight, loadSubgraphDef) {
2100
2198
  const targetDb = getTargetDb4();
2101
- const client = getRawClient2("target");
2102
2199
  const activeSubgraphs = (await listSubgraphs(targetDb)).filter((v) => v.status === "active");
2103
2200
  if (activeSubgraphs.length === 0)
2104
2201
  return;
@@ -2112,6 +2209,7 @@ async function handleSubgraphReorg(blockHeight, loadSubgraphDef) {
2112
2209
  if (!schema)
2113
2210
  continue;
2114
2211
  const schemaName = sg.schema_name ?? pgSchemaName(sg.name);
2212
+ const client = resolveSubgraphRawClient(sg);
2115
2213
  const tableNames = Object.keys(schema);
2116
2214
  const revertedByTable = {};
2117
2215
  for (const tableName of tableNames) {
@@ -2197,6 +2295,7 @@ import {
2197
2295
  isActiveSubgraphOperationConflict
2198
2296
  } from "@secondlayer/shared/db/queries/subgraph-operations";
2199
2297
  import {
2298
+ isByoSubgraph as isByoSubgraph2,
2200
2299
  listSubgraphs as listSubgraphs2,
2201
2300
  pgSchemaName as pgSchemaName2,
2202
2301
  updateSubgraphStatus as updateSubgraphStatus3
@@ -2794,6 +2893,7 @@ async function loadSubgraphDefinition(sg) {
2794
2893
  knownVersions.set(sg.name, sg.version);
2795
2894
  definitionCache.set(sg.name, def);
2796
2895
  if (prevVersion && prevVersion !== sg.version) {
2896
+ invalidateSubgraphRoute(sg.name);
2797
2897
  logger10.info("Subgraph handler reloaded", {
2798
2898
  subgraph: sg.name,
2799
2899
  from: prevVersion,
@@ -2808,6 +2908,7 @@ function cleanupCaches(active) {
2808
2908
  if (!names.has(name)) {
2809
2909
  knownVersions.delete(name);
2810
2910
  definitionCache.delete(name);
2911
+ invalidateSubgraphRoute(name);
2811
2912
  }
2812
2913
  }
2813
2914
  }
@@ -2859,6 +2960,9 @@ async function runSubgraphOperation(operation, signal) {
2859
2960
  });
2860
2961
  return result2.processed;
2861
2962
  }
2963
+ if (isByoSubgraph2(subgraph)) {
2964
+ throw new Error(`Reindex is not supported for BYO subgraphs ("${subgraph.name}"). Re-deploy to rebuild, or drop and recreate the schema in your database.`);
2965
+ }
2862
2966
  const hasResumeMetadata = subgraph.status === "reindexing" && subgraph.reindex_from_block != null && subgraph.reindex_to_block != null;
2863
2967
  if (hasResumeMetadata) {
2864
2968
  const result2 = await resumeReindex(def, { schemaName, signal });
@@ -3084,5 +3188,5 @@ var shutdown = async () => {
3084
3188
  process.on("SIGINT", shutdown);
3085
3189
  process.on("SIGTERM", shutdown);
3086
3190
 
3087
- //# debugId=CFDD2EF4C8B4C73E64756E2164756E21
3191
+ //# debugId=453058A5195B7A0C64756E2164756E21
3088
3192
  //# sourceMappingURL=service.js.map