@absolutejs/rag-postgres 0.0.5

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 ADDED
@@ -0,0 +1,49 @@
1
+ # @absolutejs/rag-postgres
2
+
3
+ PostgreSQL vector-store adapter for [`@absolutejs/rag`](https://github.com/absolutejs/rag),
4
+ with `pgvector` as the first vector implementation. Native vector search, server-side
5
+ filtering, and inspectable schema/migration plans.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add @absolutejs/rag @absolutejs/rag-postgres postgres
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { createPostgresRAG } from '@absolutejs/rag-postgres';
17
+ import { ragPlugin } from '@absolutejs/rag';
18
+
19
+ const rag = createPostgresRAG({
20
+ connectionString: process.env.DATABASE_URL,
21
+ vector: {
22
+ provider: 'pgvector',
23
+ dimensions: 1536,
24
+ distanceMetric: 'cosine',
25
+ autoCreateExtension: true,
26
+ autoCreateSchema: true,
27
+ autoCreateTables: true,
28
+ autoCreateIndex: true,
29
+ index: { type: 'hnsw', efSearch: 100, efConstruction: 64, m: 16 }
30
+ },
31
+ schema: { schemaName: 'absolute_rag', chunkTableName: 'chunks' }
32
+ });
33
+
34
+ app.use(ragPlugin({ path: '/rag', collection: rag.collection }));
35
+ ```
36
+
37
+ ### Schema and migrations
38
+
39
+ Inspect the generated SQL or apply migrations explicitly:
40
+
41
+ ```ts
42
+ const schemaPlan = rag.getSchemaPlan();
43
+ const migrationPlan = rag.getMigrationPlan();
44
+ await rag.applyMigrations();
45
+ ```
46
+
47
+ ## License
48
+
49
+ CC BY-NC 4.0
@@ -0,0 +1,122 @@
1
+ import type { RAGBackendCapabilities, RAGCollection, RAGVectorStore, RAGVectorStoreStatus } from '@absolutejs/rag';
2
+ export declare const ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME = "@absolutejs/rag-postgres";
3
+ export declare const POSTGRESQL_RAG_IMPLEMENTATIONS: readonly ["pgvector"];
4
+ export declare const PGVECTOR_DISTANCE_METRICS: readonly ["cosine", "l2", "inner_product"];
5
+ export declare const PGVECTOR_INDEX_TYPES: readonly ["none", "hnsw", "ivfflat"];
6
+ export type PostgreSQLRAGVectorImplementation = 'pgvector';
7
+ export type PgvectorDistanceMetric = 'cosine' | 'l2' | 'inner_product';
8
+ export type PgvectorIndexType = 'none' | 'hnsw' | 'ivfflat';
9
+ export type PostgreSQLRAGClient = {
10
+ query: <TRow = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<{
11
+ rows: TRow[];
12
+ rowCount?: number;
13
+ }>;
14
+ transaction?: <T>(run: (client: PostgreSQLRAGClient) => Promise<T>) => Promise<T>;
15
+ close?: () => Promise<void>;
16
+ };
17
+ export type PostgreSQLRAGClientFactory = () => Promise<PostgreSQLRAGClient> | PostgreSQLRAGClient;
18
+ export type PostgreSQLRAGSchemaConfig = {
19
+ schemaName?: string;
20
+ chunkTableName?: string;
21
+ migrationTableName?: string;
22
+ };
23
+ export type PgvectorHNSWConfig = {
24
+ type: 'hnsw';
25
+ m?: number;
26
+ efConstruction?: number;
27
+ efSearch?: number;
28
+ iterativeScan?: 'off' | 'strict_order' | 'relaxed_order';
29
+ };
30
+ export type PgvectorIVFFlatConfig = {
31
+ type: 'ivfflat';
32
+ lists?: number;
33
+ probes?: number;
34
+ maxProbes?: number;
35
+ iterativeScan?: 'off' | 'strict_order' | 'relaxed_order';
36
+ };
37
+ export type PgvectorNoIndexConfig = {
38
+ type: 'none';
39
+ };
40
+ export type PgvectorIndexConfig = PgvectorNoIndexConfig | PgvectorHNSWConfig | PgvectorIVFFlatConfig;
41
+ export type PgvectorConfig = {
42
+ provider: 'pgvector';
43
+ dimensions: number;
44
+ distanceMetric?: PgvectorDistanceMetric;
45
+ extensionName?: 'vector' | string;
46
+ autoCreateExtension?: boolean;
47
+ autoCreateSchema?: boolean;
48
+ autoCreateTables?: boolean;
49
+ autoCreateIndex?: boolean;
50
+ index?: PgvectorIndexConfig;
51
+ };
52
+ export type PostgreSQLDriverOptions = {
53
+ max?: number;
54
+ prepare?: boolean;
55
+ idle_timeout?: number;
56
+ connect_timeout?: number;
57
+ max_lifetime?: number;
58
+ ssl?: boolean | 'require' | 'allow' | 'prefer' | 'verify-full';
59
+ };
60
+ export type PostgreSQLRAGOptions = {
61
+ connectionString?: string;
62
+ client?: PostgreSQLRAGClient;
63
+ clientFactory?: PostgreSQLRAGClientFactory;
64
+ driver?: PostgreSQLDriverOptions;
65
+ schema?: PostgreSQLRAGSchemaConfig;
66
+ vector: PgvectorConfig;
67
+ embedding?: RAGVectorStore['embed'];
68
+ };
69
+ export type PostgreSQLSchemaPlan = {
70
+ implementation: PostgreSQLRAGVectorImplementation;
71
+ extensionSql: string[];
72
+ schemaSql: string[];
73
+ tableSql: string[];
74
+ indexSql: string[];
75
+ querySessionSql: string[];
76
+ migrationTableQualifiedName: string;
77
+ };
78
+ export type PostgreSQLMigrationStage = 'extension' | 'table' | 'index';
79
+ export type PostgreSQLMigrationEntry = {
80
+ name: string;
81
+ stage: PostgreSQLMigrationStage;
82
+ sql: string;
83
+ };
84
+ export type PostgreSQLMigrationPlan = {
85
+ implementation: PostgreSQLRAGVectorImplementation;
86
+ schemaName: string;
87
+ migrationTableName: string;
88
+ migrationTableQualifiedName: string;
89
+ bootstrapSql: string[];
90
+ migrations: PostgreSQLMigrationEntry[];
91
+ schemaPlan: PostgreSQLSchemaPlan;
92
+ };
93
+ export type PostgreSQLApplyMigrationsOptions = {
94
+ client?: PostgreSQLRAGClient;
95
+ dryRun?: boolean;
96
+ };
97
+ export type PostgreSQLApplyMigrationsResult = {
98
+ migrationPlan: PostgreSQLMigrationPlan;
99
+ appliedNames: string[];
100
+ skippedNames: string[];
101
+ pendingNames: string[];
102
+ appliedCount: number;
103
+ pendingCount: number;
104
+ dryRun: boolean;
105
+ };
106
+ export type PostgreSQLRAG = {
107
+ store: RAGVectorStore;
108
+ collection: RAGCollection;
109
+ getStatus: () => RAGVectorStoreStatus | undefined;
110
+ getCapabilities: () => RAGBackendCapabilities | undefined;
111
+ getSchemaPlan: () => PostgreSQLSchemaPlan;
112
+ getMigrationPlan: () => PostgreSQLMigrationPlan;
113
+ applyMigrations: (options?: PostgreSQLApplyMigrationsOptions) => Promise<PostgreSQLApplyMigrationsResult>;
114
+ };
115
+ export declare const createPostgresSchemaPlan: (options: PostgreSQLRAGOptions) => PostgreSQLSchemaPlan;
116
+ export declare const createPostgresMigrationPlan: (options: PostgreSQLRAGOptions) => PostgreSQLMigrationPlan;
117
+ export declare const applyPostgresMigrations: (options: PostgreSQLRAGOptions, applyOptions?: PostgreSQLApplyMigrationsOptions) => Promise<PostgreSQLApplyMigrationsResult>;
118
+ export declare const applyPostgresSchemaPlan: typeof applyPostgresMigrations;
119
+ export declare const createPgvectorStore: (options: PostgreSQLRAGOptions) => RAGVectorStore;
120
+ export declare const createPostgresRAGCollection: (options: PostgreSQLRAGOptions) => RAGCollection;
121
+ export declare const createPostgresRAG: (options: PostgreSQLRAGOptions) => PostgreSQLRAG;
122
+ export declare const createPostgreSQLRAG: typeof createPostgresRAG;
package/dist/index.js ADDED
@@ -0,0 +1,622 @@
1
+ // @bun
2
+ var __require = import.meta.require;
3
+
4
+ // src/index.ts
5
+ import {
6
+ createRAGCollection,
7
+ createRAGVector,
8
+ normalizeVector
9
+ } from "@absolutejs/rag";
10
+ var ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME = "@absolutejs/rag-postgres";
11
+ var POSTGRESQL_RAG_IMPLEMENTATIONS = ["pgvector"];
12
+ var PGVECTOR_DISTANCE_METRICS = [
13
+ "cosine",
14
+ "l2",
15
+ "inner_product"
16
+ ];
17
+ var PGVECTOR_INDEX_TYPES = ["none", "hnsw", "ivfflat"];
18
+ var DEFAULT_SCHEMA_NAME = "absolute_rag";
19
+ var DEFAULT_CHUNK_TABLE_NAME = "chunks";
20
+ var DEFAULT_MIGRATION_TABLE_NAME = "migrations";
21
+ var DEFAULT_DIMENSIONS = 1536;
22
+ var IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
23
+ var assertIdentifier = (value, label) => {
24
+ if (typeof value !== "string" || !IDENTIFIER_RE.test(value)) {
25
+ throw new Error(`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: invalid ${label} "${String(value)}"`);
26
+ }
27
+ };
28
+ var quoteIdentifier = (value) => {
29
+ assertIdentifier(value, "identifier");
30
+ return `"${value}"`;
31
+ };
32
+ var qualifiedTable = (schemaName, tableName) => `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;
33
+ var escapeLiteral = (value) => value.replace(/'/g, "''");
34
+ var vectorLiteral = (vector) => {
35
+ if (!Array.isArray(vector) || vector.length === 0) {
36
+ throw new Error(`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: vector values must be a non-empty array`);
37
+ }
38
+ return `[${vector.map((value) => {
39
+ if (typeof value !== "number" || !Number.isFinite(value)) {
40
+ throw new Error(`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: vector values must be finite numbers`);
41
+ }
42
+ return String(value);
43
+ }).join(",")}]`;
44
+ };
45
+ var makePlaceholder = (params, value, cast = "") => {
46
+ params.push(value);
47
+ const suffix = cast ? `::${cast}` : "";
48
+ return `$${params.length}${suffix}`;
49
+ };
50
+ var normalizeMetric = (metric) => {
51
+ if (metric === "l2" || metric === "inner_product") {
52
+ return metric;
53
+ }
54
+ return "cosine";
55
+ };
56
+ var normalizeIndex = (index) => {
57
+ if (!index || index.type === undefined) {
58
+ return { type: "none" };
59
+ }
60
+ if (index.type === "hnsw" || index.type === "ivfflat" || index.type === "none") {
61
+ return index;
62
+ }
63
+ throw new Error(`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: unsupported pgvector index type "${String(index.type)}"`);
64
+ };
65
+ var resolveSchemaConfig = (options) => {
66
+ const schemaName = options.schema?.schemaName ?? DEFAULT_SCHEMA_NAME;
67
+ const chunkTableName = options.schema?.chunkTableName ?? DEFAULT_CHUNK_TABLE_NAME;
68
+ const migrationTableName = options.schema?.migrationTableName ?? DEFAULT_MIGRATION_TABLE_NAME;
69
+ assertIdentifier(schemaName, "schema name");
70
+ assertIdentifier(chunkTableName, "chunk table name");
71
+ assertIdentifier(migrationTableName, "migration table name");
72
+ return {
73
+ schemaName,
74
+ chunkTableName,
75
+ migrationTableName
76
+ };
77
+ };
78
+ var resolveVectorConfig = (options) => {
79
+ const vector = options?.vector;
80
+ if (!vector || vector.provider !== "pgvector") {
81
+ throw new Error(`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: PostgreSQL RAG currently requires vector.provider = "pgvector"`);
82
+ }
83
+ const dimensions = vector.dimensions ?? DEFAULT_DIMENSIONS;
84
+ if (!Number.isInteger(dimensions) || dimensions <= 0) {
85
+ throw new Error(`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: dimensions must be a positive integer`);
86
+ }
87
+ const distanceMetric = normalizeMetric(vector.distanceMetric);
88
+ const index = normalizeIndex(vector.index);
89
+ return {
90
+ ...vector,
91
+ dimensions,
92
+ distanceMetric,
93
+ extensionName: vector.extensionName ?? "vector",
94
+ index
95
+ };
96
+ };
97
+ var operatorForMetric = (distanceMetric) => {
98
+ switch (distanceMetric) {
99
+ case "l2":
100
+ return "<->";
101
+ case "inner_product":
102
+ return "<#>";
103
+ case "cosine":
104
+ default:
105
+ return "<=>";
106
+ }
107
+ };
108
+ var operatorClassForMetric = (distanceMetric) => {
109
+ switch (distanceMetric) {
110
+ case "l2":
111
+ return "vector_l2_ops";
112
+ case "inner_product":
113
+ return "vector_ip_ops";
114
+ case "cosine":
115
+ default:
116
+ return "vector_cosine_ops";
117
+ }
118
+ };
119
+ var scoreFromDistance = (distance, distanceMetric) => {
120
+ if (typeof distance !== "number" || !Number.isFinite(distance)) {
121
+ return 0;
122
+ }
123
+ switch (distanceMetric) {
124
+ case "inner_product":
125
+ return -distance;
126
+ case "l2":
127
+ return 1 / (1 + Math.abs(distance));
128
+ case "cosine":
129
+ default:
130
+ return 1 - distance;
131
+ }
132
+ };
133
+ var createIndexSql = ({
134
+ schemaName,
135
+ chunkTableName,
136
+ distanceMetric,
137
+ index
138
+ }) => {
139
+ if (!index || index.type === "none") {
140
+ return [];
141
+ }
142
+ const qualifiedChunkTable = qualifiedTable(schemaName, chunkTableName);
143
+ const opClass = operatorClassForMetric(distanceMetric);
144
+ const indexName = `${chunkTableName}_embedding_${index.type}_${distanceMetric}_idx`;
145
+ const withParts = [];
146
+ if (index.type === "hnsw") {
147
+ if (Number.isInteger(index.m) && (index.m ?? 0) > 0) {
148
+ withParts.push(`m = ${index.m}`);
149
+ }
150
+ if (Number.isInteger(index.efConstruction) && (index.efConstruction ?? 0) > 0) {
151
+ withParts.push(`ef_construction = ${index.efConstruction}`);
152
+ }
153
+ }
154
+ if (index.type === "ivfflat" && Number.isInteger(index.lists) && (index.lists ?? 0) > 0) {
155
+ withParts.push(`lists = ${index.lists}`);
156
+ }
157
+ const withClause = withParts.length > 0 ? ` WITH (${withParts.join(", ")})` : "";
158
+ return [
159
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${qualifiedChunkTable} USING ${index.type} (embedding ${opClass})${withClause}`
160
+ ];
161
+ };
162
+ var createQuerySessionSql = ({
163
+ index
164
+ }) => {
165
+ if (!index || index.type === "none") {
166
+ return [];
167
+ }
168
+ const sql = [];
169
+ if (index.type === "hnsw") {
170
+ if (Number.isInteger(index.efSearch) && (index.efSearch ?? 0) > 0) {
171
+ sql.push(`SET LOCAL hnsw.ef_search = ${index.efSearch}`);
172
+ }
173
+ if (index.iterativeScan && index.iterativeScan !== "off") {
174
+ sql.push(`SET LOCAL hnsw.iterative_scan = '${escapeLiteral(index.iterativeScan)}'`);
175
+ }
176
+ }
177
+ if (index.type === "ivfflat") {
178
+ if (Number.isInteger(index.probes) && (index.probes ?? 0) > 0) {
179
+ sql.push(`SET LOCAL ivfflat.probes = ${index.probes}`);
180
+ }
181
+ if (Number.isInteger(index.maxProbes) && (index.maxProbes ?? 0) > 0) {
182
+ sql.push(`SET LOCAL ivfflat.max_probes = ${index.maxProbes}`);
183
+ }
184
+ if (index.iterativeScan && index.iterativeScan !== "off") {
185
+ sql.push(`SET LOCAL ivfflat.iterative_scan = '${escapeLiteral(index.iterativeScan)}'`);
186
+ }
187
+ }
188
+ return sql;
189
+ };
190
+ var stageOrder = [
191
+ "extension",
192
+ "schema",
193
+ "table",
194
+ "index"
195
+ ];
196
+ var buildMigrationName = (stage, stageIndex, sql) => {
197
+ const normalized = sql.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 48) || "statement";
198
+ const globalOrder = String(stageOrder.indexOf(stage) + 1).padStart(2, "0");
199
+ const localOrder = String(stageIndex + 1).padStart(3, "0");
200
+ return `${globalOrder}_${stage}_${localOrder}_${normalized}`;
201
+ };
202
+ var createMigrationTableSql = (schemaName, migrationTableName) => `CREATE TABLE IF NOT EXISTS ${qualifiedTable(schemaName, migrationTableName)} (name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`;
203
+ var filterTrackedTableSql = (tableSql, schemaName, migrationTableName) => {
204
+ const migrationTableTarget = qualifiedTable(schemaName, migrationTableName);
205
+ return tableSql.filter((sql) => !sql.includes(migrationTableTarget));
206
+ };
207
+ var createPostgresSchemaPlan = (options) => {
208
+ const schema = resolveSchemaConfig(options ?? {});
209
+ const vector = resolveVectorConfig(options ?? {});
210
+ const qualifiedChunkTable = qualifiedTable(schema.schemaName, schema.chunkTableName);
211
+ const qualifiedMigrationTable = qualifiedTable(schema.schemaName, schema.migrationTableName);
212
+ const extensionSql = vector.autoCreateExtension === false ? [] : [
213
+ `CREATE EXTENSION IF NOT EXISTS ${quoteIdentifier(vector.extensionName)}`
214
+ ];
215
+ const schemaSql = vector.autoCreateSchema === false ? [] : [
216
+ `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(schema.schemaName)}`
217
+ ];
218
+ const tableSql = vector.autoCreateTables === false ? [] : [
219
+ `CREATE TABLE IF NOT EXISTS ${qualifiedChunkTable} (id BIGSERIAL PRIMARY KEY, chunk_id TEXT NOT NULL UNIQUE, text TEXT NOT NULL, title TEXT, source TEXT, metadata JSONB NOT NULL DEFAULT '{}'::jsonb, embedding VECTOR(${vector.dimensions}) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
220
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${schema.chunkTableName}_chunk_id_idx`)} ON ${qualifiedChunkTable} (chunk_id)`,
221
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${schema.chunkTableName}_source_idx`)} ON ${qualifiedChunkTable} (source)`,
222
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${schema.chunkTableName}_metadata_idx`)} ON ${qualifiedChunkTable} USING GIN (metadata)`,
223
+ createMigrationTableSql(schema.schemaName, schema.migrationTableName)
224
+ ];
225
+ const indexSql = vector.autoCreateIndex === false ? [] : createIndexSql({
226
+ schemaName: schema.schemaName,
227
+ chunkTableName: schema.chunkTableName,
228
+ distanceMetric: vector.distanceMetric,
229
+ index: vector.index
230
+ });
231
+ return {
232
+ implementation: "pgvector",
233
+ extensionSql,
234
+ schemaSql,
235
+ tableSql,
236
+ indexSql,
237
+ querySessionSql: createQuerySessionSql({ index: vector.index }),
238
+ migrationTableQualifiedName: qualifiedMigrationTable
239
+ };
240
+ };
241
+ var createPostgresMigrationPlan = (options) => {
242
+ const schema = resolveSchemaConfig(options ?? {});
243
+ const schemaPlan = createPostgresSchemaPlan(options ?? {});
244
+ const bootstrapSql = [];
245
+ if (schemaPlan.schemaSql.length > 0) {
246
+ bootstrapSql.push(...schemaPlan.schemaSql);
247
+ }
248
+ const migrationTableSql = createMigrationTableSql(schema.schemaName, schema.migrationTableName);
249
+ if (!bootstrapSql.includes(migrationTableSql)) {
250
+ bootstrapSql.push(migrationTableSql);
251
+ }
252
+ const migrations = [
253
+ ...schemaPlan.extensionSql.map((sql, index) => ({
254
+ stage: "extension",
255
+ sql,
256
+ stageIndex: index
257
+ })),
258
+ ...filterTrackedTableSql(schemaPlan.tableSql, schema.schemaName, schema.migrationTableName).map((sql, index) => ({
259
+ stage: "table",
260
+ sql,
261
+ stageIndex: index
262
+ })),
263
+ ...schemaPlan.indexSql.map((sql, index) => ({
264
+ stage: "index",
265
+ sql,
266
+ stageIndex: index
267
+ }))
268
+ ].map((entry) => ({
269
+ name: buildMigrationName(entry.stage, entry.stageIndex, entry.sql),
270
+ stage: entry.stage,
271
+ sql: entry.sql
272
+ }));
273
+ return {
274
+ implementation: schemaPlan.implementation,
275
+ schemaName: schema.schemaName,
276
+ migrationTableName: schema.migrationTableName,
277
+ migrationTableQualifiedName: qualifiedTable(schema.schemaName, schema.migrationTableName),
278
+ bootstrapSql,
279
+ migrations,
280
+ schemaPlan
281
+ };
282
+ };
283
+ var createWrappedPostgresClient = (sql, rootSql = sql) => ({
284
+ query: async (queryText, params = []) => {
285
+ const rows = await sql.unsafe(queryText, params);
286
+ return {
287
+ rows,
288
+ rowCount: typeof rows.count === "number" ? rows.count : rows.length
289
+ };
290
+ },
291
+ transaction: async (run) => rootSql.begin(async (transactionSql) => run(createWrappedPostgresClient(transactionSql, transactionSql))),
292
+ close: async () => {
293
+ if (typeof rootSql.end === "function") {
294
+ await rootSql.end({ timeout: 5 });
295
+ }
296
+ }
297
+ });
298
+ var createDefaultPostgresClientFactory = (options) => {
299
+ const connectionString = typeof options.connectionString === "string" ? options.connectionString.trim() : "";
300
+ if (connectionString.length === 0) {
301
+ return;
302
+ }
303
+ let clientPromise;
304
+ return async () => {
305
+ if (!clientPromise) {
306
+ clientPromise = (async () => {
307
+ const postgresModule = await import("postgres");
308
+ const postgres = postgresModule.default;
309
+ const sql = postgres(connectionString, {
310
+ onnotice: () => {},
311
+ ...options.driver ?? {}
312
+ });
313
+ return createWrappedPostgresClient(sql, sql);
314
+ })();
315
+ }
316
+ return clientPromise;
317
+ };
318
+ };
319
+ var resolveClientFactory = (options) => {
320
+ if (typeof options.clientFactory === "function") {
321
+ const { clientFactory } = options;
322
+ return async () => clientFactory();
323
+ }
324
+ if (options.client) {
325
+ const { client } = options;
326
+ return async () => client;
327
+ }
328
+ const defaultFactory = createDefaultPostgresClientFactory(options);
329
+ if (defaultFactory) {
330
+ return defaultFactory;
331
+ }
332
+ return async () => {
333
+ throw new Error(`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: createPostgresRAG requires connectionString, client, or clientFactory.`);
334
+ };
335
+ };
336
+ var buildMetadataFilter = (filter) => {
337
+ if (!filter) {
338
+ return;
339
+ }
340
+ const metadataEntries = Object.entries(filter).filter(([key]) => key !== "chunkId" && key !== "title" && key !== "source");
341
+ if (metadataEntries.length === 0) {
342
+ return;
343
+ }
344
+ return Object.fromEntries(metadataEntries);
345
+ };
346
+ var parseMetadataValue = (value) => {
347
+ if (value === null || value === undefined) {
348
+ return;
349
+ }
350
+ if (typeof value === "string") {
351
+ try {
352
+ const parsed = JSON.parse(value);
353
+ if (parsed && typeof parsed === "object") {
354
+ return parsed;
355
+ }
356
+ } catch {
357
+ return;
358
+ }
359
+ }
360
+ if (typeof value === "object") {
361
+ return value;
362
+ }
363
+ return;
364
+ };
365
+ var createPgvectorStoreStatus = ({
366
+ vector,
367
+ schema,
368
+ diagnostics,
369
+ initialized
370
+ }) => ({
371
+ backend: "postgres",
372
+ vectorMode: "native_pgvector",
373
+ dimensions: vector.dimensions,
374
+ native: {
375
+ requested: true,
376
+ available: initialized && !diagnostics.lastInitError,
377
+ active: initialized && !diagnostics.lastInitError,
378
+ mode: "pgvector",
379
+ extensionName: vector.extensionName,
380
+ schemaName: schema.schemaName,
381
+ tableName: schema.chunkTableName,
382
+ distanceMetric: vector.distanceMetric,
383
+ indexType: vector.index.type,
384
+ fallbackReason: diagnostics.fallbackReason,
385
+ lastInitError: diagnostics.lastInitError,
386
+ lastQueryError: diagnostics.lastQueryError,
387
+ lastUpsertError: diagnostics.lastUpsertError,
388
+ lastMigrationError: diagnostics.lastMigrationError
389
+ }
390
+ });
391
+ var getAppliedMigrationNames = async (client, migrationPlan) => {
392
+ const result = await client.query(`SELECT name FROM ${migrationPlan.migrationTableQualifiedName} ORDER BY name ASC`);
393
+ return new Set(result.rows.map((row) => String(row.name)));
394
+ };
395
+ var insertAppliedMigration = async (client, migrationPlan, name) => {
396
+ await client.query(`INSERT INTO ${migrationPlan.migrationTableQualifiedName} (name) VALUES ($1) ON CONFLICT (name) DO NOTHING`, [name]);
397
+ };
398
+ var executeMigrationSequence = async (client, migrationPlan, migrations) => {
399
+ const appliedNames = [];
400
+ for (const migration of migrations) {
401
+ await client.query(migration.sql);
402
+ await insertAppliedMigration(client, migrationPlan, migration.name);
403
+ appliedNames.push(migration.name);
404
+ }
405
+ return appliedNames;
406
+ };
407
+ var applyPostgresMigrations = async (options, applyOptions = {}) => {
408
+ const migrationPlan = createPostgresMigrationPlan(options ?? {});
409
+ const injectedClient = applyOptions.client;
410
+ const getClient = injectedClient ? async () => injectedClient : resolveClientFactory(options ?? {});
411
+ const client = await getClient();
412
+ for (const sql of migrationPlan.bootstrapSql) {
413
+ await client.query(sql);
414
+ }
415
+ const alreadyApplied = await getAppliedMigrationNames(client, migrationPlan);
416
+ const pendingMigrations = migrationPlan.migrations.filter((migration) => !alreadyApplied.has(migration.name));
417
+ const skippedNames = migrationPlan.migrations.filter((migration) => alreadyApplied.has(migration.name)).map((migration) => migration.name);
418
+ if (applyOptions.dryRun === true) {
419
+ return {
420
+ migrationPlan,
421
+ appliedNames: [],
422
+ skippedNames,
423
+ pendingNames: pendingMigrations.map((migration) => migration.name),
424
+ appliedCount: 0,
425
+ pendingCount: pendingMigrations.length,
426
+ dryRun: true
427
+ };
428
+ }
429
+ const run = async (activeClient) => {
430
+ const names = await executeMigrationSequence(activeClient, migrationPlan, pendingMigrations);
431
+ return {
432
+ migrationPlan,
433
+ appliedNames: names,
434
+ skippedNames,
435
+ pendingNames: pendingMigrations.map((migration) => migration.name),
436
+ appliedCount: names.length,
437
+ pendingCount: pendingMigrations.length,
438
+ dryRun: false
439
+ };
440
+ };
441
+ if (typeof client.transaction === "function" && pendingMigrations.length > 0) {
442
+ return client.transaction(async (transactionClient) => run(transactionClient));
443
+ }
444
+ return run(client);
445
+ };
446
+ var applyPostgresSchemaPlan = applyPostgresMigrations;
447
+ var createPgvectorStore = (options) => {
448
+ const vector = resolveVectorConfig(options ?? {});
449
+ const schema = resolveSchemaConfig(options ?? {});
450
+ const plan = createPostgresSchemaPlan(options ?? {});
451
+ const getClient = resolveClientFactory(options ?? {});
452
+ const diagnostics = {
453
+ fallbackReason: undefined,
454
+ lastInitError: undefined,
455
+ lastQueryError: undefined,
456
+ lastUpsertError: undefined,
457
+ lastMigrationError: undefined
458
+ };
459
+ let initialized = false;
460
+ let initPromise;
461
+ const ensureInitialized = async () => {
462
+ if (initialized) {
463
+ return;
464
+ }
465
+ if (!initPromise) {
466
+ initPromise = (async () => {
467
+ try {
468
+ const client = await getClient();
469
+ await applyPostgresMigrations(options ?? {}, { client });
470
+ initialized = true;
471
+ diagnostics.lastInitError = undefined;
472
+ diagnostics.lastMigrationError = undefined;
473
+ diagnostics.fallbackReason = undefined;
474
+ } catch (error) {
475
+ initialized = false;
476
+ const message = error instanceof Error ? error.message : String(error);
477
+ diagnostics.lastInitError = message;
478
+ diagnostics.lastMigrationError = message;
479
+ diagnostics.fallbackReason = message;
480
+ throw error;
481
+ }
482
+ })();
483
+ }
484
+ return initPromise;
485
+ };
486
+ const embed = async (input) => {
487
+ if (typeof options.embedding === "function") {
488
+ const result = await options.embedding(input);
489
+ return normalizeVector(result);
490
+ }
491
+ return normalizeVector([
492
+ ...createRAGVector(input.text, vector.dimensions)
493
+ ]);
494
+ };
495
+ const query = async (input) => {
496
+ await ensureInitialized();
497
+ const client = await getClient();
498
+ const params = [];
499
+ const qualifiedChunkTable = qualifiedTable(schema.schemaName, schema.chunkTableName);
500
+ const operator = operatorForMetric(vector.distanceMetric);
501
+ const vectorPlaceholder = makePlaceholder(params, vectorLiteral(normalizeVector(input.queryVector)), "vector");
502
+ const limitPlaceholder = makePlaceholder(params, input.topK);
503
+ const whereParts = [];
504
+ const filter = input.filter;
505
+ if (filter?.chunkId !== undefined) {
506
+ whereParts.push(`chunk_id = ${makePlaceholder(params, filter.chunkId)}`);
507
+ }
508
+ if (filter?.title !== undefined) {
509
+ whereParts.push(`title = ${makePlaceholder(params, filter.title)}`);
510
+ }
511
+ if (filter?.source !== undefined) {
512
+ whereParts.push(`source = ${makePlaceholder(params, filter.source)}`);
513
+ }
514
+ const metadataFilter = buildMetadataFilter(filter);
515
+ if (metadataFilter) {
516
+ whereParts.push(`metadata @> ${makePlaceholder(params, JSON.stringify(metadataFilter), "jsonb")}`);
517
+ }
518
+ const whereSql = whereParts.length > 0 ? `WHERE ${whereParts.join(" AND ")}` : "";
519
+ const sessionSql = plan.querySessionSql;
520
+ const selectSql = `SELECT chunk_id, text, title, source, metadata, embedding ${operator} ${vectorPlaceholder} AS distance FROM ${qualifiedChunkTable} ${whereSql} ORDER BY distance ASC LIMIT ${limitPlaceholder}`;
521
+ try {
522
+ for (const sql of sessionSql) {
523
+ await client.query(sql);
524
+ }
525
+ const result = await client.query(selectSql, params);
526
+ return result.rows.map((row) => ({
527
+ chunkId: row.chunk_id,
528
+ chunkText: row.text,
529
+ title: row.title ?? undefined,
530
+ source: row.source ?? undefined,
531
+ metadata: parseMetadataValue(row.metadata),
532
+ score: scoreFromDistance(Number(row.distance), vector.distanceMetric)
533
+ }));
534
+ } catch (error) {
535
+ diagnostics.lastQueryError = error instanceof Error ? error.message : String(error);
536
+ throw error;
537
+ }
538
+ };
539
+ const upsert = async (input) => {
540
+ await ensureInitialized();
541
+ const client = await getClient();
542
+ const qualifiedChunkTable = qualifiedTable(schema.schemaName, schema.chunkTableName);
543
+ const sql = `INSERT INTO ${qualifiedChunkTable} (chunk_id, text, title, source, metadata, embedding, updated_at) VALUES ($1, $2, $3, $4, $5::jsonb, $6::vector, NOW()) ON CONFLICT (chunk_id) DO UPDATE SET text = EXCLUDED.text, title = EXCLUDED.title, source = EXCLUDED.source, metadata = EXCLUDED.metadata, embedding = EXCLUDED.embedding, updated_at = NOW()`;
544
+ try {
545
+ for (const chunk of input.chunks) {
546
+ const vectorValue = Array.isArray(chunk.embedding) && chunk.embedding.length > 0 ? normalizeVector(chunk.embedding) : await embed({ text: chunk.text });
547
+ await client.query(sql, [
548
+ chunk.chunkId,
549
+ chunk.text,
550
+ chunk.title ?? null,
551
+ chunk.source ?? null,
552
+ JSON.stringify(chunk.metadata ?? {}),
553
+ vectorLiteral(vectorValue)
554
+ ]);
555
+ }
556
+ } catch (error) {
557
+ diagnostics.lastUpsertError = error instanceof Error ? error.message : String(error);
558
+ throw error;
559
+ }
560
+ };
561
+ const clear = async () => {
562
+ await ensureInitialized();
563
+ const client = await getClient();
564
+ const qualifiedChunkTable = qualifiedTable(schema.schemaName, schema.chunkTableName);
565
+ await client.query(`DELETE FROM ${qualifiedChunkTable}`);
566
+ };
567
+ return {
568
+ embed,
569
+ query,
570
+ upsert,
571
+ clear,
572
+ getCapabilities: () => ({
573
+ backend: "postgres",
574
+ persistence: "external",
575
+ nativeVectorSearch: true,
576
+ serverSideFiltering: true,
577
+ streamingIngestStatus: false
578
+ }),
579
+ getStatus: () => createPgvectorStoreStatus({
580
+ vector,
581
+ schema,
582
+ diagnostics,
583
+ initialized
584
+ })
585
+ };
586
+ };
587
+ var createPostgresRAGCollection = (options) => createRAGCollection({
588
+ store: createPgvectorStore(options)
589
+ });
590
+ var createPostgresRAG = (options) => {
591
+ const store = createPgvectorStore(options);
592
+ const collection = createRAGCollection({ store });
593
+ const schemaPlan = createPostgresSchemaPlan(options);
594
+ const migrationPlan = createPostgresMigrationPlan(options);
595
+ return {
596
+ store,
597
+ collection,
598
+ getStatus: () => store.getStatus?.(),
599
+ getCapabilities: () => store.getCapabilities?.(),
600
+ getSchemaPlan: () => schemaPlan,
601
+ getMigrationPlan: () => migrationPlan,
602
+ applyMigrations: (applyOptions) => applyPostgresMigrations(options, applyOptions)
603
+ };
604
+ };
605
+ var createPostgreSQLRAG = createPostgresRAG;
606
+ export {
607
+ createPostgresSchemaPlan,
608
+ createPostgresRAGCollection,
609
+ createPostgresRAG,
610
+ createPostgresMigrationPlan,
611
+ createPostgreSQLRAG,
612
+ createPgvectorStore,
613
+ applyPostgresSchemaPlan,
614
+ applyPostgresMigrations,
615
+ POSTGRESQL_RAG_IMPLEMENTATIONS,
616
+ PGVECTOR_INDEX_TYPES,
617
+ PGVECTOR_DISTANCE_METRICS,
618
+ ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME
619
+ };
620
+
621
+ //# debugId=22931C2F3EFA23C264756E2164756E21
622
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": [
5
+ "import type {\n\tRAGBackendCapabilities,\n\tRAGCollection,\n\tRAGQueryInput,\n\tRAGQueryResult,\n\tRAGUpsertInput,\n\tRAGVectorStore,\n\tRAGVectorStoreStatus\n} from '@absolutejs/rag';\nimport {\n\tcreateRAGCollection,\n\tcreateRAGVector,\n\tnormalizeVector\n} from '@absolutejs/rag';\n\nexport const ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME = '@absolutejs/rag-postgres';\n\nexport const POSTGRESQL_RAG_IMPLEMENTATIONS = ['pgvector'] as const;\nexport const PGVECTOR_DISTANCE_METRICS = [\n\t'cosine',\n\t'l2',\n\t'inner_product'\n] as const;\nexport const PGVECTOR_INDEX_TYPES = ['none', 'hnsw', 'ivfflat'] as const;\n\nexport type PostgreSQLRAGVectorImplementation = 'pgvector';\nexport type PgvectorDistanceMetric = 'cosine' | 'l2' | 'inner_product';\nexport type PgvectorIndexType = 'none' | 'hnsw' | 'ivfflat';\n\nexport type PostgreSQLRAGClient = {\n\tquery: <TRow = Record<string, unknown>>(\n\t\tsql: string,\n\t\tparams?: unknown[]\n\t) => Promise<{\n\t\trows: TRow[];\n\t\trowCount?: number;\n\t}>;\n\ttransaction?: <T>(\n\t\trun: (client: PostgreSQLRAGClient) => Promise<T>\n\t) => Promise<T>;\n\tclose?: () => Promise<void>;\n};\n\nexport type PostgreSQLRAGClientFactory = () =>\n\t| Promise<PostgreSQLRAGClient>\n\t| PostgreSQLRAGClient;\n\nexport type PostgreSQLRAGSchemaConfig = {\n\tschemaName?: string;\n\tchunkTableName?: string;\n\tmigrationTableName?: string;\n};\n\nexport type PgvectorHNSWConfig = {\n\ttype: 'hnsw';\n\tm?: number;\n\tefConstruction?: number;\n\tefSearch?: number;\n\titerativeScan?: 'off' | 'strict_order' | 'relaxed_order';\n};\n\nexport type PgvectorIVFFlatConfig = {\n\ttype: 'ivfflat';\n\tlists?: number;\n\tprobes?: number;\n\tmaxProbes?: number;\n\titerativeScan?: 'off' | 'strict_order' | 'relaxed_order';\n};\n\nexport type PgvectorNoIndexConfig = {\n\ttype: 'none';\n};\n\nexport type PgvectorIndexConfig =\n\t| PgvectorNoIndexConfig\n\t| PgvectorHNSWConfig\n\t| PgvectorIVFFlatConfig;\n\nexport type PgvectorConfig = {\n\tprovider: 'pgvector';\n\tdimensions: number;\n\tdistanceMetric?: PgvectorDistanceMetric;\n\textensionName?: 'vector' | string;\n\tautoCreateExtension?: boolean;\n\tautoCreateSchema?: boolean;\n\tautoCreateTables?: boolean;\n\tautoCreateIndex?: boolean;\n\tindex?: PgvectorIndexConfig;\n};\n\nexport type PostgreSQLDriverOptions = {\n\tmax?: number;\n\tprepare?: boolean;\n\tidle_timeout?: number;\n\tconnect_timeout?: number;\n\tmax_lifetime?: number;\n\tssl?: boolean | 'require' | 'allow' | 'prefer' | 'verify-full';\n};\n\nexport type PostgreSQLRAGOptions = {\n\tconnectionString?: string;\n\tclient?: PostgreSQLRAGClient;\n\tclientFactory?: PostgreSQLRAGClientFactory;\n\tdriver?: PostgreSQLDriverOptions;\n\tschema?: PostgreSQLRAGSchemaConfig;\n\tvector: PgvectorConfig;\n\tembedding?: RAGVectorStore['embed'];\n};\n\nexport type PostgreSQLSchemaPlan = {\n\timplementation: PostgreSQLRAGVectorImplementation;\n\textensionSql: string[];\n\tschemaSql: string[];\n\ttableSql: string[];\n\tindexSql: string[];\n\tquerySessionSql: string[];\n\tmigrationTableQualifiedName: string;\n};\n\nexport type PostgreSQLMigrationStage = 'extension' | 'table' | 'index';\n\nexport type PostgreSQLMigrationEntry = {\n\tname: string;\n\tstage: PostgreSQLMigrationStage;\n\tsql: string;\n};\n\nexport type PostgreSQLMigrationPlan = {\n\timplementation: PostgreSQLRAGVectorImplementation;\n\tschemaName: string;\n\tmigrationTableName: string;\n\tmigrationTableQualifiedName: string;\n\tbootstrapSql: string[];\n\tmigrations: PostgreSQLMigrationEntry[];\n\tschemaPlan: PostgreSQLSchemaPlan;\n};\n\nexport type PostgreSQLApplyMigrationsOptions = {\n\tclient?: PostgreSQLRAGClient;\n\tdryRun?: boolean;\n};\n\nexport type PostgreSQLApplyMigrationsResult = {\n\tmigrationPlan: PostgreSQLMigrationPlan;\n\tappliedNames: string[];\n\tskippedNames: string[];\n\tpendingNames: string[];\n\tappliedCount: number;\n\tpendingCount: number;\n\tdryRun: boolean;\n};\n\nexport type PostgreSQLRAG = {\n\tstore: RAGVectorStore;\n\tcollection: RAGCollection;\n\tgetStatus: () => RAGVectorStoreStatus | undefined;\n\tgetCapabilities: () => RAGBackendCapabilities | undefined;\n\tgetSchemaPlan: () => PostgreSQLSchemaPlan;\n\tgetMigrationPlan: () => PostgreSQLMigrationPlan;\n\tapplyMigrations: (\n\t\toptions?: PostgreSQLApplyMigrationsOptions\n\t) => Promise<PostgreSQLApplyMigrationsResult>;\n};\n\ntype ResolvedSchemaConfig = {\n\tschemaName: string;\n\tchunkTableName: string;\n\tmigrationTableName: string;\n};\n\ntype ResolvedPgvectorConfig = PgvectorConfig & {\n\tdimensions: number;\n\tdistanceMetric: PgvectorDistanceMetric;\n\textensionName: string;\n\tindex: PgvectorIndexConfig;\n};\n\ntype PgvectorDiagnostics = {\n\tfallbackReason: string | undefined;\n\tlastInitError: string | undefined;\n\tlastQueryError: string | undefined;\n\tlastUpsertError: string | undefined;\n\tlastMigrationError: string | undefined;\n};\n\nconst DEFAULT_SCHEMA_NAME = 'absolute_rag';\nconst DEFAULT_CHUNK_TABLE_NAME = 'chunks';\nconst DEFAULT_MIGRATION_TABLE_NAME = 'migrations';\nconst DEFAULT_DIMENSIONS = 1536;\n\nconst IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nconst assertIdentifier = (value: unknown, label: string): void => {\n\tif (typeof value !== 'string' || !IDENTIFIER_RE.test(value)) {\n\t\tthrow new Error(\n\t\t\t`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: invalid ${label} \"${String(\n\t\t\t\tvalue\n\t\t\t)}\"`\n\t\t);\n\t}\n};\n\nconst quoteIdentifier = (value: string): string => {\n\tassertIdentifier(value, 'identifier');\n\n\treturn `\"${value}\"`;\n};\n\nconst qualifiedTable = (schemaName: string, tableName: string): string =>\n\t`${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;\n\nconst escapeLiteral = (value: string): string => value.replace(/'/g, \"''\");\n\nconst vectorLiteral = (vector: unknown): string => {\n\tif (!Array.isArray(vector) || vector.length === 0) {\n\t\tthrow new Error(\n\t\t\t`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: vector values must be a non-empty array`\n\t\t);\n\t}\n\n\treturn `[${vector\n\t\t.map((value) => {\n\t\t\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: vector values must be finite numbers`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn String(value);\n\t\t})\n\t\t.join(',')}]`;\n};\n\nconst makePlaceholder = (\n\tparams: unknown[],\n\tvalue: unknown,\n\tcast = ''\n): string => {\n\tparams.push(value);\n\tconst suffix = cast ? `::${cast}` : '';\n\n\treturn `$${params.length}${suffix}`;\n};\n\nconst normalizeMetric = (\n\tmetric: PgvectorDistanceMetric | undefined\n): PgvectorDistanceMetric => {\n\tif (metric === 'l2' || metric === 'inner_product') {\n\t\treturn metric;\n\t}\n\n\treturn 'cosine';\n};\n\nconst normalizeIndex = (\n\tindex: PgvectorIndexConfig | undefined\n): PgvectorIndexConfig => {\n\tif (!index || index.type === undefined) {\n\t\treturn { type: 'none' };\n\t}\n\n\tif (\n\t\tindex.type === 'hnsw' ||\n\t\tindex.type === 'ivfflat' ||\n\t\tindex.type === 'none'\n\t) {\n\t\treturn index;\n\t}\n\n\tthrow new Error(\n\t\t`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: unsupported pgvector index type \"${String(\n\t\t\t(index as { type: unknown }).type\n\t\t)}\"`\n\t);\n};\n\nconst resolveSchemaConfig = (\n\toptions: Partial<PostgreSQLRAGOptions>\n): ResolvedSchemaConfig => {\n\tconst schemaName = options.schema?.schemaName ?? DEFAULT_SCHEMA_NAME;\n\tconst chunkTableName =\n\t\toptions.schema?.chunkTableName ?? DEFAULT_CHUNK_TABLE_NAME;\n\tconst migrationTableName =\n\t\toptions.schema?.migrationTableName ?? DEFAULT_MIGRATION_TABLE_NAME;\n\n\tassertIdentifier(schemaName, 'schema name');\n\tassertIdentifier(chunkTableName, 'chunk table name');\n\tassertIdentifier(migrationTableName, 'migration table name');\n\n\treturn {\n\t\tschemaName,\n\t\tchunkTableName,\n\t\tmigrationTableName\n\t};\n};\n\nconst resolveVectorConfig = (\n\toptions: Partial<PostgreSQLRAGOptions>\n): ResolvedPgvectorConfig => {\n\tconst vector = options?.vector;\n\n\tif (!vector || vector.provider !== 'pgvector') {\n\t\tthrow new Error(\n\t\t\t`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: PostgreSQL RAG currently requires vector.provider = \"pgvector\"`\n\t\t);\n\t}\n\n\tconst dimensions = vector.dimensions ?? DEFAULT_DIMENSIONS;\n\tif (!Number.isInteger(dimensions) || dimensions <= 0) {\n\t\tthrow new Error(\n\t\t\t`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: dimensions must be a positive integer`\n\t\t);\n\t}\n\n\tconst distanceMetric = normalizeMetric(vector.distanceMetric);\n\tconst index = normalizeIndex(vector.index);\n\n\treturn {\n\t\t...vector,\n\t\tdimensions,\n\t\tdistanceMetric,\n\t\textensionName: vector.extensionName ?? 'vector',\n\t\tindex\n\t};\n};\n\nconst operatorForMetric = (distanceMetric: PgvectorDistanceMetric): string => {\n\tswitch (distanceMetric) {\n\t\tcase 'l2':\n\t\t\treturn '<->';\n\t\tcase 'inner_product':\n\t\t\treturn '<#>';\n\t\tcase 'cosine':\n\t\tdefault:\n\t\t\treturn '<=>';\n\t}\n};\n\nconst operatorClassForMetric = (\n\tdistanceMetric: PgvectorDistanceMetric\n): string => {\n\tswitch (distanceMetric) {\n\t\tcase 'l2':\n\t\t\treturn 'vector_l2_ops';\n\t\tcase 'inner_product':\n\t\t\treturn 'vector_ip_ops';\n\t\tcase 'cosine':\n\t\tdefault:\n\t\t\treturn 'vector_cosine_ops';\n\t}\n};\n\nconst scoreFromDistance = (\n\tdistance: unknown,\n\tdistanceMetric: PgvectorDistanceMetric\n): number => {\n\tif (typeof distance !== 'number' || !Number.isFinite(distance)) {\n\t\treturn 0;\n\t}\n\n\tswitch (distanceMetric) {\n\t\tcase 'inner_product':\n\t\t\treturn -distance;\n\t\tcase 'l2':\n\t\t\treturn 1 / (1 + Math.abs(distance));\n\t\tcase 'cosine':\n\t\tdefault:\n\t\t\treturn 1 - distance;\n\t}\n};\n\nconst createIndexSql = ({\n\tschemaName,\n\tchunkTableName,\n\tdistanceMetric,\n\tindex\n}: {\n\tschemaName: string;\n\tchunkTableName: string;\n\tdistanceMetric: PgvectorDistanceMetric;\n\tindex: PgvectorIndexConfig;\n}): string[] => {\n\tif (!index || index.type === 'none') {\n\t\treturn [];\n\t}\n\n\tconst qualifiedChunkTable = qualifiedTable(schemaName, chunkTableName);\n\tconst opClass = operatorClassForMetric(distanceMetric);\n\tconst indexName = `${chunkTableName}_embedding_${index.type}_${distanceMetric}_idx`;\n\tconst withParts: string[] = [];\n\n\tif (index.type === 'hnsw') {\n\t\tif (Number.isInteger(index.m) && (index.m ?? 0) > 0) {\n\t\t\twithParts.push(`m = ${index.m}`);\n\t\t}\n\t\tif (\n\t\t\tNumber.isInteger(index.efConstruction) &&\n\t\t\t(index.efConstruction ?? 0) > 0\n\t\t) {\n\t\t\twithParts.push(`ef_construction = ${index.efConstruction}`);\n\t\t}\n\t}\n\n\tif (\n\t\tindex.type === 'ivfflat' &&\n\t\tNumber.isInteger(index.lists) &&\n\t\t(index.lists ?? 0) > 0\n\t) {\n\t\twithParts.push(`lists = ${index.lists}`);\n\t}\n\n\tconst withClause =\n\t\twithParts.length > 0 ? ` WITH (${withParts.join(', ')})` : '';\n\n\treturn [\n\t\t`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(\n\t\t\tindexName\n\t\t)} ON ${qualifiedChunkTable} USING ${index.type} (embedding ${opClass})${withClause}`\n\t];\n};\n\nconst createQuerySessionSql = ({\n\tindex\n}: {\n\tindex: PgvectorIndexConfig;\n}): string[] => {\n\tif (!index || index.type === 'none') {\n\t\treturn [];\n\t}\n\n\tconst sql: string[] = [];\n\n\tif (index.type === 'hnsw') {\n\t\tif (Number.isInteger(index.efSearch) && (index.efSearch ?? 0) > 0) {\n\t\t\tsql.push(`SET LOCAL hnsw.ef_search = ${index.efSearch}`);\n\t\t}\n\t\tif (index.iterativeScan && index.iterativeScan !== 'off') {\n\t\t\tsql.push(\n\t\t\t\t`SET LOCAL hnsw.iterative_scan = '${escapeLiteral(\n\t\t\t\t\tindex.iterativeScan\n\t\t\t\t)}'`\n\t\t\t);\n\t\t}\n\t}\n\n\tif (index.type === 'ivfflat') {\n\t\tif (Number.isInteger(index.probes) && (index.probes ?? 0) > 0) {\n\t\t\tsql.push(`SET LOCAL ivfflat.probes = ${index.probes}`);\n\t\t}\n\t\tif (Number.isInteger(index.maxProbes) && (index.maxProbes ?? 0) > 0) {\n\t\t\tsql.push(`SET LOCAL ivfflat.max_probes = ${index.maxProbes}`);\n\t\t}\n\t\tif (index.iterativeScan && index.iterativeScan !== 'off') {\n\t\t\tsql.push(\n\t\t\t\t`SET LOCAL ivfflat.iterative_scan = '${escapeLiteral(\n\t\t\t\t\tindex.iterativeScan\n\t\t\t\t)}'`\n\t\t\t);\n\t\t}\n\t}\n\n\treturn sql;\n};\n\nconst stageOrder: PostgreSQLMigrationStage[] = [\n\t'extension',\n\t'schema' as PostgreSQLMigrationStage,\n\t'table',\n\t'index'\n];\n\nconst buildMigrationName = (\n\tstage: PostgreSQLMigrationStage,\n\tstageIndex: number,\n\tsql: string\n): string => {\n\tconst normalized =\n\t\tsql\n\t\t\t.toLowerCase()\n\t\t\t.replace(/[^a-z0-9]+/g, '_')\n\t\t\t.replace(/^_+|_+$/g, '')\n\t\t\t.slice(0, 48) || 'statement';\n\tconst globalOrder = String(stageOrder.indexOf(stage) + 1).padStart(2, '0');\n\tconst localOrder = String(stageIndex + 1).padStart(3, '0');\n\n\treturn `${globalOrder}_${stage}_${localOrder}_${normalized}`;\n};\n\nconst createMigrationTableSql = (\n\tschemaName: string,\n\tmigrationTableName: string\n): string =>\n\t`CREATE TABLE IF NOT EXISTS ${qualifiedTable(\n\t\tschemaName,\n\t\tmigrationTableName\n\t)} (name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`;\n\nconst filterTrackedTableSql = (\n\ttableSql: string[],\n\tschemaName: string,\n\tmigrationTableName: string\n): string[] => {\n\tconst migrationTableTarget = qualifiedTable(schemaName, migrationTableName);\n\n\treturn tableSql.filter((sql) => !sql.includes(migrationTableTarget));\n};\n\nexport const createPostgresSchemaPlan = (\n\toptions: PostgreSQLRAGOptions\n): PostgreSQLSchemaPlan => {\n\tconst schema = resolveSchemaConfig(options ?? {});\n\tconst vector = resolveVectorConfig(options ?? {});\n\tconst qualifiedChunkTable = qualifiedTable(\n\t\tschema.schemaName,\n\t\tschema.chunkTableName\n\t);\n\tconst qualifiedMigrationTable = qualifiedTable(\n\t\tschema.schemaName,\n\t\tschema.migrationTableName\n\t);\n\n\tconst extensionSql =\n\t\tvector.autoCreateExtension === false\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`CREATE EXTENSION IF NOT EXISTS ${quoteIdentifier(\n\t\t\t\t\t\tvector.extensionName\n\t\t\t\t\t)}`\n\t\t\t\t];\n\n\tconst schemaSql =\n\t\tvector.autoCreateSchema === false\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(\n\t\t\t\t\t\tschema.schemaName\n\t\t\t\t\t)}`\n\t\t\t\t];\n\n\tconst tableSql =\n\t\tvector.autoCreateTables === false\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`CREATE TABLE IF NOT EXISTS ${qualifiedChunkTable} (id BIGSERIAL PRIMARY KEY, chunk_id TEXT NOT NULL UNIQUE, text TEXT NOT NULL, title TEXT, source TEXT, metadata JSONB NOT NULL DEFAULT '{}'::jsonb, embedding VECTOR(${vector.dimensions}) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(\n\t\t\t\t\t\t`${schema.chunkTableName}_chunk_id_idx`\n\t\t\t\t\t)} ON ${qualifiedChunkTable} (chunk_id)`,\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(\n\t\t\t\t\t\t`${schema.chunkTableName}_source_idx`\n\t\t\t\t\t)} ON ${qualifiedChunkTable} (source)`,\n\t\t\t\t\t`CREATE INDEX IF NOT EXISTS ${quoteIdentifier(\n\t\t\t\t\t\t`${schema.chunkTableName}_metadata_idx`\n\t\t\t\t\t)} ON ${qualifiedChunkTable} USING GIN (metadata)`,\n\t\t\t\t\tcreateMigrationTableSql(\n\t\t\t\t\t\tschema.schemaName,\n\t\t\t\t\t\tschema.migrationTableName\n\t\t\t\t\t)\n\t\t\t\t];\n\n\tconst indexSql =\n\t\tvector.autoCreateIndex === false\n\t\t\t? []\n\t\t\t: createIndexSql({\n\t\t\t\t\tschemaName: schema.schemaName,\n\t\t\t\t\tchunkTableName: schema.chunkTableName,\n\t\t\t\t\tdistanceMetric: vector.distanceMetric,\n\t\t\t\t\tindex: vector.index\n\t\t\t\t});\n\n\treturn {\n\t\timplementation: 'pgvector',\n\t\textensionSql,\n\t\tschemaSql,\n\t\ttableSql,\n\t\tindexSql,\n\t\tquerySessionSql: createQuerySessionSql({ index: vector.index }),\n\t\tmigrationTableQualifiedName: qualifiedMigrationTable\n\t};\n};\n\nexport const createPostgresMigrationPlan = (\n\toptions: PostgreSQLRAGOptions\n): PostgreSQLMigrationPlan => {\n\tconst schema = resolveSchemaConfig(options ?? {});\n\tconst schemaPlan = createPostgresSchemaPlan(options ?? ({} as PostgreSQLRAGOptions));\n\tconst bootstrapSql: string[] = [];\n\n\tif (schemaPlan.schemaSql.length > 0) {\n\t\tbootstrapSql.push(...schemaPlan.schemaSql);\n\t}\n\n\tconst migrationTableSql = createMigrationTableSql(\n\t\tschema.schemaName,\n\t\tschema.migrationTableName\n\t);\n\tif (!bootstrapSql.includes(migrationTableSql)) {\n\t\tbootstrapSql.push(migrationTableSql);\n\t}\n\n\tconst migrations: PostgreSQLMigrationEntry[] = [\n\t\t...schemaPlan.extensionSql.map((sql, index) => ({\n\t\t\tstage: 'extension' as PostgreSQLMigrationStage,\n\t\t\tsql,\n\t\t\tstageIndex: index\n\t\t})),\n\t\t...filterTrackedTableSql(\n\t\t\tschemaPlan.tableSql,\n\t\t\tschema.schemaName,\n\t\t\tschema.migrationTableName\n\t\t).map((sql, index) => ({\n\t\t\tstage: 'table' as PostgreSQLMigrationStage,\n\t\t\tsql,\n\t\t\tstageIndex: index\n\t\t})),\n\t\t...schemaPlan.indexSql.map((sql, index) => ({\n\t\t\tstage: 'index' as PostgreSQLMigrationStage,\n\t\t\tsql,\n\t\t\tstageIndex: index\n\t\t}))\n\t].map((entry) => ({\n\t\tname: buildMigrationName(entry.stage, entry.stageIndex, entry.sql),\n\t\tstage: entry.stage,\n\t\tsql: entry.sql\n\t}));\n\n\treturn {\n\t\timplementation: schemaPlan.implementation,\n\t\tschemaName: schema.schemaName,\n\t\tmigrationTableName: schema.migrationTableName,\n\t\tmigrationTableQualifiedName: qualifiedTable(\n\t\t\tschema.schemaName,\n\t\t\tschema.migrationTableName\n\t\t),\n\t\tbootstrapSql,\n\t\tmigrations,\n\t\tschemaPlan\n\t};\n};\n\ntype RawPostgresClient = {\n\tunsafe: (\n\t\tqueryText: string,\n\t\tparams?: unknown[]\n\t) => Promise<unknown[] & { count?: number }>;\n\tbegin: <T>(run: (transactionSql: RawPostgresClient) => Promise<T>) => Promise<T>;\n\tend?: (options?: { timeout?: number }) => Promise<void>;\n};\n\nconst createWrappedPostgresClient = (\n\tsql: RawPostgresClient,\n\trootSql: RawPostgresClient = sql\n): PostgreSQLRAGClient => ({\n\tquery: async <TRow = Record<string, unknown>>(\n\t\tqueryText: string,\n\t\tparams: unknown[] = []\n\t) => {\n\t\tconst rows = await sql.unsafe(queryText, params);\n\n\t\treturn {\n\t\t\trows: rows as TRow[],\n\t\t\trowCount: typeof rows.count === 'number' ? rows.count : rows.length\n\t\t};\n\t},\n\ttransaction: async <T>(run: (client: PostgreSQLRAGClient) => Promise<T>) =>\n\t\trootSql.begin(async (transactionSql) =>\n\t\t\trun(createWrappedPostgresClient(transactionSql, transactionSql))\n\t\t),\n\tclose: async () => {\n\t\tif (typeof rootSql.end === 'function') {\n\t\t\tawait rootSql.end({ timeout: 5 });\n\t\t}\n\t}\n});\n\nconst createDefaultPostgresClientFactory = (\n\toptions: PostgreSQLRAGOptions\n): (() => Promise<PostgreSQLRAGClient>) | undefined => {\n\tconst connectionString =\n\t\ttypeof options.connectionString === 'string'\n\t\t\t? options.connectionString.trim()\n\t\t\t: '';\n\n\tif (connectionString.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tlet clientPromise: Promise<PostgreSQLRAGClient> | undefined;\n\n\treturn async () => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tconst postgresModule = await import('postgres');\n\t\t\t\tconst postgres = postgresModule.default;\n\t\t\t\tconst sql = postgres(connectionString, {\n\t\t\t\t\tonnotice: () => {},\n\t\t\t\t\t...(options.driver ?? {})\n\t\t\t\t}) as unknown as RawPostgresClient;\n\n\t\t\t\treturn createWrappedPostgresClient(sql, sql);\n\t\t\t})();\n\t\t}\n\n\t\treturn clientPromise;\n\t};\n};\n\nconst resolveClientFactory = (\n\toptions: PostgreSQLRAGOptions\n): (() => Promise<PostgreSQLRAGClient>) => {\n\tif (typeof options.clientFactory === 'function') {\n\t\tconst { clientFactory } = options;\n\n\t\treturn async () => clientFactory();\n\t}\n\n\tif (options.client) {\n\t\tconst { client } = options;\n\n\t\treturn async () => client;\n\t}\n\n\tconst defaultFactory = createDefaultPostgresClientFactory(options);\n\tif (defaultFactory) {\n\t\treturn defaultFactory;\n\t}\n\n\treturn async () => {\n\t\tthrow new Error(\n\t\t\t`${ABSOLUTE_POSTGRESQL_RAG_PACKAGE_NAME}: createPostgresRAG requires connectionString, client, or clientFactory.`\n\t\t);\n\t};\n};\n\nconst buildMetadataFilter = (\n\tfilter: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined => {\n\tif (!filter) {\n\t\treturn undefined;\n\t}\n\n\tconst metadataEntries = Object.entries(filter).filter(\n\t\t([key]) => key !== 'chunkId' && key !== 'title' && key !== 'source'\n\t);\n\n\tif (metadataEntries.length === 0) {\n\t\treturn undefined;\n\t}\n\n\treturn Object.fromEntries(metadataEntries);\n};\n\nconst parseMetadataValue = (\n\tvalue: unknown\n): Record<string, unknown> | undefined => {\n\tif (value === null || value === undefined) {\n\t\treturn undefined;\n\t}\n\n\tif (typeof value === 'string') {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(value);\n\t\t\tif (parsed && typeof parsed === 'object') {\n\t\t\t\treturn parsed as Record<string, unknown>;\n\t\t\t}\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tif (typeof value === 'object') {\n\t\treturn value as Record<string, unknown>;\n\t}\n\n\treturn undefined;\n};\n\nconst createPgvectorStoreStatus = ({\n\tvector,\n\tschema,\n\tdiagnostics,\n\tinitialized\n}: {\n\tvector: ResolvedPgvectorConfig;\n\tschema: ResolvedSchemaConfig;\n\tdiagnostics: PgvectorDiagnostics;\n\tinitialized: boolean;\n}): RAGVectorStoreStatus =>\n\t({\n\t\tbackend: 'postgres',\n\t\tvectorMode: 'native_pgvector',\n\t\tdimensions: vector.dimensions,\n\t\tnative: {\n\t\t\trequested: true,\n\t\t\tavailable: initialized && !diagnostics.lastInitError,\n\t\t\tactive: initialized && !diagnostics.lastInitError,\n\t\t\tmode: 'pgvector',\n\t\t\textensionName: vector.extensionName,\n\t\t\tschemaName: schema.schemaName,\n\t\t\ttableName: schema.chunkTableName,\n\t\t\tdistanceMetric: vector.distanceMetric,\n\t\t\tindexType: vector.index.type,\n\t\t\tfallbackReason: diagnostics.fallbackReason,\n\t\t\tlastInitError: diagnostics.lastInitError,\n\t\t\tlastQueryError: diagnostics.lastQueryError,\n\t\t\tlastUpsertError: diagnostics.lastUpsertError,\n\t\t\tlastMigrationError: diagnostics.lastMigrationError\n\t\t}\n\t}) as unknown as RAGVectorStoreStatus;\n\nconst getAppliedMigrationNames = async (\n\tclient: PostgreSQLRAGClient,\n\tmigrationPlan: PostgreSQLMigrationPlan\n): Promise<Set<string>> => {\n\tconst result = await client.query<{ name: unknown }>(\n\t\t`SELECT name FROM ${migrationPlan.migrationTableQualifiedName} ORDER BY name ASC`\n\t);\n\n\treturn new Set(result.rows.map((row) => String(row.name)));\n};\n\nconst insertAppliedMigration = async (\n\tclient: PostgreSQLRAGClient,\n\tmigrationPlan: PostgreSQLMigrationPlan,\n\tname: string\n): Promise<void> => {\n\tawait client.query(\n\t\t`INSERT INTO ${migrationPlan.migrationTableQualifiedName} (name) VALUES ($1) ON CONFLICT (name) DO NOTHING`,\n\t\t[name]\n\t);\n};\n\nconst executeMigrationSequence = async (\n\tclient: PostgreSQLRAGClient,\n\tmigrationPlan: PostgreSQLMigrationPlan,\n\tmigrations: PostgreSQLMigrationEntry[]\n): Promise<string[]> => {\n\tconst appliedNames: string[] = [];\n\n\tfor (const migration of migrations) {\n\t\tawait client.query(migration.sql);\n\t\tawait insertAppliedMigration(client, migrationPlan, migration.name);\n\t\tappliedNames.push(migration.name);\n\t}\n\n\treturn appliedNames;\n};\n\nexport const applyPostgresMigrations = async (\n\toptions: PostgreSQLRAGOptions,\n\tapplyOptions: PostgreSQLApplyMigrationsOptions = {}\n): Promise<PostgreSQLApplyMigrationsResult> => {\n\tconst migrationPlan = createPostgresMigrationPlan(\n\t\toptions ?? ({} as PostgreSQLRAGOptions)\n\t);\n\tconst injectedClient = applyOptions.client;\n\tconst getClient = injectedClient\n\t\t? async () => injectedClient\n\t\t: resolveClientFactory(options ?? ({} as PostgreSQLRAGOptions));\n\tconst client = await getClient();\n\n\tfor (const sql of migrationPlan.bootstrapSql) {\n\t\tawait client.query(sql);\n\t}\n\n\tconst alreadyApplied = await getAppliedMigrationNames(client, migrationPlan);\n\tconst pendingMigrations = migrationPlan.migrations.filter(\n\t\t(migration) => !alreadyApplied.has(migration.name)\n\t);\n\tconst skippedNames = migrationPlan.migrations\n\t\t.filter((migration) => alreadyApplied.has(migration.name))\n\t\t.map((migration) => migration.name);\n\n\tif (applyOptions.dryRun === true) {\n\t\treturn {\n\t\t\tmigrationPlan,\n\t\t\tappliedNames: [],\n\t\t\tskippedNames,\n\t\t\tpendingNames: pendingMigrations.map((migration) => migration.name),\n\t\t\tappliedCount: 0,\n\t\t\tpendingCount: pendingMigrations.length,\n\t\t\tdryRun: true\n\t\t};\n\t}\n\n\tconst run = async (\n\t\tactiveClient: PostgreSQLRAGClient\n\t): Promise<PostgreSQLApplyMigrationsResult> => {\n\t\tconst names = await executeMigrationSequence(\n\t\t\tactiveClient,\n\t\t\tmigrationPlan,\n\t\t\tpendingMigrations\n\t\t);\n\n\t\treturn {\n\t\t\tmigrationPlan,\n\t\t\tappliedNames: names,\n\t\t\tskippedNames,\n\t\t\tpendingNames: pendingMigrations.map((migration) => migration.name),\n\t\t\tappliedCount: names.length,\n\t\t\tpendingCount: pendingMigrations.length,\n\t\t\tdryRun: false\n\t\t};\n\t};\n\n\tif (\n\t\ttypeof client.transaction === 'function' &&\n\t\tpendingMigrations.length > 0\n\t) {\n\t\treturn client.transaction(async (transactionClient) =>\n\t\t\trun(transactionClient)\n\t\t);\n\t}\n\n\treturn run(client);\n};\n\nexport const applyPostgresSchemaPlan: typeof applyPostgresMigrations =\n\tapplyPostgresMigrations;\n\nexport const createPgvectorStore = (\n\toptions: PostgreSQLRAGOptions\n): RAGVectorStore => {\n\tconst vector = resolveVectorConfig(options ?? {});\n\tconst schema = resolveSchemaConfig(options ?? {});\n\tconst plan = createPostgresSchemaPlan(options ?? ({} as PostgreSQLRAGOptions));\n\tconst getClient = resolveClientFactory(options ?? ({} as PostgreSQLRAGOptions));\n\tconst diagnostics: PgvectorDiagnostics = {\n\t\tfallbackReason: undefined,\n\t\tlastInitError: undefined,\n\t\tlastQueryError: undefined,\n\t\tlastUpsertError: undefined,\n\t\tlastMigrationError: undefined\n\t};\n\tlet initialized = false;\n\tlet initPromise: Promise<void> | undefined;\n\n\tconst ensureInitialized = async (): Promise<void> => {\n\t\tif (initialized) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!initPromise) {\n\t\t\tinitPromise = (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst client = await getClient();\n\t\t\t\t\tawait applyPostgresMigrations(options ?? {}, { client });\n\t\t\t\t\tinitialized = true;\n\t\t\t\t\tdiagnostics.lastInitError = undefined;\n\t\t\t\t\tdiagnostics.lastMigrationError = undefined;\n\t\t\t\t\tdiagnostics.fallbackReason = undefined;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tinitialized = false;\n\t\t\t\t\tconst message =\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error);\n\t\t\t\t\tdiagnostics.lastInitError = message;\n\t\t\t\t\tdiagnostics.lastMigrationError = message;\n\t\t\t\t\tdiagnostics.fallbackReason = message;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t})();\n\t\t}\n\n\t\treturn initPromise;\n\t};\n\n\tconst embed: RAGVectorStore['embed'] = async (input) => {\n\t\tif (typeof options.embedding === 'function') {\n\t\t\tconst result = await options.embedding(input);\n\n\t\t\treturn normalizeVector(result);\n\t\t}\n\n\t\treturn normalizeVector([\n\t\t\t...createRAGVector(input.text, vector.dimensions)\n\t\t]);\n\t};\n\n\tconst query = async (input: RAGQueryInput): Promise<RAGQueryResult[]> => {\n\t\tawait ensureInitialized();\n\t\tconst client = await getClient();\n\t\tconst params: unknown[] = [];\n\t\tconst qualifiedChunkTable = qualifiedTable(\n\t\t\tschema.schemaName,\n\t\t\tschema.chunkTableName\n\t\t);\n\t\tconst operator = operatorForMetric(vector.distanceMetric);\n\t\tconst vectorPlaceholder = makePlaceholder(\n\t\t\tparams,\n\t\t\tvectorLiteral(normalizeVector(input.queryVector)),\n\t\t\t'vector'\n\t\t);\n\t\tconst limitPlaceholder = makePlaceholder(params, input.topK);\n\t\tconst whereParts: string[] = [];\n\t\tconst filter = input.filter as Record<string, unknown> | undefined;\n\n\t\tif (filter?.chunkId !== undefined) {\n\t\t\twhereParts.push(\n\t\t\t\t`chunk_id = ${makePlaceholder(params, filter.chunkId)}`\n\t\t\t);\n\t\t}\n\t\tif (filter?.title !== undefined) {\n\t\t\twhereParts.push(`title = ${makePlaceholder(params, filter.title)}`);\n\t\t}\n\t\tif (filter?.source !== undefined) {\n\t\t\twhereParts.push(\n\t\t\t\t`source = ${makePlaceholder(params, filter.source)}`\n\t\t\t);\n\t\t}\n\n\t\tconst metadataFilter = buildMetadataFilter(filter);\n\t\tif (metadataFilter) {\n\t\t\twhereParts.push(\n\t\t\t\t`metadata @> ${makePlaceholder(\n\t\t\t\t\tparams,\n\t\t\t\t\tJSON.stringify(metadataFilter),\n\t\t\t\t\t'jsonb'\n\t\t\t\t)}`\n\t\t\t);\n\t\t}\n\n\t\tconst whereSql =\n\t\t\twhereParts.length > 0 ? `WHERE ${whereParts.join(' AND ')}` : '';\n\t\tconst sessionSql = plan.querySessionSql;\n\t\tconst selectSql = `SELECT chunk_id, text, title, source, metadata, embedding ${operator} ${vectorPlaceholder} AS distance FROM ${qualifiedChunkTable} ${whereSql} ORDER BY distance ASC LIMIT ${limitPlaceholder}`;\n\n\t\ttry {\n\t\t\tfor (const sql of sessionSql) {\n\t\t\t\tawait client.query(sql);\n\t\t\t}\n\n\t\t\tconst result = await client.query<{\n\t\t\t\tchunk_id: string;\n\t\t\t\ttext: string;\n\t\t\t\ttitle: string | null;\n\t\t\t\tsource: string | null;\n\t\t\t\tmetadata: unknown;\n\t\t\t\tdistance: unknown;\n\t\t\t}>(selectSql, params);\n\n\t\t\treturn result.rows.map((row) => ({\n\t\t\t\tchunkId: row.chunk_id,\n\t\t\t\tchunkText: row.text,\n\t\t\t\ttitle: row.title ?? undefined,\n\t\t\t\tsource: row.source ?? undefined,\n\t\t\t\tmetadata: parseMetadataValue(row.metadata),\n\t\t\t\tscore: scoreFromDistance(\n\t\t\t\t\tNumber(row.distance),\n\t\t\t\t\tvector.distanceMetric\n\t\t\t\t)\n\t\t\t}));\n\t\t} catch (error) {\n\t\t\tdiagnostics.lastQueryError =\n\t\t\t\terror instanceof Error ? error.message : String(error);\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst upsert = async (input: RAGUpsertInput): Promise<void> => {\n\t\tawait ensureInitialized();\n\t\tconst client = await getClient();\n\t\tconst qualifiedChunkTable = qualifiedTable(\n\t\t\tschema.schemaName,\n\t\t\tschema.chunkTableName\n\t\t);\n\t\tconst sql = `INSERT INTO ${qualifiedChunkTable} (chunk_id, text, title, source, metadata, embedding, updated_at) VALUES ($1, $2, $3, $4, $5::jsonb, $6::vector, NOW()) ON CONFLICT (chunk_id) DO UPDATE SET text = EXCLUDED.text, title = EXCLUDED.title, source = EXCLUDED.source, metadata = EXCLUDED.metadata, embedding = EXCLUDED.embedding, updated_at = NOW()`;\n\n\t\ttry {\n\t\t\tfor (const chunk of input.chunks) {\n\t\t\t\tconst vectorValue =\n\t\t\t\t\tArray.isArray(chunk.embedding) && chunk.embedding.length > 0\n\t\t\t\t\t\t? normalizeVector(chunk.embedding)\n\t\t\t\t\t\t: await embed({ text: chunk.text });\n\t\t\t\tawait client.query(sql, [\n\t\t\t\t\tchunk.chunkId,\n\t\t\t\t\tchunk.text,\n\t\t\t\t\tchunk.title ?? null,\n\t\t\t\t\tchunk.source ?? null,\n\t\t\t\t\tJSON.stringify(chunk.metadata ?? {}),\n\t\t\t\t\tvectorLiteral(vectorValue)\n\t\t\t\t]);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tdiagnostics.lastUpsertError =\n\t\t\t\terror instanceof Error ? error.message : String(error);\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst clear = async (): Promise<void> => {\n\t\tawait ensureInitialized();\n\t\tconst client = await getClient();\n\t\tconst qualifiedChunkTable = qualifiedTable(\n\t\t\tschema.schemaName,\n\t\t\tschema.chunkTableName\n\t\t);\n\t\tawait client.query(`DELETE FROM ${qualifiedChunkTable}`);\n\t};\n\n\treturn {\n\t\tembed,\n\t\tquery,\n\t\tupsert,\n\t\tclear,\n\t\tgetCapabilities: () => ({\n\t\t\tbackend: 'postgres',\n\t\t\tpersistence: 'external',\n\t\t\tnativeVectorSearch: true,\n\t\t\tserverSideFiltering: true,\n\t\t\tstreamingIngestStatus: false\n\t\t}),\n\t\tgetStatus: () =>\n\t\t\tcreatePgvectorStoreStatus({\n\t\t\t\tvector,\n\t\t\t\tschema,\n\t\t\t\tdiagnostics,\n\t\t\t\tinitialized\n\t\t\t})\n\t} as RAGVectorStore;\n};\n\nexport const createPostgresRAGCollection = (\n\toptions: PostgreSQLRAGOptions\n): RAGCollection =>\n\tcreateRAGCollection({\n\t\tstore: createPgvectorStore(options)\n\t});\n\nexport const createPostgresRAG = (\n\toptions: PostgreSQLRAGOptions\n): PostgreSQLRAG => {\n\tconst store = createPgvectorStore(options);\n\tconst collection = createRAGCollection({ store });\n\tconst schemaPlan = createPostgresSchemaPlan(options);\n\tconst migrationPlan = createPostgresMigrationPlan(options);\n\n\treturn {\n\t\tstore,\n\t\tcollection,\n\t\tgetStatus: () => store.getStatus?.(),\n\t\tgetCapabilities: () => store.getCapabilities?.(),\n\t\tgetSchemaPlan: () => schemaPlan,\n\t\tgetMigrationPlan: () => migrationPlan,\n\t\tapplyMigrations: (applyOptions) =>\n\t\t\tapplyPostgresMigrations(options, applyOptions)\n\t};\n};\n\nexport const createPostgreSQLRAG: typeof createPostgresRAG = createPostgresRAG;\n"
6
+ ],
7
+ "mappings": ";;;;AASA;AAAA;AAAA;AAAA;AAAA;AAMO,IAAM,uCAAuC;AAE7C,IAAM,iCAAiC,CAAC,UAAU;AAClD,IAAM,4BAA4B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AACD;AACO,IAAM,uBAAuB,CAAC,QAAQ,QAAQ,SAAS;AAkK9D,IAAM,sBAAsB;AAC5B,IAAM,2BAA2B;AACjC,IAAM,+BAA+B;AACrC,IAAM,qBAAqB;AAE3B,IAAM,gBAAgB;AAEtB,IAAM,mBAAmB,CAAC,OAAgB,UAAwB;AAAA,EACjE,IAAI,OAAO,UAAU,YAAY,CAAC,cAAc,KAAK,KAAK,GAAG;AAAA,IAC5D,MAAM,IAAI,MACT,GAAG,iDAAiD,UAAU,OAC7D,KACD,IACD;AAAA,EACD;AAAA;A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AAA;AAAA,EAGxD,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,iBAAiB,OAAO;AAAA,MACvB,SAAS;AAAA,MACT,aAAa;AAAA,MACb,oBAAoB;AAAA,MACpB,qBAAqB;AAAA,MACrB,uBAAuB;AAAA,IACxB;AAAA,IACA,WAAW,MACV,0BAA0B;AAAA,MACzB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD,CAAC;AAAA,EACH;AAAA;AAGM,IAAM,8BAA8B,CAC1C,YAEA,oBAAoB;AAAA,EACnB,OAAO,oBAAoB,OAAO;AACnC,CAAC;AAEK,IAAM,oBAAoB,CAChC,YACmB;AAAA,EACnB,MAAM,QAAQ,oBAAoB,OAAO;AAAA,EACzC,MAAM,aAAa,oBAAoB,EAAE,MAAM,CAAC;AAAA,EAChD,MAAM,aAAa,yBAAyB,OAAO;AAAA,EACnD,MAAM,gBAAgB,4BAA4B,OAAO;AAAA,EAEzD,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA,WAAW,MAAM,MAAM,YAAY;AAAA,IACnC,iBAAiB,MAAM,MAAM,kBAAkB;AAAA,IAC/C,eAAe,MAAM;AAAA,IACrB,kBAAkB,MAAM;AAAA,IACxB,iBAAiB,CAAC,iBACjB,wBAAwB,SAAS,YAAY;AAAA,EAC/C;AAAA;AAGM,IAAM,sBAAgD;",
8
+ "debugId": "22931C2F3EFA23C264756E2164756E21",
9
+ "names": []
10
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@absolutejs/rag-postgres",
3
+ "version": "0.0.5",
4
+ "description": "PostgreSQL (pgvector) vector-store adapter for @absolutejs/rag",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/absolutejs/rag-adapters.git",
8
+ "directory": "postgres"
9
+ },
10
+ "main": "./dist/index.js",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "type": "module",
14
+ "license": "CC BY-NC 4.0",
15
+ "author": "Alex Kahn",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "keywords": [
20
+ "absolutejs",
21
+ "rag",
22
+ "postgresql",
23
+ "pgvector",
24
+ "vector"
25
+ ],
26
+ "scripts": {
27
+ "build": "rm -rf dist && bun build src/index.ts --outdir dist --sourcemap --target=bun --external @absolutejs/rag --external postgres && tsc --project tsconfig.build.json",
28
+ "test": "bun test",
29
+ "typecheck": "tsc --noEmit",
30
+ "format": "prettier --write \"./**/*.{ts,json,md}\"",
31
+ "release": "bun run format && bun run build && bun publish"
32
+ },
33
+ "dependencies": {
34
+ "@absolutejs/rag": "^0.0.19"
35
+ },
36
+ "peerDependencies": {
37
+ "postgres": ">= 3.4.0"
38
+ },
39
+ "devDependencies": {
40
+ "@types/bun": "1.2.9",
41
+ "postgres": "3.4.9",
42
+ "prettier": "3.5.3",
43
+ "typescript": "5.8.3"
44
+ },
45
+ "exports": {
46
+ ".": {
47
+ "types": "./dist/index.d.ts",
48
+ "import": "./dist/index.js",
49
+ "default": "./dist/index.js"
50
+ }
51
+ },
52
+ "files": [
53
+ "dist",
54
+ "README.md"
55
+ ]
56
+ }