@nicia-ai/typegraph 0.2.0 → 0.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.
- package/README.md +23 -0
- package/dist/{ast-BVyihVbP.d.cts → ast-CXFx6bF6.d.ts} +45 -165
- package/dist/{ast-BVyihVbP.d.ts → ast-D-3bOanX.d.cts} +45 -165
- package/dist/backend/drizzle/index.cjs +20 -20
- package/dist/backend/drizzle/index.d.cts +6 -5
- package/dist/backend/drizzle/index.d.ts +6 -5
- package/dist/backend/drizzle/index.js +8 -8
- package/dist/backend/drizzle/postgres.cjs +9 -9
- package/dist/backend/drizzle/postgres.d.cts +9 -11
- package/dist/backend/drizzle/postgres.d.ts +9 -11
- package/dist/backend/drizzle/postgres.js +6 -6
- package/dist/backend/drizzle/schema/postgres.cjs +10 -10
- package/dist/backend/drizzle/schema/postgres.d.cts +6 -5
- package/dist/backend/drizzle/schema/postgres.d.ts +6 -5
- package/dist/backend/drizzle/schema/postgres.js +3 -3
- package/dist/backend/drizzle/schema/sqlite.cjs +10 -10
- package/dist/backend/drizzle/schema/sqlite.d.cts +6 -5
- package/dist/backend/drizzle/schema/sqlite.d.ts +6 -5
- package/dist/backend/drizzle/schema/sqlite.js +3 -3
- package/dist/backend/drizzle/sqlite.cjs +9 -9
- package/dist/backend/drizzle/sqlite.d.cts +17 -18
- package/dist/backend/drizzle/sqlite.d.ts +17 -18
- package/dist/backend/drizzle/sqlite.js +6 -6
- package/dist/backend/postgres/index.cjs +21 -17
- package/dist/backend/postgres/index.d.cts +8 -7
- package/dist/backend/postgres/index.d.ts +8 -7
- package/dist/backend/postgres/index.js +8 -8
- package/dist/backend/sqlite/index.cjs +27 -21
- package/dist/backend/sqlite/index.cjs.map +1 -1
- package/dist/backend/sqlite/index.d.cts +7 -6
- package/dist/backend/sqlite/index.d.ts +7 -6
- package/dist/backend/sqlite/index.js +18 -12
- package/dist/backend/sqlite/index.js.map +1 -1
- package/dist/{chunk-YM5AL65Y.cjs → chunk-2WVFEIHR.cjs} +29 -3
- package/dist/chunk-2WVFEIHR.cjs.map +1 -0
- package/dist/{chunk-4PIEL2VO.js → chunk-3PURVEA4.js} +36 -5
- package/dist/chunk-3PURVEA4.js.map +1 -0
- package/dist/chunk-4HARSV2G.js +1448 -0
- package/dist/chunk-4HARSV2G.js.map +1 -0
- package/dist/{chunk-IIAT36MI.js → chunk-54WJF3DW.js} +29 -3
- package/dist/chunk-54WJF3DW.js.map +1 -0
- package/dist/chunk-CMHFS34N.cjs +390 -0
- package/dist/chunk-CMHFS34N.cjs.map +1 -0
- package/dist/chunk-DD6ONEBN.cjs +1264 -0
- package/dist/chunk-DD6ONEBN.cjs.map +1 -0
- package/dist/chunk-F2BZSEFE.js +388 -0
- package/dist/chunk-F2BZSEFE.js.map +1 -0
- package/dist/{chunk-DDM2FZRJ.cjs → chunk-JQDWEX6V.cjs} +24 -24
- package/dist/{chunk-DDM2FZRJ.cjs.map → chunk-JQDWEX6V.cjs.map} +1 -1
- package/dist/chunk-NP4G4ZKM.js +1228 -0
- package/dist/chunk-NP4G4ZKM.js.map +1 -0
- package/dist/{chunk-UJAGXJDG.cjs → chunk-NU2XNMVI.cjs} +38 -7
- package/dist/chunk-NU2XNMVI.cjs.map +1 -0
- package/dist/{chunk-JKTO7TW3.js → chunk-O5XPCJLF.js} +25 -3
- package/dist/chunk-O5XPCJLF.js.map +1 -0
- package/dist/{chunk-2QHQ2C4P.js → chunk-OGGLFYFA.js} +36 -5
- package/dist/chunk-OGGLFYFA.js.map +1 -0
- package/dist/{chunk-SV5H3XM5.cjs → chunk-OYL2SGBD.cjs} +26 -2
- package/dist/chunk-OYL2SGBD.cjs.map +1 -0
- package/dist/chunk-SFY2PPOY.cjs +1469 -0
- package/dist/chunk-SFY2PPOY.cjs.map +1 -0
- package/dist/{chunk-JDAET5LO.js → chunk-SMLIWLS7.js} +9 -9
- package/dist/chunk-SMLIWLS7.js.map +1 -0
- package/dist/{chunk-VXRVGFCI.js → chunk-U3452TEU.js} +17 -17
- package/dist/{chunk-VXRVGFCI.js.map → chunk-U3452TEU.js.map} +1 -1
- package/dist/{chunk-MNO33ASC.cjs → chunk-UYMT4LO2.cjs} +9 -8
- package/dist/chunk-UYMT4LO2.cjs.map +1 -0
- package/dist/chunk-V7CS2MDB.cjs +289 -0
- package/dist/chunk-V7CS2MDB.cjs.map +1 -0
- package/dist/chunk-WE5BKYNB.js +287 -0
- package/dist/chunk-WE5BKYNB.js.map +1 -0
- package/dist/{chunk-L642L24T.js → chunk-XDTYTNYL.js} +14 -21
- package/dist/chunk-XDTYTNYL.js.map +1 -0
- package/dist/{chunk-N4AOJ3VF.cjs → chunk-XZL6MCZJ.cjs} +38 -7
- package/dist/chunk-XZL6MCZJ.cjs.map +1 -0
- package/dist/{chunk-DBFCKELK.cjs → chunk-ZJHQZZT2.cjs} +18 -27
- package/dist/chunk-ZJHQZZT2.cjs.map +1 -0
- package/dist/index-Dkicw49A.d.cts +373 -0
- package/dist/index-Dkicw49A.d.ts +373 -0
- package/dist/index.cjs +5915 -3377
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +24 -664
- package/dist/index.d.ts +24 -664
- package/dist/index.js +5781 -3223
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +16 -16
- package/dist/indexes/index.d.cts +5 -4
- package/dist/indexes/index.d.ts +5 -4
- package/dist/indexes/index.js +2 -2
- package/dist/interchange/index.cjs +9 -9
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +5 -3
- package/dist/interchange/index.d.ts +5 -3
- package/dist/interchange/index.js +8 -8
- package/dist/interchange/index.js.map +1 -1
- package/dist/manager-Jc5Btay9.d.cts +493 -0
- package/dist/manager-e9LXthrx.d.ts +493 -0
- package/dist/profiler/index.cjs +2 -8
- package/dist/profiler/index.cjs.map +1 -1
- package/dist/profiler/index.d.cts +9 -161
- package/dist/profiler/index.d.ts +9 -161
- package/dist/profiler/index.js +4 -4
- package/dist/profiler/index.js.map +1 -1
- package/dist/schema/index.cjs +145 -0
- package/dist/schema/index.cjs.map +1 -0
- package/dist/schema/index.d.cts +237 -0
- package/dist/schema/index.d.ts +237 -0
- package/dist/schema/index.js +72 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/{store-BPhjw5S8.d.ts → store-DM3Tk3Pw.d.ts} +874 -1283
- package/dist/{store-DNOOQEm8.d.cts → store-nbBybLWP.d.cts} +874 -1283
- package/dist/{test-helpers-BjyRYJZX.d.ts → test-helpers-CIq1Hhj1.d.ts} +5 -1
- package/dist/{test-helpers-NoQXhleQ.d.cts → test-helpers-DPRFVky4.d.cts} +5 -1
- package/dist/{types-D_3mEv2y.d.ts → types-BL1GyVku.d.cts} +2 -2
- package/dist/{types-DsRfx0yk.d.ts → types-Cdbi4hcx.d.ts} +228 -4
- package/dist/{types-BrSfFSpW.d.cts → types-DCGa53O2.d.ts} +2 -2
- package/dist/{types-aapj0GLz.d.cts → types-DDP0MGBF.d.cts} +228 -4
- package/dist/{types-CX4cLd7M.d.ts → types-DHRsi6j9.d.cts} +4 -3
- package/dist/types-DTJEu_-h.d.cts +158 -0
- package/dist/types-DTJEu_-h.d.ts +158 -0
- package/dist/{types-a5rAxC92.d.cts → types-ZT5mlism.d.ts} +4 -3
- package/package.json +17 -2
- package/dist/chunk-2FURVVAX.cjs +0 -350
- package/dist/chunk-2FURVVAX.cjs.map +0 -1
- package/dist/chunk-2QHQ2C4P.js.map +0 -1
- package/dist/chunk-4PIEL2VO.js.map +0 -1
- package/dist/chunk-DBFCKELK.cjs.map +0 -1
- package/dist/chunk-H7THXVH6.cjs +0 -314
- package/dist/chunk-H7THXVH6.cjs.map +0 -1
- package/dist/chunk-HXAPXPZH.cjs +0 -680
- package/dist/chunk-HXAPXPZH.cjs.map +0 -1
- package/dist/chunk-IIAT36MI.js.map +0 -1
- package/dist/chunk-JDAET5LO.js.map +0 -1
- package/dist/chunk-JKTO7TW3.js.map +0 -1
- package/dist/chunk-L642L24T.js.map +0 -1
- package/dist/chunk-MNO33ASC.cjs.map +0 -1
- package/dist/chunk-N4AOJ3VF.cjs.map +0 -1
- package/dist/chunk-QB3WBMDT.js +0 -646
- package/dist/chunk-QB3WBMDT.js.map +0 -1
- package/dist/chunk-SV5H3XM5.cjs.map +0 -1
- package/dist/chunk-UJAGXJDG.cjs.map +0 -1
- package/dist/chunk-X4EVMBON.js +0 -312
- package/dist/chunk-X4EVMBON.js.map +0 -1
- package/dist/chunk-XZL4NLV6.js +0 -348
- package/dist/chunk-XZL4NLV6.js.map +0 -1
- package/dist/chunk-YM5AL65Y.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backend/drizzle/execution/postgres-execution.ts","../src/backend/drizzle/postgres.ts"],"names":["tables","options"],"mappings":";;;;;AA0BA,SAAS,gBAAgB,EAAA,EAA8C;AACrE,EAAA,MAAM,kBAAA,GAAqB,EAAA;AAC3B,EAAA,MAAM,WAAW,kBAAA,CAAmB,OAAA;AACpC,EAAA,IAAI,QAAA,EAAU,UAAU,MAAA,EAAW;AACjC,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,QAAA;AACT;AAEA,eAAe,mBAAA,CACb,IACA,KAAA,EAC0B;AAC1B,EAAA,MAAM,MAAA,GAAU,MAAM,EAAA,CAAG,OAAA,CAAQ,KAAK,CAAA;AAGtC,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAEA,SAAS,yBAAA,CACP,UACA,OAAA,EACsB;AACtB,EAAA,OAAO;AAAA,IACL,MAAM,QAAc,MAAA,EAAsD;AACxE,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,KAAA,CAAM,SAAS,MAAM,CAAA;AACnD,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB;AAAA,GACF;AACF;AAEO,SAAS,+BACd,EAAA,EAC0B;AAC1B,EAAA,MAAM,QAAA,GAAW,gBAAgB,EAAE,CAAA;AAEnC,EAAA,SAAS,Q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CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ;AAAA,GACrB,CAAA;AACH","file":"chunk-WE5BKYNB.js","sourcesContent":["import { type SQL } from \"drizzle-orm\";\nimport { type PgDatabase, type PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n} from \"./types\";\n\ntype PgQueryResult = Readonly<{\n rows: readonly unknown[];\n}>;\n\ntype PgQueryClient = Readonly<{\n query: (sqlText: string, params: readonly unknown[]) => Promise<PgQueryResult>;\n}>;\n\ntype PgClientCarrier = Readonly<{\n $client?: PgQueryClient;\n}>;\n\nexport type AnyPgDatabase = PgDatabase<PgQueryResultHKT>;\n\nexport type PostgresExecutionAdapter = SqlExecutionAdapter;\n\nfunction resolvePgClient(db: AnyPgDatabase): PgQueryClient | undefined {\n const databaseWithClient = db as PgClientCarrier;\n const pgClient = databaseWithClient.$client;\n if (pgClient?.query === undefined) {\n return undefined;\n }\n return pgClient;\n}\n\nasync function executeDrizzleQuery<TRow>(\n db: AnyPgDatabase,\n query: SQL,\n): Promise<readonly TRow[]> {\n const result = (await db.execute(query)) as Readonly<{\n rows: readonly TRow[];\n }>;\n return result.rows;\n}\n\nfunction createPgPreparedStatement(\n pgClient: PgQueryClient,\n sqlText: string,\n): PreparedSqlStatement {\n return {\n async execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const result = await pgClient.query(sqlText, params);\n return result.rows as readonly TRow[];\n },\n };\n}\n\nexport function createPostgresExecutionAdapter(\n db: AnyPgDatabase,\n): PostgresExecutionAdapter {\n const pgClient = resolvePgClient(db);\n\n function compile(query: SQL): CompiledSqlQuery {\n return compileQueryWithDialect(db, query, \"PostgreSQL\");\n }\n\n if (pgClient === undefined) {\n return {\n compile,\n async execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(db, query);\n },\n };\n }\n\n const pgQueryClient = pgClient;\n\n async function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const result = await pgQueryClient.query(\n compiledQuery.sql,\n compiledQuery.params,\n );\n return result.rows as readonly TRow[];\n }\n\n return {\n compile,\n async execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(db, query);\n },\n executeCompiled,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPgPreparedStatement(pgQueryClient, sqlText);\n },\n };\n}\n","/**\n * PostgreSQL backend adapter for TypeGraph.\n *\n * Works with any Drizzle PostgreSQL database instance:\n * - node-postgres (pg)\n * - PGlite\n * - Neon\n * - Vercel Postgres\n * - Supabase\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/node-postgres\";\n * import { Pool } from \"pg\";\n * import { createPostgresBackend } from \"@nicia-ai/typegraph/drizzle/postgres\";\n * import { tables } from \"@nicia-ai/typegraph/drizzle/schema/postgres\";\n *\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL });\n * const db = drizzle(pool);\n * const backend = createPostgresBackend(db, { tables });\n * ```\n */\nimport { getTableName, type SQL } from \"drizzle-orm\";\n\nimport type { SqlTableNames } from \"../../query/compiler/schema\";\nimport {\n type BackendCapabilities,\n type CreateVectorIndexParams,\n type DeleteEmbeddingParams,\n type DropVectorIndexParams,\n type EmbeddingRow,\n type GraphBackend,\n POSTGRES_CAPABILITIES,\n type TransactionBackend,\n type TransactionOptions,\n type UpsertEmbeddingParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n type AnyPgDatabase,\n createPostgresExecutionAdapter,\n type PostgresExecutionAdapter,\n} from \"./execution/postgres-execution\";\nimport { createCommonOperationBackend } from \"./operation-backend-core\";\nimport { createPostgresOperationStrategy } from \"./operations/strategy\";\nimport {\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n formatPostgresTimestamp,\n nowIso,\n POSTGRES_ROW_MAPPER_CONFIG,\n} from \"./row-mappers\";\nimport {\n type PostgresTables,\n tables as defaultTables,\n} from \"./schema/postgres\";\nimport {\n createPostgresVectorIndex,\n dropPostgresVectorIndex,\n generateVectorIndexName,\n type VectorIndexOptions,\n} from \"./vector-index\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a PostgreSQL backend.\n */\nexport type PostgresBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createPostgresTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: PostgresTables;\n}>;\n\nconst POSTGRES_MAX_BIND_PARAMETERS = 65_535;\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst POSTGRES_NODE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT),\n);\nconst POSTGRES_EDGE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT),\n);\nconst POSTGRES_GET_NODES_ID_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - 2,\n);\nconst POSTGRES_GET_EDGES_ID_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - 1,\n);\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\n\n/**\n * Converts a database row to EmbeddingRow type.\n * Raw SQL returns snake_case column names.\n */\nfunction toEmbeddingRow(row: Record<string, unknown>): EmbeddingRow {\n // pgvector returns embedding as a string '[1,2,3]' or as parsed array\n let embedding: readonly number[];\n if (typeof row.embedding === \"string\") {\n const content = row.embedding.slice(1, -1);\n embedding = content === \"\" ? [] : content.split(\",\").map((s) => Number.parseFloat(s.trim()));\n } else if (Array.isArray(row.embedding)) {\n embedding = row.embedding as number[];\n } else {\n embedding = [];\n }\n\n return {\n graph_id: row.graph_id as string,\n node_kind: row.node_kind as string,\n node_id: row.node_id as string,\n field_path: row.field_path as string,\n embedding,\n dimensions: row.dimensions as number,\n created_at: formatPostgresTimestamp(row.created_at) ?? \"\",\n updated_at: formatPostgresTimestamp(row.updated_at) ?? \"\",\n };\n}\n\n/**\n * PostgreSQL capabilities with vector search support.\n * Extends base POSTGRES_CAPABILITIES with vector operations.\n */\nconst POSTGRES_VECTOR_CAPABILITIES: BackendCapabilities = {\n ...POSTGRES_CAPABILITIES,\n vector: {\n supported: true,\n metrics: [\"cosine\", \"l2\", \"inner_product\"] as const,\n indexTypes: [\"hnsw\", \"ivfflat\", \"none\"] as const,\n maxDimensions: 16_000, // pgvector limit\n },\n};\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for PostgreSQL databases.\n *\n * Works with any Drizzle PostgreSQL instance regardless of the underlying driver.\n *\n * @param db - A Drizzle PostgreSQL database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\nexport function createPostgresBackend(\n db: AnyPgDatabase,\n options: PostgresBackendOptions = {},\n): GraphBackend {\n const tables = options.tables ?? defaultTables;\n const executionAdapter = createPostgresExecutionAdapter(db);\n const tableNames: SqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n embeddings: getTableName(tables.embeddings),\n };\n const operationStrategy = createPostgresOperationStrategy(tables);\n const operations = createPostgresOperationBackend({\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n });\n\n const backend: GraphBackend = {\n ...operations,\n\n async setActiveSchema(graphId: string, version: number): Promise<void> {\n await backend.transaction(async (txBackend) => {\n await txBackend.setActiveSchema(graphId, version);\n });\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T> {\n const txConfig = options?.isolationLevel\n ? {\n isolationLevel: options.isolationLevel.replace(\"_\", \" \") as\n | \"read uncommitted\"\n | \"read committed\"\n | \"repeatable read\"\n | \"serializable\",\n }\n : undefined;\n\n return db.transaction(async (tx) => {\n const txBackend = createTransactionBackend({\n db: tx as AnyPgDatabase,\n operationStrategy,\n tableNames,\n });\n return fn(txBackend);\n }, txConfig);\n },\n\n async close(): Promise<void> {\n // Drizzle doesn't expose a close method\n // Users manage connection lifecycle themselves\n },\n };\n\n return backend;\n}\n\ntype CreatePostgresOperationBackendOptions = Readonly<{\n db: AnyPgDatabase;\n executionAdapter: PostgresExecutionAdapter;\n operationStrategy: ReturnType<typeof createPostgresOperationStrategy>;\n tableNames: SqlTableNames;\n}>;\n\ntype CreatePostgresTransactionBackendOptions = Readonly<{\n db: AnyPgDatabase;\n executionAdapter?: PostgresExecutionAdapter;\n operationStrategy: ReturnType<typeof createPostgresOperationStrategy>;\n tableNames: SqlTableNames;\n}>;\n\nfunction createPostgresOperationBackend(\n options: CreatePostgresOperationBackendOptions,\n): TransactionBackend {\n const { db, executionAdapter, operationStrategy, tableNames } = options;\n\n async function execAll<T>(query: SQL): Promise<T[]> {\n const result = (await db.execute(query)) as Readonly<{\n rows: T[];\n }>;\n return result.rows;\n }\n\n async function execGet<T>(query: SQL): Promise<T | undefined> {\n const result = (await db.execute(query)) as Readonly<{\n rows: T[];\n }>;\n return result.rows[0];\n }\n\n async function execRun(query: SQL): Promise<void> {\n await db.execute(query);\n }\n\n const commonBackend = createCommonOperationBackend({\n batchConfig: {\n edgeInsertBatchSize: POSTGRES_EDGE_INSERT_BATCH_SIZE,\n getEdgesChunkSize: POSTGRES_GET_EDGES_ID_CHUNK_SIZE,\n getNodesChunkSize: POSTGRES_GET_NODES_ID_CHUNK_SIZE,\n nodeInsertBatchSize: POSTGRES_NODE_INSERT_BATCH_SIZE,\n },\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n async executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return executeCompiled<T>({ params, sql: sqlText });\n },\n };\n\n const operationBackend: TransactionBackend = {\n ...commonBackend,\n ...executeRawMethod,\n capabilities: POSTGRES_VECTOR_CAPABILITIES,\n dialect: \"postgres\",\n tableNames,\n\n // === Embedding Operations ===\n\n async upsertEmbedding(params: UpsertEmbeddingParams): Promise<void> {\n const timestamp = nowIso();\n const query = operationStrategy.buildUpsertEmbedding(params, timestamp);\n await execRun(query);\n },\n\n async deleteEmbedding(params: DeleteEmbeddingParams): Promise<void> {\n const query = operationStrategy.buildDeleteEmbedding(params);\n await execRun(query);\n },\n\n async getEmbedding(\n graphId: string,\n nodeKind: string,\n nodeId: string,\n fieldPath: string,\n ): Promise<EmbeddingRow | undefined> {\n const query = operationStrategy.buildGetEmbedding(\n graphId,\n nodeKind,\n nodeId,\n fieldPath,\n );\n const row = await execGet<Record<string, unknown>>(query);\n return row ? toEmbeddingRow(row) : undefined;\n },\n\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n const query = operationStrategy.buildVectorSearch(params);\n const rows = await execAll<{ node_id: string; score: number }>(query);\n return rows.map((row) => ({\n nodeId: row.node_id,\n score: row.score,\n }));\n },\n\n async createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n const indexOptions: VectorIndexOptions = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.fieldPath,\n dimensions: params.dimensions,\n embeddingsTableName: tableNames.embeddings,\n indexType: params.indexType,\n metric: params.metric,\n ...(params.indexParams?.m === undefined\n ? {}\n : { hnswM: params.indexParams.m }),\n ...(params.indexParams?.efConstruction === undefined\n ? {}\n : { hnswEfConstruction: params.indexParams.efConstruction }),\n ...(params.indexParams?.lists === undefined\n ? {}\n : { ivfflatLists: params.indexParams.lists }),\n };\n\n const result = await createPostgresVectorIndex(db, indexOptions);\n\n if (!result.success) {\n throw new Error(\n result.message ?? \"Failed to create PostgreSQL vector index\",\n );\n }\n },\n\n async dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n const metrics =\n POSTGRES_VECTOR_CAPABILITIES.vector?.metrics ?? ([\"cosine\"] as const);\n\n for (const metric of metrics) {\n const indexName = generateVectorIndexName(\n params.graphId,\n params.nodeKind,\n params.fieldPath,\n metric,\n );\n const result = await dropPostgresVectorIndex(db, indexName);\n if (!result.success) {\n throw new Error(\n result.message ?? \"Failed to drop PostgreSQL vector index\",\n );\n }\n }\n },\n\n // === Query Execution ===\n\n async execute<T>(query: SQL): Promise<readonly T[]> {\n return executionAdapter.execute<T>(query);\n },\n\n compileSql(query: SQL): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\nfunction createTransactionBackend(\n options: CreatePostgresTransactionBackendOptions,\n): TransactionBackend {\n const txExecutionAdapter =\n options.executionAdapter ?? createPostgresExecutionAdapter(options.db);\n\n return createPostgresOperationBackend({\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n });\n}\n\n// Re-export schema utilities\nexport type { PostgresTableNames,PostgresTables } from \"./schema/postgres\";\nexport { createPostgresTables, tables } from \"./schema/postgres\";\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ValidationError, ConfigurationError } from './chunk-
|
|
1
|
+
import { ValidationError, ConfigurationError } from './chunk-O5XPCJLF.js';
|
|
2
2
|
|
|
3
3
|
// src/core/types.ts
|
|
4
4
|
var NODE_TYPE_BRAND = "__nodeType";
|
|
@@ -16,14 +16,14 @@ function isEdgeTypeWithEndpoints(value) {
|
|
|
16
16
|
// src/core/define-graph.ts
|
|
17
17
|
var GRAPH_DEF_BRAND = "__graphDef";
|
|
18
18
|
function validateConstraintNarrowing(name, edgeType, registration) {
|
|
19
|
-
const builtInFromNames = new Set(edgeType.from.map((n) => n.
|
|
19
|
+
const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));
|
|
20
20
|
for (const fromNode of registration.from) {
|
|
21
|
-
if (!builtInFromNames.has(fromNode.
|
|
21
|
+
if (!builtInFromNames.has(fromNode.kind)) {
|
|
22
22
|
throw new ConfigurationError(
|
|
23
|
-
`Edge "${name}" registration has 'from' kind "${fromNode.
|
|
23
|
+
`Edge "${name}" registration has 'from' kind "${fromNode.kind}" not in edge's built-in domain: [${[...builtInFromNames].join(", ")}]`,
|
|
24
24
|
{
|
|
25
25
|
edgeName: name,
|
|
26
|
-
invalidFrom: fromNode.
|
|
26
|
+
invalidFrom: fromNode.kind,
|
|
27
27
|
allowedFrom: [...builtInFromNames]
|
|
28
28
|
},
|
|
29
29
|
{
|
|
@@ -32,14 +32,14 @@ function validateConstraintNarrowing(name, edgeType, registration) {
|
|
|
32
32
|
);
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
-
const builtInToNames = new Set(edgeType.to.map((n) => n.
|
|
35
|
+
const builtInToNames = new Set(edgeType.to.map((n) => n.kind));
|
|
36
36
|
for (const toNode of registration.to) {
|
|
37
|
-
if (!builtInToNames.has(toNode.
|
|
37
|
+
if (!builtInToNames.has(toNode.kind)) {
|
|
38
38
|
throw new ConfigurationError(
|
|
39
|
-
`Edge "${name}" registration has 'to' kind "${toNode.
|
|
39
|
+
`Edge "${name}" registration has 'to' kind "${toNode.kind}" not in edge's built-in range: [${[...builtInToNames].join(", ")}]`,
|
|
40
40
|
{
|
|
41
41
|
edgeName: name,
|
|
42
|
-
invalidTo: toNode.
|
|
42
|
+
invalidTo: toNode.kind,
|
|
43
43
|
allowedTo: [...builtInToNames]
|
|
44
44
|
},
|
|
45
45
|
{
|
|
@@ -87,10 +87,10 @@ function defineGraph(config) {
|
|
|
87
87
|
function isGraphDef(value) {
|
|
88
88
|
return typeof value === "object" && value !== null && GRAPH_DEF_BRAND in value && value[GRAPH_DEF_BRAND] === true;
|
|
89
89
|
}
|
|
90
|
-
function
|
|
90
|
+
function getNodeKinds(graph) {
|
|
91
91
|
return Object.keys(graph.nodes);
|
|
92
92
|
}
|
|
93
|
-
function
|
|
93
|
+
function getEdgeKinds(graph) {
|
|
94
94
|
return Object.keys(graph.edges);
|
|
95
95
|
}
|
|
96
96
|
|
|
@@ -126,17 +126,10 @@ function validateOptionalIsoDate(value, fieldName) {
|
|
|
126
126
|
if (value === void 0) return void 0;
|
|
127
127
|
return validateIsoDate(value, fieldName);
|
|
128
128
|
}
|
|
129
|
-
function encodeDate(date) {
|
|
130
|
-
return date.toISOString();
|
|
131
|
-
}
|
|
132
|
-
function decodeDate(isoString) {
|
|
133
|
-
validateIsoDate(isoString, "date");
|
|
134
|
-
return new Date(isoString);
|
|
135
|
-
}
|
|
136
129
|
function nowIso() {
|
|
137
130
|
return (/* @__PURE__ */ new Date()).toISOString();
|
|
138
131
|
}
|
|
139
132
|
|
|
140
|
-
export { EDGE_TYPE_BRAND, NODE_TYPE_BRAND,
|
|
141
|
-
//# sourceMappingURL=chunk-
|
|
142
|
-
//# sourceMappingURL=chunk-
|
|
133
|
+
export { EDGE_TYPE_BRAND, NODE_TYPE_BRAND, defineGraph, getEdgeKinds, getNodeKinds, isEdgeType, isEdgeTypeWithEndpoints, isGraphDef, isNodeType, nowIso, validateOptionalIsoDate };
|
|
134
|
+
//# sourceMappingURL=chunk-XDTYTNYL.js.map
|
|
135
|
+
//# sourceMappingURL=chunk-XDTYTNYL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts","../src/core/define-graph.ts","../src/utils/date.ts"],"names":[],"mappings":";;;AAOO,IAA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AAQlB,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,IAAI,CAAC,gBAAA,CAAiB,IAAA,CAAK,KAAK,CAAA,EAAG;AACjC,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,IAAA,GAAO,IAAI,IAAA,CAAK,KAAK,CAAA;AAC3B,EAAA,OAAO,CAAC,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA;AACrC;AAWO,SAAS,eAAA,CAAgB,OAAe,SAAA,EAA2B;AACxE,EAAA,IAAI,CAAC,cAAA,CAAe,KAAK,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAI,eAAA;AAAA,MACR,CAAA,+BAAA,EAAkC,SAAS,CAAA,IAAA,EAAO,KAAK,CAAA,4CAAA,CAAA;AAAA,MAEvD;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA,EAAM,SAAA;AAAA,YACN,OAAA,EAAS,+EAA+E,KAAK,CAAA,CAAA;AAAA;AAC/F;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY,CAAA,iEAAA;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,uBAAA,CACd,OACA,SAAA,EACoB;AACpB,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,OAAO,eAAA,CAAgB,OAAO,SAAS,CAAA;AACzC;AAuBO,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC","file":"chunk-XDTYTNYL.js","sourcesContent":["import { type z } from \"zod\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\nexport type UniqueConstraintPredicateBuilder<\n S extends z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n}>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\nexport type UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: \"isNull\" | \"isNotNull\";\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeTypeWithEndpoints,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (if it has from/to defined)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | EdgeTypeWithEndpoints;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n */\ntype NormalizedEdges<TEdges extends Record<string, EdgeEntry>> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends EdgeTypeWithEndpoints ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"][number],\n TEdges[K][\"to\"][number]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((n) => n.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(name: string, entry: EdgeEntry): EdgeRegistration {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to - convert to EdgeRegistration\n return {\n type: entry,\n from: entry.from,\n to: entry.to,\n };\n }\n\n // Already EdgeRegistration - validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n TNodes extends Record<string, NodeRegistration<NodeType>>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const normalizedEdges = normalizeEdges(config.edges);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n }) as GraphDef<TNodes, NormalizedEdges<TEdges>, TOntology>;\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(graph: G): readonly string[] {\n return Object.keys(graph.nodes);\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(graph: G): readonly string[] {\n return Object.keys(graph.edges);\n}\n","/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport { ValidationError } from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional ISO date string.\n * Returns undefined if value is undefined, otherwise validates.\n */\nexport function validateOptionalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateIsoDate(value, fieldName);\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkJQDWEX6V_cjs = require('./chunk-JQDWEX6V.cjs');
|
|
4
4
|
var sqliteCore = require('drizzle-orm/sqlite-core');
|
|
5
5
|
|
|
6
6
|
var DEFAULT_TABLE_NAMES = {
|
|
@@ -30,9 +30,15 @@ function createSqliteTables(names = {}, options = {}) {
|
|
|
30
30
|
(t) => [
|
|
31
31
|
sqliteCore.primaryKey({ columns: [t.graphId, t.kind, t.id] }),
|
|
32
32
|
sqliteCore.index(`${n.nodes}_kind_idx`).on(t.graphId, t.kind),
|
|
33
|
+
sqliteCore.index(`${n.nodes}_kind_created_idx`).on(
|
|
34
|
+
t.graphId,
|
|
35
|
+
t.kind,
|
|
36
|
+
t.deletedAt,
|
|
37
|
+
t.createdAt
|
|
38
|
+
),
|
|
33
39
|
sqliteCore.index(`${n.nodes}_deleted_idx`).on(t.graphId, t.deletedAt),
|
|
34
40
|
sqliteCore.index(`${n.nodes}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),
|
|
35
|
-
...
|
|
41
|
+
...chunkJQDWEX6V_cjs.buildSqliteNodeIndexBuilders(t, indexes)
|
|
36
42
|
]
|
|
37
43
|
);
|
|
38
44
|
const edges2 = sqliteCore.sqliteTable(
|
|
@@ -55,8 +61,33 @@ function createSqliteTables(names = {}, options = {}) {
|
|
|
55
61
|
(t) => [
|
|
56
62
|
sqliteCore.primaryKey({ columns: [t.graphId, t.id] }),
|
|
57
63
|
sqliteCore.index(`${n.edges}_kind_idx`).on(t.graphId, t.kind),
|
|
58
|
-
|
|
59
|
-
|
|
64
|
+
// Directional traversal index (outgoing): supports endpoint lookups
|
|
65
|
+
// and extra filtering by edge kind / target kind.
|
|
66
|
+
sqliteCore.index(`${n.edges}_from_idx`).on(
|
|
67
|
+
t.graphId,
|
|
68
|
+
t.fromKind,
|
|
69
|
+
t.fromId,
|
|
70
|
+
t.kind,
|
|
71
|
+
t.toKind,
|
|
72
|
+
t.deletedAt,
|
|
73
|
+
t.validTo
|
|
74
|
+
),
|
|
75
|
+
// Directional traversal index (incoming): mirrors from_idx for reverse traversals.
|
|
76
|
+
sqliteCore.index(`${n.edges}_to_idx`).on(
|
|
77
|
+
t.graphId,
|
|
78
|
+
t.toKind,
|
|
79
|
+
t.toId,
|
|
80
|
+
t.kind,
|
|
81
|
+
t.fromKind,
|
|
82
|
+
t.deletedAt,
|
|
83
|
+
t.validTo
|
|
84
|
+
),
|
|
85
|
+
sqliteCore.index(`${n.edges}_kind_created_idx`).on(
|
|
86
|
+
t.graphId,
|
|
87
|
+
t.kind,
|
|
88
|
+
t.deletedAt,
|
|
89
|
+
t.createdAt
|
|
90
|
+
),
|
|
60
91
|
sqliteCore.index(`${n.edges}_deleted_idx`).on(t.graphId, t.deletedAt),
|
|
61
92
|
sqliteCore.index(`${n.edges}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),
|
|
62
93
|
sqliteCore.index(`${n.edges}_cardinality_idx`).on(
|
|
@@ -66,7 +97,7 @@ function createSqliteTables(names = {}, options = {}) {
|
|
|
66
97
|
t.fromId,
|
|
67
98
|
t.validTo
|
|
68
99
|
),
|
|
69
|
-
...
|
|
100
|
+
...chunkJQDWEX6V_cjs.buildSqliteEdgeIndexBuilders(t, indexes)
|
|
70
101
|
]
|
|
71
102
|
);
|
|
72
103
|
const uniques2 = sqliteCore.sqliteTable(
|
|
@@ -150,5 +181,5 @@ exports.nodes = nodes;
|
|
|
150
181
|
exports.schemaVersions = schemaVersions;
|
|
151
182
|
exports.tables = tables;
|
|
152
183
|
exports.uniques = uniques;
|
|
153
|
-
//# sourceMappingURL=chunk-
|
|
154
|
-
//# sourceMappingURL=chunk-
|
|
184
|
+
//# sourceMappingURL=chunk-XZL6MCZJ.cjs.map
|
|
185
|
+
//# sourceMappingURL=chunk-XZL6MCZJ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backend/drizzle/schema/sqlite.ts"],"names":["nodes","sqliteTable","text","integer","primaryKey","index","buildSqliteNodeIndexBuilders","edges","buildSqliteEdgeIndexBuilders","uniques","schemaVersions","embeddings","blob"],"mappings":";;;;;AAwDA,IAAM,mBAAA,GAAwC;AAAA,EAC5C,KAAA,EAAO,iBAAA;AAAA,EACP,KAAA,EAAO,iBAAA;AAAA,EACP,OAAA,EAAS,wBAAA;AAAA,EACT,cAAA,EAAgB,2BAAA;AAAA,EAChB,UAAA,EAAY;AACd,CAAA;AAMO,SAAS,mBACd,KAAA,GAAmC,EAAC,EACpC,OAAA,GAAqC,EAAC,EACtC;AACA,EAAA,MAAM,CAAA,GAAsB,EAAE,GAAG,mBAAA,EAAqB,GAAG,KAAA,EAAM;AAC/D,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,IAAW,EAAC;AAEpC,EAAA,MAAMA,MAAAA,GAAQC,sBAAA;AAAA,IACZ,CAAA,CAAE,KAAA;AAAA,IACF;AAAA,MACE,OAAA,EAASC,eAAA,CAAK,UAAU,CAAA,CAAE,OAAA,EAAQ;AAAA,MAClC,IAAA,EAAMA,eAAA,CAAK,MAAM,CAAA,CAAE,OAAA,EAAQ;AAAA,MAC3B,EAAA,EAAIA,eAAA,CAAK,IAAI,CAAA,CAAE,OAAA,EAAQ;AAAA,MACvB,KAAA,EAAOA,eAAA,CAAK,OAAO,CAAA,CAAE,OAAA,EAAQ;AAAA,MAC7B,SAASC,kBAAA,CAAQ,SAAS,EAAE,OAAA,EAAQ,CAAE,QAAQ,CAAC,CAAA;AAAA,MAC/C,SAAA,EAAWD,gBAAK,YAAY,CAAA;AAAA,MAC5B,OAAA,EAASA,gBAAK,UAAU,CAAA;AAAA,MACxB,SAAA,EAAWA,eAAA,CAAK,YAAY,CAA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OAAA,EAAS,CAAC,CAAA,CAAE,OAAA,EAAS,EAAE,QAAA,EAAU,CAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,SAAS;AAAA,OACvD,CAAA;AAAA;AAAA,MAEDC,gBAAA,CAAM,CAAA,EAAG,CAAA,CAAE,UAAU,WAAW,CAAA,CAAE,EAAA;AAAA,QAChC,CAAA,CAAE,OAAA;AAAA,QACF,CAAA,CAAE,QAAA;AAAA,QACF,CAAA,CAAE;AAAA,OACJ;AAAA;AAAA,MAEAA,gBAAA,CAAM,CAAA,EAAG,CAAA,CAAE,UAAU,iBAAiB,CAAA,CAAE,EAAA;AAAA,QACtC,CAAA,CAAE,OAAA;AAAA,QACF,CAAA,CAAE,QAAA;AAAA,QACF,CAAA,CAAE;AAAA;AACJ;AACF,GACF;AAEA,EAAA,OAAO,EAAE,KAAA,EAAAL,MAAAA,EAAO,KAAA,EAAAO,MAAAA,EAAO,SAAAE,QAAAA,EAAS,cAAA,EAAAC,eAAAA,EAAgB,UAAA,EAAAC,WAAAA,EAAW;AAC7D;AAKO,IAAM,SAAS,kBAAA;AAKf,IAAM,EAAE,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,cAAA,EAAgB,YAAW,GAAI","file":"chunk-XZL6MCZJ.cjs","sourcesContent":["/**\n * Drizzle SQLite schema for TypeGraph.\n *\n * Provides table definitions that can be customized via the factory function.\n * Users import these tables into their Drizzle schema and use drizzle-kit\n * for migrations.\n *\n * @example\n * ```typescript\n * // Default table names\n * import { tables } from \"@nicia-ai/typegraph/drizzle/schema/sqlite\";\n *\n * // Custom table names\n * import { createSqliteTables } from \"@nicia-ai/typegraph/drizzle/schema/sqlite\";\n * const tables = createSqliteTables({\n * nodes: \"myapp_nodes\",\n * edges: \"myapp_edges\",\n * });\n * ```\n */\nimport {\n blob,\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n} from \"drizzle-orm/sqlite-core\";\n\nimport {\n buildSqliteEdgeIndexBuilders,\n buildSqliteNodeIndexBuilders,\n type TypeGraphIndex,\n} from \"../../../indexes\";\n\n/**\n * Table name configuration.\n */\nexport type SqliteTableNames = Readonly<{\n nodes: string;\n edges: string;\n uniques: string;\n schemaVersions: string;\n embeddings: string;\n}>;\n\nexport type CreateSqliteTablesOptions = Readonly<{\n /**\n * Additional TypeGraph indexes to include in the Drizzle schema.\n *\n * These become first-class Drizzle indexes, so drizzle-kit migrations will\n * pick them up automatically.\n */\n indexes?: readonly TypeGraphIndex[] | undefined;\n}>;\n\nconst DEFAULT_TABLE_NAMES: SqliteTableNames = {\n nodes: \"typegraph_nodes\",\n edges: \"typegraph_edges\",\n uniques: \"typegraph_node_uniques\",\n schemaVersions: \"typegraph_schema_versions\",\n embeddings: \"typegraph_node_embeddings\",\n};\n\n/**\n * Creates SQLite table definitions with customizable table names.\n * Index names are derived from table names.\n */\nexport function createSqliteTables(\n names: Partial<SqliteTableNames> = {},\n options: CreateSqliteTablesOptions = {},\n) {\n const n: SqliteTableNames = { ...DEFAULT_TABLE_NAMES, ...names };\n const indexes = options.indexes ?? [];\n\n const nodes = sqliteTable(\n n.nodes,\n {\n graphId: text(\"graph_id\").notNull(),\n kind: text(\"kind\").notNull(),\n id: text(\"id\").notNull(),\n props: text(\"props\").notNull(),\n version: integer(\"version\").notNull().default(1),\n validFrom: text(\"valid_from\"),\n validTo: text(\"valid_to\"),\n createdAt: text(\"created_at\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.kind, t.id] }),\n index(`${n.nodes}_kind_idx`).on(t.graphId, t.kind),\n index(`${n.nodes}_kind_created_idx`).on(\n t.graphId,\n t.kind,\n t.deletedAt,\n t.createdAt,\n ),\n index(`${n.nodes}_deleted_idx`).on(t.graphId, t.deletedAt),\n index(`${n.nodes}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),\n ...buildSqliteNodeIndexBuilders(t, indexes),\n ],\n );\n\n const edges = sqliteTable(\n n.edges,\n {\n graphId: text(\"graph_id\").notNull(),\n id: text(\"id\").notNull(),\n kind: text(\"kind\").notNull(),\n fromKind: text(\"from_kind\").notNull(),\n fromId: text(\"from_id\").notNull(),\n toKind: text(\"to_kind\").notNull(),\n toId: text(\"to_id\").notNull(),\n props: text(\"props\").notNull(),\n validFrom: text(\"valid_from\"),\n validTo: text(\"valid_to\"),\n createdAt: text(\"created_at\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.id] }),\n index(`${n.edges}_kind_idx`).on(t.graphId, t.kind),\n // Directional traversal index (outgoing): supports endpoint lookups\n // and extra filtering by edge kind / target kind.\n index(`${n.edges}_from_idx`).on(\n t.graphId,\n t.fromKind,\n t.fromId,\n t.kind,\n t.toKind,\n t.deletedAt,\n t.validTo,\n ),\n // Directional traversal index (incoming): mirrors from_idx for reverse traversals.\n index(`${n.edges}_to_idx`).on(\n t.graphId,\n t.toKind,\n t.toId,\n t.kind,\n t.fromKind,\n t.deletedAt,\n t.validTo,\n ),\n index(`${n.edges}_kind_created_idx`).on(\n t.graphId,\n t.kind,\n t.deletedAt,\n t.createdAt,\n ),\n index(`${n.edges}_deleted_idx`).on(t.graphId, t.deletedAt),\n index(`${n.edges}_valid_idx`).on(t.graphId, t.validFrom, t.validTo),\n index(`${n.edges}_cardinality_idx`).on(\n t.graphId,\n t.kind,\n t.fromKind,\n t.fromId,\n t.validTo,\n ),\n ...buildSqliteEdgeIndexBuilders(t, indexes),\n ],\n );\n\n const uniques = sqliteTable(\n n.uniques,\n {\n graphId: text(\"graph_id\").notNull(),\n nodeKind: text(\"node_kind\").notNull(),\n constraintName: text(\"constraint_name\").notNull(),\n key: text(\"key\").notNull(),\n nodeId: text(\"node_id\").notNull(),\n concreteKind: text(\"concrete_kind\").notNull(),\n deletedAt: text(\"deleted_at\"),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.nodeKind, t.constraintName, t.key],\n }),\n index(`${n.uniques}_node_idx`).on(t.graphId, t.concreteKind, t.nodeId),\n ],\n );\n\n const schemaVersions = sqliteTable(\n n.schemaVersions,\n {\n graphId: text(\"graph_id\").notNull(),\n version: integer(\"version\").notNull(),\n schemaHash: text(\"schema_hash\").notNull(),\n schemaDoc: text(\"schema_doc\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n isActive: integer(\"is_active\", { mode: \"boolean\" })\n .notNull()\n .default(false),\n },\n (t) => [\n primaryKey({ columns: [t.graphId, t.version] }),\n index(`${n.schemaVersions}_active_idx`).on(t.graphId, t.isActive),\n ],\n );\n\n /**\n * Embeddings table for vector search.\n *\n * Stores embeddings as BLOB (for sqlite-vec binary format) or as JSON text.\n * When sqlite-vec extension is loaded, the BLOB column can be used with\n * vec_f32() for similarity operations.\n */\n const embeddings = sqliteTable(\n n.embeddings,\n {\n graphId: text(\"graph_id\").notNull(),\n nodeKind: text(\"node_kind\").notNull(),\n nodeId: text(\"node_id\").notNull(),\n fieldPath: text(\"field_path\").notNull(),\n /**\n * Embedding vector.\n * Stored as BLOB for sqlite-vec binary format, or JSON text for fallback.\n * For sqlite-vec: use vec_f32() to convert JSON array to binary.\n */\n embedding: blob(\"embedding\", { mode: \"buffer\" }).notNull(),\n /** Number of dimensions (for validation) */\n dimensions: integer(\"dimensions\").notNull(),\n createdAt: text(\"created_at\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (t) => [\n primaryKey({\n columns: [t.graphId, t.nodeKind, t.nodeId, t.fieldPath],\n }),\n // Index for looking up embeddings by node\n index(`${n.embeddings}_node_idx`).on(\n t.graphId,\n t.nodeKind,\n t.nodeId,\n ),\n // Index for filtering by kind and field (used in vector search)\n index(`${n.embeddings}_kind_field_idx`).on(\n t.graphId,\n t.nodeKind,\n t.fieldPath,\n ),\n ],\n );\n\n return { nodes, edges, uniques, schemaVersions, embeddings } as const;\n}\n\n/**\n * Default tables with standard TypeGraph table names.\n */\nexport const tables = createSqliteTables();\n\n/**\n * Convenience exports for default tables.\n */\nexport const { nodes, edges, uniques, schemaVersions, embeddings } = tables;\n\n/**\n * Type representing the tables object returned by createSqliteTables.\n */\nexport type SqliteTables = ReturnType<typeof createSqliteTables>;\n\n/**\n * Type for nodes table.\n */\nexport type NodesTable = SqliteTables[\"nodes\"];\n\n/**\n * Type for edges table.\n */\nexport type EdgesTable = SqliteTables[\"edges\"];\n\n/**\n * Type for uniques table.\n */\nexport type UniquesTable = SqliteTables[\"uniques\"];\n\n/**\n * Type for schema versions table.\n */\nexport type SchemaVersionsTable = SqliteTables[\"schemaVersions\"];\n\n/**\n * Type for embeddings table.\n */\nexport type EmbeddingsTable = SqliteTables[\"embeddings\"];\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkOYL2SGBD_cjs = require('./chunk-OYL2SGBD.cjs');
|
|
4
4
|
|
|
5
5
|
// src/core/types.ts
|
|
6
6
|
var NODE_TYPE_BRAND = "__nodeType";
|
|
@@ -18,14 +18,14 @@ function isEdgeTypeWithEndpoints(value) {
|
|
|
18
18
|
// src/core/define-graph.ts
|
|
19
19
|
var GRAPH_DEF_BRAND = "__graphDef";
|
|
20
20
|
function validateConstraintNarrowing(name, edgeType, registration) {
|
|
21
|
-
const builtInFromNames = new Set(edgeType.from.map((n) => n.
|
|
21
|
+
const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));
|
|
22
22
|
for (const fromNode of registration.from) {
|
|
23
|
-
if (!builtInFromNames.has(fromNode.
|
|
24
|
-
throw new
|
|
25
|
-
`Edge "${name}" registration has 'from' kind "${fromNode.
|
|
23
|
+
if (!builtInFromNames.has(fromNode.kind)) {
|
|
24
|
+
throw new chunkOYL2SGBD_cjs.ConfigurationError(
|
|
25
|
+
`Edge "${name}" registration has 'from' kind "${fromNode.kind}" not in edge's built-in domain: [${[...builtInFromNames].join(", ")}]`,
|
|
26
26
|
{
|
|
27
27
|
edgeName: name,
|
|
28
|
-
invalidFrom: fromNode.
|
|
28
|
+
invalidFrom: fromNode.kind,
|
|
29
29
|
allowedFrom: [...builtInFromNames]
|
|
30
30
|
},
|
|
31
31
|
{
|
|
@@ -34,14 +34,14 @@ function validateConstraintNarrowing(name, edgeType, registration) {
|
|
|
34
34
|
);
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
-
const builtInToNames = new Set(edgeType.to.map((n) => n.
|
|
37
|
+
const builtInToNames = new Set(edgeType.to.map((n) => n.kind));
|
|
38
38
|
for (const toNode of registration.to) {
|
|
39
|
-
if (!builtInToNames.has(toNode.
|
|
40
|
-
throw new
|
|
41
|
-
`Edge "${name}" registration has 'to' kind "${toNode.
|
|
39
|
+
if (!builtInToNames.has(toNode.kind)) {
|
|
40
|
+
throw new chunkOYL2SGBD_cjs.ConfigurationError(
|
|
41
|
+
`Edge "${name}" registration has 'to' kind "${toNode.kind}" not in edge's built-in range: [${[...builtInToNames].join(", ")}]`,
|
|
42
42
|
{
|
|
43
43
|
edgeName: name,
|
|
44
|
-
invalidTo: toNode.
|
|
44
|
+
invalidTo: toNode.kind,
|
|
45
45
|
allowedTo: [...builtInToNames]
|
|
46
46
|
},
|
|
47
47
|
{
|
|
@@ -89,10 +89,10 @@ function defineGraph(config) {
|
|
|
89
89
|
function isGraphDef(value) {
|
|
90
90
|
return typeof value === "object" && value !== null && GRAPH_DEF_BRAND in value && value[GRAPH_DEF_BRAND] === true;
|
|
91
91
|
}
|
|
92
|
-
function
|
|
92
|
+
function getNodeKinds(graph) {
|
|
93
93
|
return Object.keys(graph.nodes);
|
|
94
94
|
}
|
|
95
|
-
function
|
|
95
|
+
function getEdgeKinds(graph) {
|
|
96
96
|
return Object.keys(graph.edges);
|
|
97
97
|
}
|
|
98
98
|
|
|
@@ -107,7 +107,7 @@ function isValidIsoDate(value) {
|
|
|
107
107
|
}
|
|
108
108
|
function validateIsoDate(value, fieldName) {
|
|
109
109
|
if (!isValidIsoDate(value)) {
|
|
110
|
-
throw new
|
|
110
|
+
throw new chunkOYL2SGBD_cjs.ValidationError(
|
|
111
111
|
`Invalid ISO 8601 datetime for "${fieldName}": "${value}". Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,
|
|
112
112
|
{
|
|
113
113
|
issues: [
|
|
@@ -128,29 +128,20 @@ function validateOptionalIsoDate(value, fieldName) {
|
|
|
128
128
|
if (value === void 0) return void 0;
|
|
129
129
|
return validateIsoDate(value, fieldName);
|
|
130
130
|
}
|
|
131
|
-
function encodeDate(date) {
|
|
132
|
-
return date.toISOString();
|
|
133
|
-
}
|
|
134
|
-
function decodeDate(isoString) {
|
|
135
|
-
validateIsoDate(isoString, "date");
|
|
136
|
-
return new Date(isoString);
|
|
137
|
-
}
|
|
138
131
|
function nowIso() {
|
|
139
132
|
return (/* @__PURE__ */ new Date()).toISOString();
|
|
140
133
|
}
|
|
141
134
|
|
|
142
135
|
exports.EDGE_TYPE_BRAND = EDGE_TYPE_BRAND;
|
|
143
136
|
exports.NODE_TYPE_BRAND = NODE_TYPE_BRAND;
|
|
144
|
-
exports.decodeDate = decodeDate;
|
|
145
137
|
exports.defineGraph = defineGraph;
|
|
146
|
-
exports.
|
|
147
|
-
exports.
|
|
148
|
-
exports.getNodeTypeNames = getNodeTypeNames;
|
|
138
|
+
exports.getEdgeKinds = getEdgeKinds;
|
|
139
|
+
exports.getNodeKinds = getNodeKinds;
|
|
149
140
|
exports.isEdgeType = isEdgeType;
|
|
150
141
|
exports.isEdgeTypeWithEndpoints = isEdgeTypeWithEndpoints;
|
|
151
142
|
exports.isGraphDef = isGraphDef;
|
|
152
143
|
exports.isNodeType = isNodeType;
|
|
153
144
|
exports.nowIso = nowIso;
|
|
154
145
|
exports.validateOptionalIsoDate = validateOptionalIsoDate;
|
|
155
|
-
//# sourceMappingURL=chunk-
|
|
156
|
-
//# sourceMappingURL=chunk-
|
|
146
|
+
//# sourceMappingURL=chunk-ZJHQZZT2.cjs.map
|
|
147
|
+
//# sourceMappingURL=chunk-ZJHQZZT2.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts","../src/core/define-graph.ts","../src/utils/date.ts"],"names":["ConfigurationError","ValidationError"],"mappings":";;;;;AAOO,IAAM,eAAA,GAAkB;AAGxB,IAAM,eAAA,GAAkB;AA6OxB,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAKO,SAAS,WAAW,KAAA,EAAsC;AAC/D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAMO,SAAS,wBACd,KAAA,EACgC;AAChC,EAAA,OACE,WAAW,KAAK,CAAA,IAChB,MAAM,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,IACxB,KAAA,CAAM,KAAK,MAAA,GAAS,CAAA,IACpB,MAAM,OAAA,CAAQ,KAAA,CAAM,EAAE,CAAA,IACtB,KAAA,CAAM,GAAG,MAAA,GAAS,CAAA;AAEtB;;;ACxQA,IAAM,eAAA,GAAkB,YAAA;AAoCxB,SAAS,2BAAA,CACP,IAAA,EACA,QAAA,EACA,YAAA,EACM;AACN,EAAA,MAAM,gBAAA,GAAmB,IAAI,GAAA,CAAI,QAAA,CAAS,IAAA,CAAK,IAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAI,CAAC,CAAA;AACjE,EAAA,KAAA,MAAW,QAAA,IAAY,aAAa,IAAA,EAAM;AACxC,IAAA,IAAI,CAAC,gBAAA,CAAiB,GAAA,CAAI,QAAA,CAAS,IAAI,CAAA,EAAG;AACxC,MAAA,MAAM,IAAIA,oCAAA;AAAA,QACR,CAAA,MAAA,EAAS,IAAI,CAAA,gCAAA,EAAmC,QAAA,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AM,KAAK,CAAA;AAChC;AAKO,SAAS,aAAiC,KAAA,EAA6B;AAC5E,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,KAAK,CAAA;AAChC;;;AC7SA,IAAM,gBAAA,GAAmB,sDAAA;AAQlB,SAAS,eAAe,KAAA,EAAwB;AACrD,EAAA,IAAI,CAAC,gBAAA,CAAiB,IAAA,CAAK,KAAK,CAAA,EAAG;AACjC,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,IAAA,GAAO,IAAI,IAAA,CAAK,KAAK,CAAA;AAC3B,EAAA,OAAO,CAAC,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA;AACrC;AAWO,SAAS,eAAA,CAAgB,OAAe,SAAA,EAA2B;AACxE,EAAA,IAAI,CAAC,cAAA,CAAe,KAAK,CAAA,EAAG;AAC1B,IAAA,MAAM,IAAIC,iCAAA;AAAA,MACR,CAAA,+BAAA,EAAkC,SAAS,CAAA,IAAA,EAAO,KAAK,CAAA,4CAAA,CAAA;AAAA,MAEvD;AAAA,QACE,MAAA,EAAQ;AAAA,UACN;AAAA,YACE,IAAA,EAAM,SAAA;AAAA,YACN,OAAA,EAAS,+EAA+E,KAAK,CAAA,CAAA;AAAA;AAC/F;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY,CAAA,iEAAA;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,uBAAA,CACd,OACA,SAAA,EACoB;AACpB,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,OAAO,eAAA,CAAgB,OAAO,SAAS,CAAA;AACzC;AAuBO,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC","file":"chunk-ZJHQZZT2.cjs","sourcesContent":["import { type z } from \"zod\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\nexport type UniqueConstraintPredicateBuilder<\n S extends z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n}>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\nexport type UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: \"isNull\" | \"isNotNull\";\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeTypeWithEndpoints,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (if it has from/to defined)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | EdgeTypeWithEndpoints;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n */\ntype NormalizedEdges<TEdges extends Record<string, EdgeEntry>> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends EdgeTypeWithEndpoints ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"][number],\n TEdges[K][\"to\"][number]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((n) => n.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(name: string, entry: EdgeEntry): EdgeRegistration {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to - convert to EdgeRegistration\n return {\n type: entry,\n from: entry.from,\n to: entry.to,\n };\n }\n\n // Already EdgeRegistration - validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n TNodes extends Record<string, NodeRegistration<NodeType>>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const normalizedEdges = normalizeEdges(config.edges);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n }) as GraphDef<TNodes, NormalizedEdges<TEdges>, TOntology>;\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(graph: G): readonly string[] {\n return Object.keys(graph.nodes);\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(graph: G): readonly string[] {\n return Object.keys(graph.edges);\n}\n","/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport { ValidationError } from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional ISO date string.\n * Returns undefined if value is undefined, otherwise validates.\n */\nexport function validateOptionalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateIsoDate(value, fieldName);\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n"]}
|