@mastra/pg 1.28.0 → 1.28.1-alpha.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/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- import { createHash, randomUUID } from "crypto";
2
1
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
3
2
  import * as coreStorage from "@mastra/core/storage";
4
3
  import { AgentsStorage, BRANCH_SPAN_TYPES, BackgroundTasksStorage, BlobStore, ChannelsStorage, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, DatasetsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, EntityType, ExperimentsStorage, FactoryStorage, FavoritesStorage, KNOWLEDGE_ACTIVITY_SCHEMA, KNOWLEDGE_CURSORS_SCHEMA, KNOWLEDGE_MENTIONS_SCHEMA, KNOWLEDGE_NODES_SCHEMA, KNOWLEDGE_RECORDS_SCHEMA, KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA, KnowledgeConflictError, KnowledgeNotFoundError, KnowledgeStorage, MCPClientsStorage, MCPServersStorage, METRIC_DISTINCT_COLUMNS, MastraCompositeStore, MemoryStorage, NotificationsStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, PromptBlocksStorage, SchedulesStorage, ScorerDefinitionsStorage, ScoresStorage, SkillsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_BACKGROUND_TASKS, TABLE_CHANNEL_CONFIG, TABLE_CHANNEL_INSTALLATIONS, TABLE_CONFIGS, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, TABLE_FAVORITES, TABLE_KNOWLEDGE_ACTIVITY, TABLE_KNOWLEDGE_CURSORS, TABLE_KNOWLEDGE_MENTIONS, TABLE_KNOWLEDGE_NODES, TABLE_KNOWLEDGE_RECORDS, TABLE_KNOWLEDGE_SEMANTIC_OUTBOX, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, TABLE_MESSAGES, TABLE_NOTIFICATIONS, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, TABLE_RESOURCES, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, TABLE_SKILLS, TABLE_SKILL_BLOBS, TABLE_SKILL_VERSIONS, TABLE_SPANS, TABLE_THREADS, TABLE_THREAD_STATE, TABLE_TOOL_PROVIDER_CONNECTIONS, TABLE_WORKFLOW_DEFINITIONS, TABLE_WORKFLOW_SNAPSHOT, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, ThreadStateStorage, ToolProviderConnectionsStorage, TraceStatus, UniqueViolationError, WorkflowDefinitionsStorage, WorkflowsStorage, WorkspacesStorage, assertKnowledgeCeilingRaised, assertKnowledgeScopeWithinCeiling, calculatePagination, canonicalizeKnowledgeScope, createKnowledgeUlid, createStorageErrorId, createVectorErrorId, ensureDate, executeRetentionPrune, getDefaultValue, getSqlType, hasErrorCode, isKnowledgeScopeVisible, knowledgeScopeKey, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, listBranchesArgsSchema, listFeedbackArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listTracesArgsSchema, matchesExpectedWorkflowStatus, mergeWorkflowStepResult, normalizePerPage, normalizeScheduleTarget, parseDuration, parseKnowledgeNodeCursor, parseKnowledgeWikilinks, resolveListOrderBy, resolveRetentionTargets, retentionCutoffMs, runRetentionBatches, safelyParseJSON, storageMessageMatchesMetadataFilter, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
@@ -11,6 +10,7 @@ import xxhash from "xxhash-wasm";
11
10
  import { parse } from "pg-connection-string";
12
11
  import { BaseFilterTranslator } from "@mastra/core/vector/filter";
13
12
  import { MastraBase } from "@mastra/core/base";
13
+ import { createHash } from "crypto";
14
14
  import { MessageList } from "@mastra/core/agent";
15
15
  import { coreFeatures } from "@mastra/core/features";
16
16
  import { saveScorePayloadSchema } from "@mastra/core/evals";
@@ -825,7 +825,7 @@ var PgVector = class extends MastraVector {
825
825
  AND NOT attisdropped`, [tableName])).rowCount === 0) return;
826
826
  await client.query(`ALTER TABLE ${tableName} ADD COLUMN IF NOT EXISTS namespace VARCHAR(255) NOT NULL DEFAULT '${DEFAULT_NAMESPACE}'`);
827
827
  if (!(await this.getNamespaceSchemaState(tableName, client)).composite_index) {
828
- const namespaceIndexName = this.getNamespaceIndexName(parsedIndexName);
828
+ const namespaceIndexName = await this.getNamespaceIndexName(parsedIndexName);
829
829
  await client.query(`CREATE UNIQUE INDEX IF NOT EXISTS "${namespaceIndexName}" ON ${tableName} (namespace, vector_id)`);
830
830
  }
831
831
  const legacyConstraints = await client.query(`SELECT c.conname
@@ -838,10 +838,10 @@ var PgVector = class extends MastraVector {
838
838
  await client.query(`ALTER TABLE ${tableName} DROP CONSTRAINT "${parsedConstraintName}"`);
839
839
  }
840
840
  }
841
- getNamespaceIndexName(parsedIndexName) {
841
+ async getNamespaceIndexName(parsedIndexName) {
842
842
  const fullName = `${parsedIndexName}_namespace_vector_id_idx`;
843
843
  if (fullName.length <= 63) return fullName;
844
- const suffix = `_ns_${createHash("sha256").update(parsedIndexName).digest("hex").slice(0, 32)}_idx`;
844
+ const suffix = `_ns_${Buffer.from(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(parsedIndexName))).toString("hex").slice(0, 32)}_idx`;
845
845
  return `${parsedIndexName.slice(0, 63 - suffix.length)}${suffix}`;
846
846
  }
847
847
  async getNamespaceSchemaState(tableName, client) {
@@ -12653,7 +12653,7 @@ var MemoryPG = class MemoryPG extends MemoryStorage {
12653
12653
  });
12654
12654
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
12655
12655
  const newChunk = {
12656
- id: `ombuf-${randomUUID()}`,
12656
+ id: `ombuf-${globalThis.crypto.randomUUID()}`,
12657
12657
  cycleId: input.chunk.cycleId,
12658
12658
  observations: input.chunk.observations,
12659
12659
  tokenCount: Math.round(input.chunk.tokenCount),
@@ -13223,7 +13223,7 @@ var NotificationsPG = class NotificationsPG extends NotificationsStorage {
13223
13223
  }
13224
13224
  const now = input.createdAt ?? /* @__PURE__ */ new Date();
13225
13225
  const record = {
13226
- id: input.id ?? randomUUID(),
13226
+ id: input.id ?? globalThis.crypto.randomUUID(),
13227
13227
  threadId: input.threadId,
13228
13228
  source: input.source,
13229
13229
  kind: input.kind,
@@ -21476,7 +21476,6 @@ var SkillsPG = class SkillsPG extends SkillsStorage {
21476
21476
  details: { skillId: id }
21477
21477
  });
21478
21478
  const { authorId, visibility, activeVersionId, status, ...rawConfigFields } = updates;
21479
- let versionCreated = false;
21480
21479
  const configFields = {};
21481
21480
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
21482
21481
  if (SNAPSHOT_FIELDS$1.some((field) => field in configFields)) {
@@ -21495,7 +21494,6 @@ var SkillsPG = class SkillsPG extends SkillsStorage {
21495
21494
  };
21496
21495
  const changedFields = SNAPSHOT_FIELDS$1.filter((field) => field in configFields && !skillSnapshotFieldValuesEqual(configFields[field], latestConfig[field]));
21497
21496
  if (changedFields.length > 0) {
21498
- versionCreated = true;
21499
21497
  const newVersionId = crypto.randomUUID();
21500
21498
  await this.createVersion({
21501
21499
  id: newVersionId,
@@ -21536,7 +21534,7 @@ var SkillsPG = class SkillsPG extends SkillsStorage {
21536
21534
  setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
21537
21535
  values.push(now);
21538
21536
  values.push(id);
21539
- if (setClauses.length > 2 || versionCreated) await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
21537
+ await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
21540
21538
  const updatedSkill = await this.#getById(this.#db.client, id);
21541
21539
  if (!updatedSkill) throw new MastraError({
21542
21540
  id: createStorageErrorId("PG", "UPDATE_SKILL", "NOT_FOUND_AFTER_UPDATE"),
@@ -23313,7 +23311,6 @@ var WorkspacesPG = class WorkspacesPG extends WorkspacesStorage {
23313
23311
  details: { workspaceId: id }
23314
23312
  });
23315
23313
  const { authorId, activeVersionId, metadata, status, ...rawConfigFields } = updates;
23316
- let versionCreated = false;
23317
23314
  const configFields = {};
23318
23315
  for (const [key, value] of Object.entries(rawConfigFields)) if (value !== void 0) configFields[key] = value;
23319
23316
  if (SNAPSHOT_FIELDS.some((field) => field in configFields)) {
@@ -23336,7 +23333,6 @@ var WorkspacesPG = class WorkspacesPG extends WorkspacesStorage {
23336
23333
  };
23337
23334
  const changedFields = SNAPSHOT_FIELDS.filter((field) => field in configFields && !isDeepStrictEqual(normalized(configFields[field]), normalized(latestConfig[field])));
23338
23335
  if (changedFields.length > 0) {
23339
- versionCreated = true;
23340
23336
  const newVersionId = crypto.randomUUID();
23341
23337
  await this.createVersion({
23342
23338
  id: newVersionId,
@@ -23382,7 +23378,7 @@ var WorkspacesPG = class WorkspacesPG extends WorkspacesStorage {
23382
23378
  setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
23383
23379
  values.push(now);
23384
23380
  values.push(id);
23385
- if (setClauses.length > 2 || versionCreated) await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
23381
+ await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
23386
23382
  const updatedWorkspace = await this.#getById(this.#db.client, id);
23387
23383
  if (!updatedWorkspace) throw new MastraError({
23388
23384
  id: createStorageErrorId("PG", "UPDATE_WORKSPACE", "NOT_FOUND_AFTER_UPDATE"),
@@ -23944,7 +23940,7 @@ var PgFactoryStorageOps = class {
23944
23940
  const schema = this.#schema(collection);
23945
23941
  const pk = primaryKeyOf(schema);
23946
23942
  const values = { ...row };
23947
- if (schema.columns[pk].type === "uuid-pk" && values[pk] === void 0) values[pk] = randomUUID();
23943
+ if (schema.columns[pk].type === "uuid-pk" && values[pk] === void 0) values[pk] = globalThis.crypto.randomUUID();
23948
23944
  const columns = Object.keys(values).filter((column) => values[column] !== void 0);
23949
23945
  for (const column of columns) this.#column(schema, column);
23950
23946
  const sql = `INSERT INTO "${schema.name}" (${columns.map((c) => `"${c}"`).join(", ")}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(", ")}) RETURNING *`;