{
  "version": 3,
  "sources": ["../src/index.js", "../src/embeddings.js", "../src/utils.js"],
  "sourcesContent": ["// embeddings/src/index.js\n/**\n * @file Main entry point for the @daitanjs/embeddings package.\n * @module @daitanjs/embeddings\n *\n * @description\n * This package provides a comprehensive suite of tools for working with text embeddings.\n * It has been simplified to focus on core, stable functionality.\n */\nimport { getLogger } from '@daitanjs/development';\n\nconst embeddingsIndexLogger = getLogger('daitan-embeddings-index');\n\nembeddingsIndexLogger.debug('Exporting DaitanJS Embeddings functionalities...');\n\n// --- Core Embedding Generation ---\n// JSDoc for these is in `src/embeddings.js`.\nexport {\n  generateEmbedding,\n  generateBatchEmbeddings, // Kept for backward compatibility\n} from './embeddings.js';\n\n// --- Mathematical and Utility Functions ---\n// JSDoc for these is in `src/functions.js`.\n// These are removed for now to ensure a stable build, as they depend on ml-paca etc.\n// export {\n//   averageEmbeddings,\n//   interpolateEmbeddings,\n//   visualizeEmbeddings,\n//   clusterEmbeddings,\n// } from './functions.js';\n\n// --- Lower-level Utility Functions ---\n// JSDoc for these is in `src/utils.js`.\nexport {\n  isTensorFlowSupported,\n  dotProduct,\n  magnitude,\n  cosineSimilarity,\n} from './utils.js';\n\nembeddingsIndexLogger.info('DaitanJS Embeddings module exports ready.');\n", "// embeddings/src/embeddings.js\n/**\n * @file [STABLE REWRITE] Core functionalities for generating embeddings.\n * @module @daitanjs/embeddings/embeddings\n * @description This file has been radically simplified to remove complex dependencies (ml-pca, ml-kmeans, tensorflow)\n * that were causing build corruption. Its sole purpose is now to provide a stable, reliable\n * interface for generating embeddings via the OpenAI API.\n */\nimport { getLogger } from '@daitanjs/development';\nimport { getConfigManager } from '@daitanjs/config';\nimport {\n  DaitanConfigurationError,\n  DaitanOperationError,\n  DaitanInvalidInputError,\n  DaitanError,\n} from '@daitanjs/error';\nimport { query as apiQuery } from '@daitanjs/apiqueries';\n\nconst embeddingsServiceLogger = getLogger('daitan-embeddings-service');\n\nconst embeddingRequestCache = new Map();\nconst DEFAULT_EMBEDDING_CACHE_MAX_SIZE = 1000;\n\n/**\n * @typedef {Object} EmbeddingGenerationResult\n * @property {number[] | number[][]} embedding - The generated embedding vector or array of vectors.\n * @property {string} modelUsed - The actual embedding model that was used.\n * @property {object} [usage] - Token usage information from the API.\n */\n\n/**\n * @typedef {Object} EmbeddingConfig\n * @property {string} [target] - The target embedding model, specified as 'provider|model' (e.g., 'openai|text-embedding-3-small').\n * @property {string} [apiKey] - Explicit API key for the provider.\n * @property {boolean} [useCache] - Enable/disable caching for this call.\n */\n\n/**\n * @typedef {Object} GenerateEmbeddingParams\n * @property {string | string[]} input - A single string or an array of strings to embed.\n * @property {EmbeddingConfig} [config={}] - Configuration for the embedding generation call.\n */\n\n/**\n * Generates embeddings for a single input string or an array of strings.\n */\nexport const generateEmbedding = async ({ input, config = {} }) => {\n  const configManager = getConfigManager();\n  const isBatch = Array.isArray(input);\n\n  if (\n    (isBatch &&\n      (input.length === 0 ||\n        !input.every((item) => typeof item === 'string' && item.trim()))) ||\n    (!isBatch && (typeof input !== 'string' || !input.trim()))\n  ) {\n    throw new DaitanInvalidInputError(\n      'Input for embedding must be a non-empty string or a non-empty array of non-empty strings.'\n    );\n  }\n\n  const {\n    target,\n    apiKey: explicitApiKey,\n    useCache: callSpecificUseCache,\n  } = config;\n\n  const [providerKey, modelName] = (target || 'openai|').split('|');\n  if (providerKey.toLowerCase().trim() !== 'openai') {\n    throw new DaitanConfigurationError(\n      `Unsupported embedding provider: \"${providerKey}\". Currently, only \"openai\" is supported.`\n    );\n  }\n\n  const effectiveModel =\n    modelName?.trim() ||\n    configManager.get('OPENAI_EMBEDDING_MODEL') ||\n    'text-embedding-3-small';\n  const apiKey = explicitApiKey || configManager.get('OPENAI_API_KEY');\n  if (!apiKey) {\n    throw new DaitanConfigurationError(\n      'OpenAI API key (OPENAI_API_KEY) is not configured for embeddings.'\n    );\n  }\n\n  const effectiveUseCache =\n    callSpecificUseCache ?? configManager.get('EMBEDDING_USE_CACHE', true);\n  const cacheKey =\n    effectiveUseCache && !isBatch ? `${input}_${effectiveModel}` : null;\n\n  if (cacheKey && embeddingRequestCache.has(cacheKey)) {\n    return {\n      embedding: embeddingRequestCache.get(cacheKey),\n      modelUsed: effectiveModel,\n      usage: null,\n    };\n  }\n\n  try {\n    const responseData = await apiQuery({\n      url: 'https://api.openai.com/v1/embeddings',\n      method: 'POST',\n      headers: { Authorization: `Bearer ${apiKey}` },\n      data: { input: isBatch ? input : [input], model: effectiveModel },\n      summary: `OpenAI Embedding: Model ${effectiveModel}`,\n    });\n\n    if (!responseData?.data?.[0]?.embedding) {\n      throw new DaitanOperationError(\n        'Invalid response structure from OpenAI Embeddings API.'\n      );\n    }\n\n    const embeddingsList = responseData.data.map((item) => item.embedding);\n    const resultEmbedding = isBatch ? embeddingsList : embeddingsList[0];\n\n    if (cacheKey) {\n      if (embeddingRequestCache.size >= DEFAULT_EMBEDDING_CACHE_MAX_SIZE) {\n        embeddingRequestCache.delete(embeddingRequestCache.keys().next().value);\n      }\n      embeddingRequestCache.set(cacheKey, resultEmbedding);\n    }\n\n    return {\n      embedding: resultEmbedding,\n      modelUsed: responseData.model || effectiveModel,\n      usage: responseData.usage || null,\n    };\n  } catch (error) {\n    if (error instanceof DaitanError) throw error;\n    throw new DaitanOperationError(\n      `Failed to generate embedding: ${error.message}`,\n      { model: effectiveModel },\n      error\n    );\n  }\n};\n\n/**\n * @deprecated Use `generateEmbedding({ input: inputsArray })` directly.\n */\nexport const generateBatchEmbeddings = async (inputsArray, model) => {\n  embeddingsServiceLogger.warn(\n    '`generateBatchEmbeddings` is deprecated. Use `generateEmbedding({ input: inputsArray, ... })` instead.'\n  );\n  return generateEmbedding({\n    input: inputsArray,\n    config: { target: `openai|${model}` },\n  });\n};\n", "// embeddings/src/utils.js\n/**\n * @file Utility functions for embedding operations, including math helpers and TensorFlow support checks.\n * @module @daitanjs/embeddings/utils\n *\n * @description\n * This module provides core mathematical utilities often used with embedding vectors,\n * such as dot product, magnitude calculation, and cosine similarity. It also re-exports\n * the `isTensorFlowSupported` check from `@daitanjs/development` for convenience within\n * the embeddings package, as TensorFlow.js Node can be leveraged for optimized\n * embedding similarity searches if the environment supports it.\n */\nimport {\n  getLogger,\n  isTensorFlowSupported as isTfJsNodeSupportedFromDev, // Import canonical check\n} from '@daitanjs/development';\nimport { DaitanInvalidInputError } from '@daitanjs/error'; // For input validation errors\n\nconst embeddingsUtilLogger = getLogger('daitan-embeddings-utils');\n\n/**\n * Re-export of the canonical TensorFlow.js Node support check from `@daitanjs/development`.\n * This function checks if the current CPU is likely to support TensorFlow.js Node\n * operations, which can be used for optimized embedding calculations.\n *\n * @public\n * @returns {boolean} True if TensorFlow.js Node is likely supported, false otherwise.\n */\nexport const isTensorFlowSupported = () => {\n  const supported = isTfJsNodeSupportedFromDev();\n  // embeddingsUtilLogger.debug(`isTensorFlowSupported (re-export): Result = ${supported}`); // Can be noisy, log if needed\n  return supported;\n};\n\n/**\n * Calculates the dot product of two numerical vectors (arrays of numbers).\n * Both vectors must be non-empty and have the same length.\n *\n * @public\n * @param {number[]} vectorA - The first vector.\n * @param {number[]} vectorB - The second vector.\n * @returns {number} The dot product of `vectorA` and `vectorB`.\n * @throws {DaitanInvalidInputError} If inputs are not valid arrays of numbers of the same length, or are empty.\n */\nexport const dotProduct = (vectorA, vectorB) => {\n  if (!Array.isArray(vectorA) || !Array.isArray(vectorB)) {\n    throw new DaitanInvalidInputError(\n      'Both inputs for dot product must be arrays.'\n    );\n  }\n  if (vectorA.length === 0) {\n    // vectorB.length === 0 covered by length check\n    throw new DaitanInvalidInputError(\n      'Vectors for dot product cannot be empty.'\n    );\n  }\n  if (vectorA.length !== vectorB.length) {\n    throw new DaitanInvalidInputError(\n      `Vectors must have the same length for dot product. Got lengths ${vectorA.length} and ${vectorB.length}.`\n    );\n  }\n\n  let product = 0;\n  for (let i = 0; i < vectorA.length; i++) {\n    if (\n      typeof vectorA[i] !== 'number' ||\n      typeof vectorB[i] !== 'number' ||\n      !isFinite(vectorA[i]) ||\n      !isFinite(vectorB[i])\n    ) {\n      throw new DaitanInvalidInputError(\n        `All vector elements must be finite numbers for dot product. Found invalid element at index ${i}.`\n      );\n    }\n    product += vectorA[i] * vectorB[i];\n  }\n  return product;\n};\n\n/**\n * Calculates the magnitude (Euclidean norm or L2 norm) of a numerical vector.\n * The vector must be non-empty and contain only finite numbers.\n *\n * @public\n * @param {number[]} vector - The vector for which to calculate the magnitude.\n * @returns {number} The magnitude of the vector.\n * @throws {DaitanInvalidInputError} If the input is not a valid non-empty array of finite numbers.\n */\nexport const magnitude = (vector) => {\n  if (!Array.isArray(vector)) {\n    throw new DaitanInvalidInputError(\n      'Input for magnitude calculation must be an array.'\n    );\n  }\n  if (vector.length === 0) {\n    throw new DaitanInvalidInputError(\n      'Cannot calculate magnitude of an empty vector.'\n    );\n  }\n\n  let sumOfSquares = 0;\n  for (let i = 0; i < vector.length; i++) {\n    if (typeof vector[i] !== 'number' || !isFinite(vector[i])) {\n      throw new DaitanInvalidInputError(\n        `All vector elements must be finite numbers to calculate magnitude. Found invalid element at index ${i}.`\n      );\n    }\n    sumOfSquares += vector[i] * vector[i];\n  }\n  return Math.sqrt(sumOfSquares);\n};\n\n/**\n * Calculates the cosine similarity between two numerical vectors.\n * Cosine similarity measures the cosine of the angle between two non-zero vectors,\n * indicating their orientation similarity. It ranges from -1 (exactly opposite)\n * to 1 (exactly the same direction), with 0 indicating orthogonality.\n *\n * Returns `NaN` if either vector has zero magnitude (as cosine similarity is undefined in such cases).\n *\n * @public\n * @param {number[]} vectorA - The first vector.\n * @param {number[]} vectorB - The second vector.\n * @returns {number} The cosine similarity, a value between -1 and 1 (inclusive), or `NaN` if undefined.\n * @throws {DaitanInvalidInputError} If inputs are invalid for dot product or magnitude calculations (propagated).\n */\nexport const cosineSimilarity = (vectorA, vectorB) => {\n  // dotProduct and magnitude will throw DaitanInvalidInputError on invalid inputs.\n  const dot = dotProduct(vectorA, vectorB);\n  const magA = magnitude(vectorA);\n  const magB = magnitude(vectorB);\n\n  if (magA === 0 || magB === 0) {\n    embeddingsUtilLogger.debug(\n      'Cosine similarity is undefined (returning NaN) because one or both vector magnitudes are zero.',\n      {\n        magA,\n        magB,\n        vectorALength: vectorA?.length,\n        vectorBLength: vectorB?.length,\n      }\n    );\n    return NaN; // Cosine similarity is undefined if one or both vectors are zero vectors.\n    // Returning 0 might be another option depending on how downstream code handles it.\n  }\n  const similarity = dot / (magA * magB);\n  // Clip to [-1, 1] to handle potential floating point inaccuracies for nearly identical/opposite vectors\n  return Math.max(-1, Math.min(1, similarity));\n};\n\n// The original basic getLogger from this file was removed in previous refactoring steps,\n// as the standardized getLogger is imported from @daitanjs/development.\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,IAAAA,sBAA0B;;;ACD1B,yBAA0B;AAC1B,oBAAiC;AACjC,mBAKO;AACP,wBAAkC;AAElC,IAAM,8BAA0B,8BAAU,2BAA2B;AAErE,IAAM,wBAAwB,oBAAI,IAAI;AACtC,IAAM,mCAAmC;AAyBlC,IAAM,oBAAoB,OAAO,EAAE,OAAO,SAAS,CAAC,EAAE,MAAM;AACjE,QAAM,oBAAgB,gCAAiB;AACvC,QAAM,UAAU,MAAM,QAAQ,KAAK;AAEnC,MACG,YACE,MAAM,WAAW,KAChB,CAAC,MAAM,MAAM,CAAC,SAAS,OAAO,SAAS,YAAY,KAAK,KAAK,CAAC,MACjE,CAAC,YAAY,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,IACvD;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM;AAAA,IACJ;AAAA,IACA,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ,IAAI;AAEJ,QAAM,CAAC,aAAa,SAAS,KAAK,UAAU,WAAW,MAAM,GAAG;AAChE,MAAI,YAAY,YAAY,EAAE,KAAK,MAAM,UAAU;AACjD,UAAM,IAAI;AA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