@mastra/couchbase 0.0.0-trigger-playground-ui-package-20250506151043 → 0.0.0-tsconfig-compile-20250703214351

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/dist/index.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var error = require('@mastra/core/error');
3
4
  var vector = require('@mastra/core/vector');
4
5
  var couchbase = require('couchbase');
5
6
 
@@ -19,28 +20,47 @@ var CouchbaseVector = class extends vector.MastraVector {
19
20
  bucket;
20
21
  scope;
21
22
  vector_dimension;
22
- constructor(cnn_string, username, password, bucketName, scopeName, collectionName) {
23
+ constructor({ connectionString, username, password, bucketName, scopeName, collectionName }) {
23
24
  super();
24
- const baseClusterPromise = couchbase.connect(cnn_string, {
25
- username,
26
- password,
27
- configProfile: "wanDevelopment"
28
- });
29
- const telemetry = this.__getTelemetry();
30
- this.clusterPromise = telemetry?.traceClass(baseClusterPromise, {
31
- spanNamePrefix: "couchbase-vector",
32
- attributes: {
33
- "vector.type": "couchbase"
34
- }
35
- }) ?? baseClusterPromise;
36
- this.cluster = null;
37
- this.bucketName = bucketName;
38
- this.collectionName = collectionName;
39
- this.scopeName = scopeName;
40
- this.collection = null;
41
- this.bucket = null;
42
- this.scope = null;
43
- this.vector_dimension = null;
25
+ try {
26
+ const baseClusterPromise = couchbase.connect(connectionString, {
27
+ username,
28
+ password,
29
+ configProfile: "wanDevelopment"
30
+ });
31
+ const telemetry = this.__getTelemetry();
32
+ this.clusterPromise = telemetry?.traceClass(baseClusterPromise, {
33
+ spanNamePrefix: "couchbase-vector",
34
+ attributes: {
35
+ "vector.type": "couchbase"
36
+ }
37
+ }) ?? baseClusterPromise;
38
+ this.cluster = null;
39
+ this.bucketName = bucketName;
40
+ this.collectionName = collectionName;
41
+ this.scopeName = scopeName;
42
+ this.collection = null;
43
+ this.bucket = null;
44
+ this.scope = null;
45
+ this.vector_dimension = null;
46
+ } catch (error$1) {
47
+ throw new error.MastraError(
48
+ {
49
+ id: "COUCHBASE_VECTOR_INITIALIZE_FAILED",
50
+ domain: error.ErrorDomain.STORAGE,
51
+ category: error.ErrorCategory.THIRD_PARTY,
52
+ details: {
53
+ connectionString,
54
+ username,
55
+ password,
56
+ bucketName,
57
+ scopeName,
58
+ collectionName
59
+ }
60
+ },
61
+ error$1
62
+ );
63
+ }
44
64
  }
45
65
  async getCollection() {
46
66
  if (!this.cluster) {
@@ -53,189 +73,380 @@ var CouchbaseVector = class extends vector.MastraVector {
53
73
  }
54
74
  return this.collection;
55
75
  }
56
- async createIndex(params) {
57
- const { indexName, dimension, metric = "dotproduct" } = params;
58
- await this.getCollection();
59
- if (!Number.isInteger(dimension) || dimension <= 0) {
60
- throw new Error("Dimension must be a positive integer");
61
- }
62
- await this.scope.searchIndexes().upsertIndex({
63
- name: indexName,
64
- sourceName: this.bucketName,
65
- type: "fulltext-index",
66
- params: {
67
- doc_config: {
68
- docid_prefix_delim: "",
69
- docid_regexp: "",
70
- mode: "scope.collection.type_field",
71
- type_field: "type"
72
- },
73
- mapping: {
74
- default_analyzer: "standard",
75
- default_datetime_parser: "dateTimeOptional",
76
- default_field: "_all",
77
- default_mapping: {
78
- dynamic: true,
79
- enabled: false
76
+ async createIndex({ indexName, dimension, metric = "dotproduct" }) {
77
+ try {
78
+ await this.getCollection();
79
+ if (!Number.isInteger(dimension) || dimension <= 0) {
80
+ throw new Error("Dimension must be a positive integer");
81
+ }
82
+ await this.scope.searchIndexes().upsertIndex({
83
+ name: indexName,
84
+ sourceName: this.bucketName,
85
+ type: "fulltext-index",
86
+ params: {
87
+ doc_config: {
88
+ docid_prefix_delim: "",
89
+ docid_regexp: "",
90
+ mode: "scope.collection.type_field",
91
+ type_field: "type"
80
92
  },
81
- default_type: "_default",
82
- docvalues_dynamic: true,
83
- // [Doc](https://docs.couchbase.com/server/current/search/search-index-params.html#params) mentions this attribute is required for vector search to return the indexed field
84
- index_dynamic: true,
85
- store_dynamic: true,
86
- // [Doc](https://docs.couchbase.com/server/current/search/search-index-params.html#params) mentions this attribute is required for vector search to return the indexed field
87
- type_field: "_type",
88
- types: {
89
- [`${this.scopeName}.${this.collectionName}`]: {
93
+ mapping: {
94
+ default_analyzer: "standard",
95
+ default_datetime_parser: "dateTimeOptional",
96
+ default_field: "_all",
97
+ default_mapping: {
90
98
  dynamic: true,
91
- enabled: true,
92
- properties: {
93
- embedding: {
94
- enabled: true,
95
- fields: [
96
- {
97
- dims: dimension,
98
- index: true,
99
- name: "embedding",
100
- similarity: DISTANCE_MAPPING[metric],
101
- type: "vector",
102
- vector_index_optimized_for: "recall",
103
- store: true,
104
- // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields
105
- docvalues: true,
106
- // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields
107
- include_term_vectors: true
108
- // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields
109
- }
110
- ]
111
- },
112
- content: {
113
- enabled: true,
114
- fields: [
115
- {
116
- index: true,
117
- name: "content",
118
- store: true,
119
- type: "text"
120
- }
121
- ]
99
+ enabled: false
100
+ },
101
+ default_type: "_default",
102
+ docvalues_dynamic: true,
103
+ // [Doc](https://docs.couchbase.com/server/current/search/search-index-params.html#params) mentions this attribute is required for vector search to return the indexed field
104
+ index_dynamic: true,
105
+ store_dynamic: true,
106
+ // [Doc](https://docs.couchbase.com/server/current/search/search-index-params.html#params) mentions this attribute is required for vector search to return the indexed field
107
+ type_field: "_type",
108
+ types: {
109
+ [`${this.scopeName}.${this.collectionName}`]: {
110
+ dynamic: true,
111
+ enabled: true,
112
+ properties: {
113
+ embedding: {
114
+ enabled: true,
115
+ fields: [
116
+ {
117
+ dims: dimension,
118
+ index: true,
119
+ name: "embedding",
120
+ similarity: DISTANCE_MAPPING[metric],
121
+ type: "vector",
122
+ vector_index_optimized_for: "recall",
123
+ store: true,
124
+ // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields
125
+ docvalues: true,
126
+ // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields
127
+ include_term_vectors: true
128
+ // CHANGED due to https://docs.couchbase.com/server/current/search/search-index-params.html#fields
129
+ }
130
+ ]
131
+ },
132
+ content: {
133
+ enabled: true,
134
+ fields: [
135
+ {
136
+ index: true,
137
+ name: "content",
138
+ store: true,
139
+ type: "text"
140
+ }
141
+ ]
142
+ }
122
143
  }
123
144
  }
124
145
  }
146
+ },
147
+ store: {
148
+ indexType: "scorch",
149
+ segmentVersion: 16
125
150
  }
126
151
  },
127
- store: {
128
- indexType: "scorch",
129
- segmentVersion: 16
152
+ sourceUuid: "",
153
+ sourceParams: {},
154
+ sourceType: "gocbcore",
155
+ planParams: {
156
+ maxPartitionsPerPIndex: 64,
157
+ indexPartitions: 16,
158
+ numReplicas: 0
130
159
  }
131
- },
132
- sourceUuid: "",
133
- sourceParams: {},
134
- sourceType: "gocbcore",
135
- planParams: {
136
- maxPartitionsPerPIndex: 64,
137
- indexPartitions: 16,
138
- numReplicas: 0
139
- }
140
- });
141
- this.vector_dimension = dimension;
160
+ });
161
+ this.vector_dimension = dimension;
162
+ } catch (error$1) {
163
+ const message = error$1?.message || error$1?.toString();
164
+ if (message && message.toLowerCase().includes("index exists")) {
165
+ await this.validateExistingIndex(indexName, dimension, metric);
166
+ return;
167
+ }
168
+ throw new error.MastraError(
169
+ {
170
+ id: "COUCHBASE_VECTOR_CREATE_INDEX_FAILED",
171
+ domain: error.ErrorDomain.STORAGE,
172
+ category: error.ErrorCategory.THIRD_PARTY,
173
+ details: {
174
+ indexName,
175
+ dimension,
176
+ metric
177
+ }
178
+ },
179
+ error$1
180
+ );
181
+ }
142
182
  }
143
- async upsert(params) {
144
- const { vectors, metadata, ids } = params;
145
- await this.getCollection();
146
- if (!vectors || vectors.length === 0) {
147
- throw new Error("No vectors provided");
183
+ async upsert({ vectors, metadata, ids }) {
184
+ try {
185
+ await this.getCollection();
186
+ if (!vectors || vectors.length === 0) {
187
+ throw new Error("No vectors provided");
188
+ }
189
+ if (this.vector_dimension) {
190
+ for (const vector of vectors) {
191
+ if (!vector || this.vector_dimension !== vector.length) {
192
+ throw new Error("Vector dimension mismatch");
193
+ }
194
+ }
195
+ }
196
+ const pointIds = ids || vectors.map(() => crypto.randomUUID());
197
+ const records = vectors.map((vector, i) => {
198
+ const metadataObj = metadata?.[i] || {};
199
+ const record = {
200
+ embedding: vector,
201
+ metadata: metadataObj
202
+ };
203
+ if (metadataObj.text) {
204
+ record.content = metadataObj.text;
205
+ }
206
+ return record;
207
+ });
208
+ const allPromises = [];
209
+ for (let i = 0; i < records.length; i++) {
210
+ allPromises.push(this.collection.upsert(pointIds[i], records[i]));
211
+ }
212
+ await Promise.all(allPromises);
213
+ return pointIds;
214
+ } catch (error$1) {
215
+ throw new error.MastraError(
216
+ {
217
+ id: "COUCHBASE_VECTOR_UPSERT_FAILED",
218
+ domain: error.ErrorDomain.STORAGE,
219
+ category: error.ErrorCategory.THIRD_PARTY
220
+ },
221
+ error$1
222
+ );
148
223
  }
149
- if (this.vector_dimension) {
150
- for (const vector of vectors) {
151
- if (!vector || this.vector_dimension !== vector.length) {
152
- throw new Error("Vector dimension mismatch");
224
+ }
225
+ async query({ indexName, queryVector, topK = 10, includeVector = false }) {
226
+ try {
227
+ await this.getCollection();
228
+ const index_stats = await this.describeIndex({ indexName });
229
+ if (queryVector.length !== index_stats.dimension) {
230
+ throw new Error(
231
+ `Query vector dimension mismatch. Expected ${index_stats.dimension}, got ${queryVector.length}`
232
+ );
233
+ }
234
+ let request = couchbase.SearchRequest.create(
235
+ couchbase.VectorSearch.fromVectorQuery(couchbase.VectorQuery.create("embedding", queryVector).numCandidates(topK))
236
+ );
237
+ const results = await this.scope.search(indexName, request, {
238
+ fields: ["*"]
239
+ });
240
+ if (includeVector) {
241
+ throw new Error("Including vectors in search results is not yet supported by the Couchbase vector store");
242
+ }
243
+ const output = [];
244
+ for (const match of results.rows) {
245
+ const cleanedMetadata = {};
246
+ const fields = match.fields || {};
247
+ for (const key in fields) {
248
+ if (Object.prototype.hasOwnProperty.call(fields, key)) {
249
+ const newKey = key.startsWith("metadata.") ? key.substring("metadata.".length) : key;
250
+ cleanedMetadata[newKey] = fields[key];
251
+ }
153
252
  }
253
+ output.push({
254
+ id: match.id,
255
+ score: match.score || 0,
256
+ metadata: cleanedMetadata
257
+ // Use the cleaned metadata object
258
+ });
154
259
  }
260
+ return output;
261
+ } catch (error$1) {
262
+ throw new error.MastraError(
263
+ {
264
+ id: "COUCHBASE_VECTOR_QUERY_FAILED",
265
+ domain: error.ErrorDomain.STORAGE,
266
+ category: error.ErrorCategory.THIRD_PARTY,
267
+ details: {
268
+ indexName,
269
+ topK
270
+ }
271
+ },
272
+ error$1
273
+ );
155
274
  }
156
- const pointIds = ids || vectors.map(() => crypto.randomUUID());
157
- const records = vectors.map((vector, i) => {
158
- const metadataObj = metadata?.[i] || {};
159
- const record = {
160
- embedding: vector,
161
- metadata: metadataObj
162
- };
163
- if (metadataObj.text) {
164
- record.content = metadataObj.text;
165
- }
166
- return record;
167
- });
168
- const allPromises = [];
169
- for (let i = 0; i < records.length; i++) {
170
- allPromises.push(this.collection.upsert(pointIds[i], records[i]));
275
+ }
276
+ async listIndexes() {
277
+ try {
278
+ await this.getCollection();
279
+ const indexes = await this.scope.searchIndexes().getAllIndexes();
280
+ return indexes?.map((index) => index.name) || [];
281
+ } catch (error$1) {
282
+ throw new error.MastraError(
283
+ {
284
+ id: "COUCHBASE_VECTOR_LIST_INDEXES_FAILED",
285
+ domain: error.ErrorDomain.STORAGE,
286
+ category: error.ErrorCategory.THIRD_PARTY
287
+ },
288
+ error$1
289
+ );
171
290
  }
172
- await Promise.all(allPromises);
173
- return pointIds;
174
291
  }
175
- async query(params) {
176
- const { indexName, queryVector, topK = 10, includeVector = false } = params;
177
- await this.getCollection();
178
- const index_stats = await this.describeIndex(indexName);
179
- if (queryVector.length !== index_stats.dimension) {
180
- throw new Error(`Query vector dimension mismatch. Expected ${index_stats.dimension}, got ${queryVector.length}`);
292
+ /**
293
+ * Retrieves statistics about a vector index.
294
+ *
295
+ * @param {string} indexName - The name of the index to describe
296
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
297
+ */
298
+ async describeIndex({ indexName }) {
299
+ try {
300
+ await this.getCollection();
301
+ if (!(await this.listIndexes()).includes(indexName)) {
302
+ throw new Error(`Index ${indexName} does not exist`);
303
+ }
304
+ const index = await this.scope.searchIndexes().getIndex(indexName);
305
+ const dimensions = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.dims;
306
+ const count = -1;
307
+ const metric = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.similarity;
308
+ return {
309
+ dimension: dimensions,
310
+ count,
311
+ metric: Object.keys(DISTANCE_MAPPING).find(
312
+ (key) => DISTANCE_MAPPING[key] === metric
313
+ )
314
+ };
315
+ } catch (error$1) {
316
+ throw new error.MastraError(
317
+ {
318
+ id: "COUCHBASE_VECTOR_DESCRIBE_INDEX_FAILED",
319
+ domain: error.ErrorDomain.STORAGE,
320
+ category: error.ErrorCategory.THIRD_PARTY,
321
+ details: {
322
+ indexName
323
+ }
324
+ },
325
+ error$1
326
+ );
181
327
  }
182
- let request = couchbase.SearchRequest.create(
183
- couchbase.VectorSearch.fromVectorQuery(couchbase.VectorQuery.create("embedding", queryVector).numCandidates(topK))
184
- );
185
- const results = await this.scope.search(indexName, request, {
186
- fields: ["*"]
187
- });
188
- if (includeVector) {
189
- throw new Error("Including vectors in search results is not yet supported by the Couchbase vector store");
328
+ }
329
+ async deleteIndex({ indexName }) {
330
+ try {
331
+ await this.getCollection();
332
+ if (!(await this.listIndexes()).includes(indexName)) {
333
+ throw new Error(`Index ${indexName} does not exist`);
334
+ }
335
+ await this.scope.searchIndexes().dropIndex(indexName);
336
+ this.vector_dimension = null;
337
+ } catch (error$1) {
338
+ if (error$1 instanceof error.MastraError) {
339
+ throw error$1;
340
+ }
341
+ throw new error.MastraError(
342
+ {
343
+ id: "COUCHBASE_VECTOR_DELETE_INDEX_FAILED",
344
+ domain: error.ErrorDomain.STORAGE,
345
+ category: error.ErrorCategory.THIRD_PARTY,
346
+ details: {
347
+ indexName
348
+ }
349
+ },
350
+ error$1
351
+ );
190
352
  }
191
- const output = [];
192
- for (const match of results.rows) {
193
- const cleanedMetadata = {};
194
- const fields = match.fields || {};
195
- for (const key in fields) {
196
- if (Object.prototype.hasOwnProperty.call(fields, key)) {
197
- const newKey = key.startsWith("metadata.") ? key.substring("metadata.".length) : key;
198
- cleanedMetadata[newKey] = fields[key];
353
+ }
354
+ /**
355
+ * Updates a vector by its ID with the provided vector and/or metadata.
356
+ * @param indexName - The name of the index containing the vector.
357
+ * @param id - The ID of the vector to update.
358
+ * @param update - An object containing the vector and/or metadata to update.
359
+ * @param update.vector - An optional array of numbers representing the new vector.
360
+ * @param update.metadata - An optional record containing the new metadata.
361
+ * @returns A promise that resolves when the update is complete.
362
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
363
+ */
364
+ async updateVector({ id, update }) {
365
+ try {
366
+ if (!update.vector && !update.metadata) {
367
+ throw new Error("No updates provided");
368
+ }
369
+ if (update.vector && this.vector_dimension && update.vector.length !== this.vector_dimension) {
370
+ throw new Error("Vector dimension mismatch");
371
+ }
372
+ const collection = await this.getCollection();
373
+ try {
374
+ await collection.get(id);
375
+ } catch (err) {
376
+ if (err.code === 13 || err.message?.includes("document not found")) {
377
+ throw new Error(`Vector with id ${id} does not exist`);
199
378
  }
379
+ throw err;
200
380
  }
201
- output.push({
202
- id: match.id,
203
- score: match.score || 0,
204
- metadata: cleanedMetadata
205
- // Use the cleaned metadata object
206
- });
381
+ const specs = [];
382
+ if (update.vector) specs.push(couchbase.MutateInSpec.replace("embedding", update.vector));
383
+ if (update.metadata) specs.push(couchbase.MutateInSpec.replace("metadata", update.metadata));
384
+ await collection.mutateIn(id, specs);
385
+ } catch (error$1) {
386
+ throw new error.MastraError(
387
+ {
388
+ id: "COUCHBASE_VECTOR_UPDATE_FAILED",
389
+ domain: error.ErrorDomain.STORAGE,
390
+ category: error.ErrorCategory.THIRD_PARTY,
391
+ details: {
392
+ id,
393
+ hasVectorUpdate: !!update.vector,
394
+ hasMetadataUpdate: !!update.metadata
395
+ }
396
+ },
397
+ error$1
398
+ );
207
399
  }
208
- return output;
209
- }
210
- async listIndexes() {
211
- await this.getCollection();
212
- const indexes = await this.scope.searchIndexes().getAllIndexes();
213
- return indexes?.map((index) => index.name) || [];
214
400
  }
215
- async describeIndex(indexName) {
216
- await this.getCollection();
217
- if (!(await this.listIndexes()).includes(indexName)) {
218
- throw new Error(`Index ${indexName} does not exist`);
401
+ /**
402
+ * Deletes a vector by its ID.
403
+ * @param indexName - The name of the index containing the vector.
404
+ * @param id - The ID of the vector to delete.
405
+ * @returns A promise that resolves when the deletion is complete.
406
+ * @throws Will throw an error if the deletion operation fails.
407
+ */
408
+ async deleteVector({ id }) {
409
+ try {
410
+ const collection = await this.getCollection();
411
+ try {
412
+ await collection.get(id);
413
+ } catch (err) {
414
+ if (err.code === 13 || err.message?.includes("document not found")) {
415
+ throw new Error(`Vector with id ${id} does not exist`);
416
+ }
417
+ throw err;
418
+ }
419
+ await collection.remove(id);
420
+ } catch (error$1) {
421
+ throw new error.MastraError(
422
+ {
423
+ id: "COUCHBASE_VECTOR_DELETE_FAILED",
424
+ domain: error.ErrorDomain.STORAGE,
425
+ category: error.ErrorCategory.THIRD_PARTY,
426
+ details: {
427
+ id
428
+ }
429
+ },
430
+ error$1
431
+ );
219
432
  }
220
- const index = await this.scope.searchIndexes().getIndex(indexName);
221
- const dimensions = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.dims;
222
- const count = -1;
223
- const metric = index.params.mapping?.types?.[`${this.scopeName}.${this.collectionName}`]?.properties?.embedding?.fields?.[0]?.similarity;
224
- return {
225
- dimension: dimensions,
226
- count,
227
- metric: Object.keys(DISTANCE_MAPPING).find(
228
- (key) => DISTANCE_MAPPING[key] === metric
229
- )
230
- };
231
433
  }
232
- async deleteIndex(indexName) {
233
- await this.getCollection();
234
- if (!(await this.listIndexes()).includes(indexName)) {
235
- throw new Error(`Index ${indexName} does not exist`);
434
+ async disconnect() {
435
+ try {
436
+ if (!this.cluster) {
437
+ return;
438
+ }
439
+ await this.cluster.close();
440
+ } catch (error$1) {
441
+ throw new error.MastraError(
442
+ {
443
+ id: "COUCHBASE_VECTOR_DISCONNECT_FAILED",
444
+ domain: error.ErrorDomain.STORAGE,
445
+ category: error.ErrorCategory.THIRD_PARTY
446
+ },
447
+ error$1
448
+ );
236
449
  }
237
- await this.scope.searchIndexes().dropIndex(indexName);
238
- this.vector_dimension = null;
239
450
  }
240
451
  };
241
452
 
package/dist/index.d.cts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { DISTANCE_MAPPING } from './_tsup-dts-rollup.cjs';
2
+ export { CouchbaseVectorParams } from './_tsup-dts-rollup.cjs';
2
3
  export { CouchbaseVector } from './_tsup-dts-rollup.cjs';
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { DISTANCE_MAPPING } from './_tsup-dts-rollup.js';
2
+ export { CouchbaseVectorParams } from './_tsup-dts-rollup.js';
2
3
  export { CouchbaseVector } from './_tsup-dts-rollup.js';