@retrivora-ai/rag-engine 2.3.7 → 2.3.9

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.
@@ -317,7 +317,7 @@ var init_package = __esm({
317
317
  "package.json"() {
318
318
  package_default = {
319
319
  name: "@retrivora-ai/rag-engine",
320
- version: "2.3.7",
320
+ version: "2.3.9",
321
321
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
322
322
  author: "Abhinav Alkuchi",
323
323
  license: "UNLICENSED",
@@ -503,10 +503,16 @@ var init_ConfigFetcher = __esm({
503
503
  process.env.RETRIVORA_CONTROL_PLANE_URL,
504
504
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
505
505
  CONTROL_PLANE_URL
506
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
506
+ ].filter((url) => {
507
+ if (!url) return false;
508
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
509
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
510
+ return true;
511
+ }).map((url) => url.replace(/\/$/, ""));
507
512
  for (const baseUrl of controlPlaneUrls) {
508
513
  try {
509
514
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
515
+ console.log(`[ConfigFetcher] Fetching config from: ${url}`);
510
516
  const res = await fetch(url, {
511
517
  method: "GET",
512
518
  headers: __spreadValues({
@@ -514,6 +520,10 @@ var init_ConfigFetcher = __esm({
514
520
  "x-sdk-version": SDK_VERSION
515
521
  }, licenseKey ? { "x-license-key": licenseKey } : {})
516
522
  });
523
+ console.log(`[ConfigFetcher] Response status: ${res.status}`);
524
+ if (!res.ok) {
525
+ console.warn(`[ConfigFetcher] Error text: ${await res.text()}`);
526
+ }
517
527
  if (res.ok) {
518
528
  const data = await res.json();
519
529
  if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.vectorDb)) {
@@ -524,8 +534,7 @@ var init_ConfigFetcher = __esm({
524
534
  isActive: data.isActive,
525
535
  expiresAt: data.expiresAt,
526
536
  vectorDb: {
527
- // apiKey is not returned by the config API — it's a server-only secret.
528
- // The SDK uses local PINECONE_API_KEY if available.
537
+ // Fetch apiKey from credentials API if available, else fallback to empty
529
538
  apiKey: data.vectorDb.apiKey || "",
530
539
  indexName: data.vectorDb.indexName || "retrivora-free",
531
540
  provider: data.vectorDb.provider || "pinecone",
@@ -557,6 +566,32 @@ var init_ConfigFetcher = __esm({
557
566
  data.projectSettings || data.settings
558
567
  )
559
568
  };
569
+ if (licenseKey) {
570
+ try {
571
+ const credUrl = `${baseUrl}/api/v1/credentials`;
572
+ const credRes = await fetch(credUrl, {
573
+ method: "POST",
574
+ headers: {
575
+ "Content-Type": "application/json"
576
+ },
577
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
578
+ });
579
+ if (credRes.ok) {
580
+ const credData = await credRes.json();
581
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
582
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
583
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
584
+ }
585
+ if (credData.credentials.litellmApiKey) {
586
+ config.llm.apiKey = credData.credentials.litellmApiKey;
587
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
588
+ }
589
+ }
590
+ }
591
+ } catch (e) {
592
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
593
+ }
594
+ }
560
595
  this.cache.set(cacheKey, { config, cachedAt: now });
561
596
  return config;
562
597
  }
@@ -596,6 +631,14 @@ var init_PineconeProvider = __esm({
596
631
  const opts = config.options || {};
597
632
  this.apiKey = opts.apiKey || process.env.PINECONE_API_KEY || "";
598
633
  }
634
+ getControlPlaneUrl() {
635
+ const urls = [
636
+ process.env.RETRIVORA_CONTROL_PLANE_URL,
637
+ process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
638
+ "https://www.retrivora.com"
639
+ ].filter((url) => Boolean(url));
640
+ return urls[0].replace(/\/$/, "");
641
+ }
599
642
  static getValidator() {
600
643
  return {
601
644
  validate(config) {
@@ -659,6 +702,7 @@ var init_PineconeProvider = __esm({
659
702
  let key = this.apiKey || process.env.PINECONE_API_KEY || "";
660
703
  if (!key) {
661
704
  const licenseKey = process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
705
+ this.licenseKey = licenseKey;
662
706
  const jwtProjectId = (() => {
663
707
  if (!licenseKey) return void 0;
664
708
  try {
@@ -672,6 +716,7 @@ var init_PineconeProvider = __esm({
672
716
  return void 0;
673
717
  })();
674
718
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
719
+ this.projectId = projectId;
675
720
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
676
721
  if (remoteConfig) {
677
722
  if (remoteConfig.apiKey) {
@@ -717,19 +762,59 @@ var init_PineconeProvider = __esm({
717
762
  return namespace ? idx.namespace(namespace) : idx.namespace("");
718
763
  }
719
764
  async upsert(doc, namespace) {
720
- var _a3;
765
+ var _a3, _b;
766
+ if (!this.client) {
767
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
768
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
769
+ method: "POST",
770
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
771
+ body: JSON.stringify({
772
+ projectId: this.projectId,
773
+ indexName: this.indexName,
774
+ namespace: namespace || this.projectId,
775
+ records: [{ id: String(doc.id), values: doc.vector, metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {}) }]
776
+ })
777
+ });
778
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy upsert failed: ${await res.text()}`);
779
+ return;
780
+ }
721
781
  const targetIdx = await this.getActiveIndex(namespace);
722
782
  await targetIdx.upsert({
723
783
  records: [{
724
784
  id: String(doc.id),
725
785
  values: doc.vector,
726
- metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {})
786
+ metadata: __spreadValues({ content: doc.content }, (_b = doc.metadata) != null ? _b : {})
727
787
  }]
728
788
  });
729
789
  }
730
790
  async batchUpsert(docs, namespace) {
731
- const targetIdx = await this.getActiveIndex(namespace);
732
791
  const BATCH = 100;
792
+ if (!this.client) {
793
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
794
+ for (let i = 0; i < docs.length; i += BATCH) {
795
+ const records = docs.slice(i, i + BATCH).map((d) => {
796
+ var _a3;
797
+ return {
798
+ id: String(d.id),
799
+ values: d.vector,
800
+ metadata: __spreadValues({ content: d.content }, (_a3 = d.metadata) != null ? _a3 : {})
801
+ };
802
+ });
803
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
804
+ method: "POST",
805
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
806
+ body: JSON.stringify({
807
+ projectId: this.projectId,
808
+ indexName: this.indexName,
809
+ namespace: namespace || this.projectId,
810
+ records
811
+ })
812
+ });
813
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy batch upsert failed: ${await res.text()}`);
814
+ }
815
+ return;
816
+ }
817
+ const targetIdx = await this.getActiveIndex(namespace);
733
818
  for (let i = 0; i < docs.length; i += BATCH) {
734
819
  const records = docs.slice(i, i + BATCH).map((d) => {
735
820
  var _a3;
@@ -743,20 +828,46 @@ var init_PineconeProvider = __esm({
743
828
  }
744
829
  }
745
830
  async query(vector, topK, namespace, filter) {
746
- var _a3;
747
- const targetIdx = await this.getActiveIndex(namespace);
831
+ var _a3, _b;
748
832
  const pineconeFilter = this.sanitizeFilter(filter);
833
+ if (!this.client) {
834
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
835
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/query`, {
836
+ method: "POST",
837
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
838
+ body: JSON.stringify({
839
+ projectId: this.projectId,
840
+ indexName: this.indexName,
841
+ namespace: namespace || this.projectId,
842
+ vector,
843
+ topK,
844
+ filter: pineconeFilter
845
+ })
846
+ });
847
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy query failed: ${await res.text()}`);
848
+ const data = await res.json();
849
+ return ((_a3 = data.matches) != null ? _a3 : []).map((m) => {
850
+ var _a4, _b2;
851
+ return {
852
+ id: m.id,
853
+ score: (_a4 = m.score) != null ? _a4 : 0,
854
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
855
+ metadata: m.metadata
856
+ };
857
+ });
858
+ }
859
+ const targetIdx = await this.getActiveIndex(namespace);
749
860
  const result = await targetIdx.query(__spreadValues({
750
861
  vector,
751
862
  topK,
752
863
  includeMetadata: true
753
864
  }, Object.keys(pineconeFilter).length > 0 ? { filter: pineconeFilter } : {}));
754
- return ((_a3 = result.matches) != null ? _a3 : []).map((m) => {
755
- var _a4, _b;
865
+ return ((_b = result.matches) != null ? _b : []).map((m) => {
866
+ var _a4, _b2;
756
867
  return {
757
868
  id: m.id,
758
869
  score: (_a4 = m.score) != null ? _a4 : 0,
759
- content: ((_b = m.metadata) == null ? void 0 : _b.content) || "",
870
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
760
871
  metadata: m.metadata
761
872
  };
762
873
  });
@@ -2573,9 +2684,6 @@ var import_server = require("next/server");
2573
2684
  // src/core/ConfigResolver.ts
2574
2685
  init_templateUtils();
2575
2686
 
2576
- // src/core/LicenseVerifier.ts
2577
- var crypto = __toESM(require("crypto"));
2578
-
2579
2687
  // src/exceptions/index.ts
2580
2688
  var RetrivoraError = class extends Error {
2581
2689
  constructor(message, code, details) {
@@ -2651,29 +2759,18 @@ function wrapError(err, defaultCode, defaultMessage) {
2651
2759
  }
2652
2760
 
2653
2761
  // src/core/LicenseVerifier.ts
2654
- var LicenseVerifier = class {
2762
+ var _LicenseVerifier = class _LicenseVerifier {
2763
+ // Cache verified license for 5 minutes
2655
2764
  /**
2656
- * Decodes, verifies signature, and checks metadata of a license key.
2765
+ * Validates the license key asynchronously by calling the Retrivora backend.
2657
2766
  *
2658
2767
  * @param licenseKey - Base64url signed JWT license key.
2659
2768
  * @param currentProjectId - Project namespace ID.
2660
- * @param publicKeyOverride - Optional override for unit/integration tests.
2769
+ * @param provider - Optional provider for tier checks.
2661
2770
  */
2662
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
2771
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
2663
2772
  const isProduction = process.env.NODE_ENV === "production";
2664
2773
  const now = Date.now();
2665
- if (licenseKey) {
2666
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2667
- const cached = this.cache.get(cacheKey);
2668
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2669
- const currentTimestampSec = Math.floor(now / 1e3);
2670
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2671
- this.cache.delete(cacheKey);
2672
- } else {
2673
- return cached.payload;
2674
- }
2675
- }
2676
- }
2677
2774
  if (!licenseKey) {
2678
2775
  if (isProduction) {
2679
2776
  throw new ConfigurationException(
@@ -2690,52 +2787,61 @@ var LicenseVerifier = class {
2690
2787
  tier: "hobby"
2691
2788
  };
2692
2789
  }
2693
- try {
2694
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
2695
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2696
- const parts = rawToken.split(".");
2697
- if (parts.length !== 3) {
2698
- throw new Error("Malformed token structure (expected 3 parts).");
2699
- }
2700
- const [headerB64, payloadB64, signatureB64] = parts;
2701
- const dataToVerify = `${headerB64}.${payloadB64}`;
2702
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
2703
- const signature = Buffer.from(signatureB64, "base64url");
2704
- const data = Buffer.from(dataToVerify);
2705
- const isValid = crypto.verify(
2706
- "sha256",
2707
- data,
2708
- publicKey,
2709
- signature
2710
- );
2711
- if (!isValid) {
2712
- throw new Error("Signature verification failed.");
2790
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
2791
+ const cached = this.cache.get(cacheKey);
2792
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2793
+ const currentTimestampSec = Math.floor(now / 1e3);
2794
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2795
+ this.cache.delete(cacheKey);
2796
+ } else {
2797
+ return cached.payload;
2713
2798
  }
2714
- const payload = JSON.parse(
2715
- Buffer.from(payloadB64, "base64url").toString("utf8")
2716
- );
2717
- if (!payload.projectId) {
2718
- throw new Error('License payload is missing "projectId".');
2799
+ }
2800
+ try {
2801
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
2802
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
2803
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
2719
2804
  }
2720
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
2721
- if (!isProjectMatch) {
2722
- throw new Error(
2723
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
2724
- );
2805
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
2806
+ const response = await fetch(endpoint, {
2807
+ method: "POST",
2808
+ headers: {
2809
+ "Content-Type": "application/json",
2810
+ "x-license-key": licenseKey
2811
+ },
2812
+ body: JSON.stringify({
2813
+ licenseKey,
2814
+ projectId: currentProjectId,
2815
+ provider
2816
+ })
2817
+ });
2818
+ if (!response.ok) {
2819
+ let errMessage = `HTTP ${response.status}`;
2820
+ try {
2821
+ const body = await response.json();
2822
+ if (body.message) errMessage = body.message;
2823
+ } catch (e) {
2824
+ }
2825
+ throw new Error(errMessage);
2725
2826
  }
2726
- if (!payload.expiresAt) {
2727
- throw new Error('License payload is missing expiration ("expiresAt").');
2827
+ const data = await response.json();
2828
+ if (!data.valid) {
2829
+ throw new Error(data.message || "License validation failed by server.");
2728
2830
  }
2729
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
2730
- if (currentTimestampSec > payload.expiresAt) {
2731
- throw new Error(
2732
- `License key has expired. Expiration: ${new Date(
2733
- payload.expiresAt * 1e3
2734
- ).toDateString()}`
2735
- );
2831
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
2832
+ if (data.expiresAt) {
2833
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
2736
2834
  }
2835
+ const tier = _LicenseVerifier.extractTier(licenseKey);
2836
+ const payload = {
2837
+ projectId: currentProjectId,
2838
+ expiresAt: expiresAtNum,
2839
+ tier,
2840
+ licenseStatus: data.licenseStatus,
2841
+ minimumSupportedVersion: data.minimumSupportedVersion,
2842
+ forceUpgrade: data.forceUpgrade
2843
+ };
2737
2844
  if (isProduction && provider) {
2738
- const tier = (payload.tier || "").toLowerCase();
2739
2845
  const normalizedProvider = provider.toLowerCase();
2740
2846
  if (tier === "hobby") {
2741
2847
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -2763,15 +2869,12 @@ var LicenseVerifier = class {
2763
2869
  }
2764
2870
  }
2765
2871
  }
2766
- if (licenseKey) {
2767
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2768
- this.cache.set(cacheKey, { payload, cachedAt: now });
2769
- }
2872
+ this.cache.set(cacheKey, { payload, cachedAt: now });
2770
2873
  return payload;
2771
2874
  } catch (err) {
2772
2875
  const message = err instanceof Error ? err.message : String(err);
2773
2876
  throw new ConfigurationException(
2774
- `[Retrivora SDK] License key validation failed: ${message}`
2877
+ `[Retrivora SDK] License key validation failed via API: ${message}`
2775
2878
  );
2776
2879
  }
2777
2880
  }
@@ -2840,23 +2943,25 @@ var LicenseVerifier = class {
2840
2943
  }
2841
2944
  }
2842
2945
  }
2946
+ static extractTier(licenseKey) {
2947
+ if (!licenseKey) return "hobby";
2948
+ try {
2949
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
2950
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2951
+ const parts = rawToken.split(".");
2952
+ if (parts.length === 3) {
2953
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2954
+ if (decodedPayload.tier) return decodedPayload.tier;
2955
+ }
2956
+ } catch (e) {
2957
+ }
2958
+ return "hobby";
2959
+ }
2843
2960
  };
2844
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
2845
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
2846
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
2847
- // Cache verified license for 60 seconds
2848
- // Retrivora's Public Key used to verify the license key signature.
2849
- // In production, this matches the private key held by Retrivora SaaS.
2850
- // Rotate this key only when the signing private key is replaced.
2851
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
2852
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
2853
- jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
2854
- Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
2855
- 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
2856
- sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
2857
- 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
2858
- 6QIDAQAB
2859
- -----END PUBLIC KEY-----`;
2961
+ // In-memory cache to save network overhead on hot paths.
2962
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
2963
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
2964
+ var LicenseVerifier = _LicenseVerifier;
2860
2965
 
2861
2966
  // src/config/constants.ts
2862
2967
  var VECTOR_DB_PROVIDERS = [
@@ -2928,7 +3033,7 @@ function readEnum(env, name, fallback, allowed) {
2928
3033
  throw new Error(`[getRagConfig] ${name} must be one of: ${allowed.join(", ")}`);
2929
3034
  }
2930
3035
  function getEnvConfig(env = process.env, base) {
2931
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb, _ob, _pb, _qb, _rb, _sb, _tb, _ub, _vb, _wb, _xb, _yb, _zb, _Ab, _Bb, _Cb, _Db, _Eb, _Fb, _Gb, _Hb;
3036
+ var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb, _ob, _pb, _qb, _rb, _sb, _tb, _ub, _vb, _wb, _xb, _yb, _zb, _Ab, _Bb, _Cb, _Db, _Eb, _Fb, _Gb, _Hb, _Ib;
2932
3037
  const licenseKey = (_d = (_c = (_b = (_a3 = readString(env, "RAG_LICENSE_KEY")) != null ? _a3 : readString(env, "RETRIVORA_LICENSE_KEY")) != null ? _b : readString(env, "NEXT_PUBLIC_RETRIVORA_LICENSE_KEY")) != null ? _c : readString(env, "LICENSE_KEY")) != null ? _d : base == null ? void 0 : base.licenseKey;
2933
3038
  const jwtProjectId = (() => {
2934
3039
  if (!licenseKey) return void 0;
@@ -3013,8 +3118,7 @@ function getEnvConfig(env = process.env, base) {
3013
3118
  const isFreeTier2 = (() => {
3014
3119
  if (!licenseKey) return true;
3015
3120
  try {
3016
- const payload = LicenseVerifier.verify(licenseKey, projectId);
3017
- const tier = (payload.tier || "").toLowerCase();
3121
+ const tier = LicenseVerifier.extractTier(licenseKey).toLowerCase();
3018
3122
  return tier === "free_trial" || tier === "free_tier" || tier === "free" || tier === "hobby";
3019
3123
  } catch (e) {
3020
3124
  return true;
@@ -3022,14 +3126,15 @@ function getEnvConfig(env = process.env, base) {
3022
3126
  })();
3023
3127
  const tierBasedLLMModel = isFreeTier2 ? "llama-3.1-8b-instant" : "llama-3.3-70b-versatile";
3024
3128
  const tierBasedEmbeddingModel = isFreeTier2 ? "text-embedding-004" : "text-embedding-004";
3025
- const defaultGatewayUrl = "https://llm.retrivora.com/api/v1";
3129
+ const controlPlaneUrl = (_qa = readString(env, "RETRIVORA_CONTROL_PLANE_URL")) != null ? _qa : readString(env, "NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL");
3130
+ const defaultGatewayUrl = controlPlaneUrl ? `${controlPlaneUrl.replace(/\/$/, "")}/api/v1` : "https://llm.retrivora.com/api/v1";
3026
3131
  const rt = _runtimeConfig;
3027
3132
  const defaultLlmProvider = "universal_rest";
3028
- const llmProvider = (_sa = (_ra = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _ra : (_qa = base == null ? void 0 : base.llm) == null ? void 0 : _qa.provider) != null ? _sa : defaultLlmProvider;
3029
- const llmBaseUrl = (_xa = (_wa = (_va = (_ta = readString(env, "LITELLM_BASE_URL")) != null ? _ta : readString(env, "LLM_BASE_URL")) != null ? _va : (_ua = base == null ? void 0 : base.llm) == null ? void 0 : _ua.baseUrl) != null ? _wa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _xa : defaultGatewayUrl;
3030
- const llmModel = (_Ba = (_Aa = (_za = readString(env, "LLM_MODEL")) != null ? _za : (_ya = base == null ? void 0 : base.llm) == null ? void 0 : _ya.model) != null ? _Aa : rt == null ? void 0 : rt.llmModel) != null ? _Ba : tierBasedLLMModel;
3031
- const llmApiKey = (_Fa = (_Ea = (_Ca = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ca : rt == null ? void 0 : rt.litellmApiKey) != null ? _Ea : (_Da = base == null ? void 0 : base.llm) == null ? void 0 : _Da.apiKey) != null ? _Fa : licenseKey;
3032
- const llmProfile = (_Ja = (_Ia = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ia : (_Ha = (_Ga = base == null ? void 0 : base.llm) == null ? void 0 : _Ga.options) == null ? void 0 : _Ha.profile) != null ? _Ja : "litellm";
3133
+ const llmProvider = (_ta = (_sa = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _sa : (_ra = base == null ? void 0 : base.llm) == null ? void 0 : _ra.provider) != null ? _ta : defaultLlmProvider;
3134
+ const llmBaseUrl = (_ya = (_xa = (_wa = (_ua = readString(env, "LITELLM_BASE_URL")) != null ? _ua : readString(env, "LLM_BASE_URL")) != null ? _wa : (_va = base == null ? void 0 : base.llm) == null ? void 0 : _va.baseUrl) != null ? _xa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _ya : defaultGatewayUrl;
3135
+ const llmModel = (_Ca = (_Ba = (_Aa = readString(env, "LLM_MODEL")) != null ? _Aa : (_za = base == null ? void 0 : base.llm) == null ? void 0 : _za.model) != null ? _Ba : rt == null ? void 0 : rt.llmModel) != null ? _Ca : tierBasedLLMModel;
3136
+ const llmApiKey = (_Ga = (_Fa = (_Da = readString(env, "LITELLM_MASTER_KEY")) != null ? _Da : rt == null ? void 0 : rt.litellmApiKey) != null ? _Fa : (_Ea = base == null ? void 0 : base.llm) == null ? void 0 : _Ea.apiKey) != null ? _Ga : licenseKey;
3137
+ const llmProfile = (_Ka = (_Ja = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ja : (_Ia = (_Ha = base == null ? void 0 : base.llm) == null ? void 0 : _Ha.options) == null ? void 0 : _Ia.profile) != null ? _Ka : "litellm";
3033
3138
  console.log("[serverConfig] \u{1F527} LLM Configuration:", {
3034
3139
  baseUrl: llmBaseUrl,
3035
3140
  model: llmModel,
@@ -3038,17 +3143,24 @@ function getEnvConfig(env = process.env, base) {
3038
3143
  source: (rt == null ? void 0 : rt.llmModel) ? "runtime-injected" : "env/fallback"
3039
3144
  });
3040
3145
  const defaultEmbeddingProvider = "universal_rest";
3041
- const embeddingProvider = (_Ma = (_La = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _La : (_Ka = base == null ? void 0 : base.embedding) == null ? void 0 : _Ka.provider) != null ? _Ma : defaultEmbeddingProvider;
3042
- const embeddingBaseUrl = (_Ta = (_Sa = (_Ra = (_Qa = (_Oa = (_Na = readString(env, "LITELLM_BASE_URL")) != null ? _Na : readString(env, "EMBEDDING_BASE_URL")) != null ? _Oa : readString(env, "LLM_BASE_URL")) != null ? _Qa : (_Pa = base == null ? void 0 : base.embedding) == null ? void 0 : _Pa.baseUrl) != null ? _Ra : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Sa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Ta : defaultGatewayUrl;
3043
- const embeddingModel = (_Xa = (_Wa = (_Va = readString(env, "EMBEDDING_MODEL")) != null ? _Va : (_Ua = base == null ? void 0 : base.embedding) == null ? void 0 : _Ua.model) != null ? _Wa : rt == null ? void 0 : rt.embeddingModel) != null ? _Xa : tierBasedEmbeddingModel;
3044
- const embeddingApiKey = (_$a = (__a = (_Ya = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ya : rt == null ? void 0 : rt.litellmApiKey) != null ? __a : (_Za = base == null ? void 0 : base.embedding) == null ? void 0 : _Za.apiKey) != null ? _$a : licenseKey;
3045
- const embeddingProfile = (_db = (_cb = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _cb : (_bb = (_ab = base == null ? void 0 : base.embedding) == null ? void 0 : _ab.options) == null ? void 0 : _bb.profile) != null ? _db : "litellm";
3146
+ const embeddingProvider = (_Na = (_Ma = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _Ma : (_La = base == null ? void 0 : base.embedding) == null ? void 0 : _La.provider) != null ? _Na : defaultEmbeddingProvider;
3147
+ const embeddingBaseUrl = (_Ua = (_Ta = (_Sa = (_Ra = (_Pa = (_Oa = readString(env, "LITELLM_BASE_URL")) != null ? _Oa : readString(env, "EMBEDDING_BASE_URL")) != null ? _Pa : readString(env, "LLM_BASE_URL")) != null ? _Ra : (_Qa = base == null ? void 0 : base.embedding) == null ? void 0 : _Qa.baseUrl) != null ? _Sa : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Ta : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Ua : defaultGatewayUrl;
3148
+ const embeddingModel = (_Ya = (_Xa = (_Wa = readString(env, "EMBEDDING_MODEL")) != null ? _Wa : (_Va = base == null ? void 0 : base.embedding) == null ? void 0 : _Va.model) != null ? _Xa : rt == null ? void 0 : rt.embeddingModel) != null ? _Ya : tierBasedEmbeddingModel;
3149
+ const embeddingApiKey = (_ab = (_$a = (_Za = readString(env, "LITELLM_MASTER_KEY")) != null ? _Za : rt == null ? void 0 : rt.litellmApiKey) != null ? _$a : (__a = base == null ? void 0 : base.embedding) == null ? void 0 : __a.apiKey) != null ? _ab : licenseKey;
3150
+ const embeddingProfile = (_eb = (_db = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _db : (_cb = (_bb = base == null ? void 0 : base.embedding) == null ? void 0 : _bb.options) == null ? void 0 : _cb.profile) != null ? _eb : "litellm";
3151
+ console.log("[serverConfig] \u{1F527} Embedding Configuration:", {
3152
+ baseUrl: embeddingBaseUrl,
3153
+ model: embeddingModel,
3154
+ provider: embeddingProvider,
3155
+ hasApiKey: !!embeddingApiKey,
3156
+ source: (rt == null ? void 0 : rt.embeddingModel) ? "runtime-injected" : "env/fallback"
3157
+ });
3046
3158
  return __spreadProps(__spreadValues({
3047
3159
  projectId,
3048
3160
  licenseKey,
3049
3161
  vectorDb: {
3050
3162
  provider: vectorProvider,
3051
- indexName: (_fb = (_eb = readString(env, "VECTOR_DB_INDEX")) != null ? _eb : vectorDbOptions.indexName) != null ? _fb : "rag-index",
3163
+ indexName: (_gb = (_fb = readString(env, "VECTOR_DB_INDEX")) != null ? _fb : vectorDbOptions.indexName) != null ? _gb : "rag-index",
3052
3164
  options: vectorDbOptions
3053
3165
  },
3054
3166
  llm: {
@@ -3078,30 +3190,30 @@ function getEnvConfig(env = process.env, base) {
3078
3190
  }
3079
3191
  },
3080
3192
  ui: {
3081
- title: (_hb = (_gb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _gb : readString(env, "UI_TITLE")) != null ? _hb : "AI Assistant",
3082
- subtitle: (_jb = (_ib = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _ib : readString(env, "UI_SUBTITLE")) != null ? _jb : "Powered by RAG",
3083
- primaryColor: (_lb = (_kb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _kb : readString(env, "UI_PRIMARY_COLOR")) != null ? _lb : "#10b981",
3084
- accentColor: (_nb = (_mb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _mb : readString(env, "UI_ACCENT_COLOR")) != null ? _nb : "#3b82f6",
3085
- logoUrl: (_ob = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _ob : readString(env, "UI_LOGO_URL"),
3086
- placeholder: (_qb = (_pb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _pb : readString(env, "UI_PLACEHOLDER")) != null ? _qb : "Ask me anything\u2026",
3087
- showSources: ((_sb = (_rb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _rb : readString(env, "UI_SHOW_SOURCES")) != null ? _sb : "true") !== "false",
3088
- welcomeMessage: (_ub = (_tb = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _tb : readString(env, "UI_WELCOME_MESSAGE")) != null ? _ub : "Hello! I'm your AI assistant. Ask me anything about your documents.",
3089
- visualStyle: (_wb = (_vb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _vb : readString(env, "UI_VISUAL_STYLE")) != null ? _wb : "glass",
3090
- borderRadius: (_yb = (_xb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _xb : readString(env, "UI_BORDER_RADIUS")) != null ? _yb : "xl",
3091
- allowUpload: ((_Ab = (_zb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _zb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Ab : "false") === "true"
3193
+ title: (_ib = (_hb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _hb : readString(env, "UI_TITLE")) != null ? _ib : "AI Assistant",
3194
+ subtitle: (_kb = (_jb = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _jb : readString(env, "UI_SUBTITLE")) != null ? _kb : "Powered by RAG",
3195
+ primaryColor: (_mb = (_lb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _lb : readString(env, "UI_PRIMARY_COLOR")) != null ? _mb : "#10b981",
3196
+ accentColor: (_ob = (_nb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _nb : readString(env, "UI_ACCENT_COLOR")) != null ? _ob : "#3b82f6",
3197
+ logoUrl: (_pb = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _pb : readString(env, "UI_LOGO_URL"),
3198
+ placeholder: (_rb = (_qb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _qb : readString(env, "UI_PLACEHOLDER")) != null ? _rb : "Ask me anything\u2026",
3199
+ showSources: ((_tb = (_sb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _sb : readString(env, "UI_SHOW_SOURCES")) != null ? _tb : "true") !== "false",
3200
+ welcomeMessage: (_vb = (_ub = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _ub : readString(env, "UI_WELCOME_MESSAGE")) != null ? _vb : "Hello! I'm your AI assistant. Ask me anything about your documents.",
3201
+ visualStyle: (_xb = (_wb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _wb : readString(env, "UI_VISUAL_STYLE")) != null ? _xb : "glass",
3202
+ borderRadius: (_zb = (_yb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _yb : readString(env, "UI_BORDER_RADIUS")) != null ? _zb : "xl",
3203
+ allowUpload: ((_Bb = (_Ab = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _Ab : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Bb : "false") === "true"
3092
3204
  },
3093
3205
  rag: {
3094
3206
  topK: readNumber(env, "RAG_TOP_K", 5),
3095
3207
  scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
3096
3208
  chunkSize: readNumber(env, "RAG_CHUNK_SIZE", 1e3),
3097
3209
  chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", 200),
3098
- filterableFields: (_Bb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Bb.split(",").map((f) => f.trim()),
3210
+ filterableFields: (_Cb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Cb.split(",").map((f) => f.trim()),
3099
3211
  // Query pipeline toggles — read from .env.local
3100
3212
  useQueryTransformation: readString(env, "RAG_USE_QUERY_TRANSFORMATION") === "true",
3101
3213
  useReranking: readString(env, "RAG_USE_RERANKING") === "true",
3102
3214
  useGraphRetrieval: readString(env, "RAG_USE_GRAPH_RETRIEVAL") === "true",
3103
- architecture: (_Cb = readString(env, "RAG_ARCHITECTURE")) != null ? _Cb : "simple",
3104
- chunkingStrategy: (_Db = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Db : "recursive",
3215
+ architecture: (_Db = readString(env, "RAG_ARCHITECTURE")) != null ? _Db : "simple",
3216
+ chunkingStrategy: (_Eb = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Eb : "recursive",
3105
3217
  uiMapping: (() => {
3106
3218
  const raw = readString(env, "RAG_UI_MAPPING");
3107
3219
  if (!raw) return void 0;
@@ -3114,7 +3226,7 @@ function getEnvConfig(env = process.env, base) {
3114
3226
  },
3115
3227
  telemetry: {
3116
3228
  enabled: telemetryEnabled,
3117
- url: (_Hb = (_Gb = (_Eb = readString(env, "TELEMETRY_URL")) != null ? _Eb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Gb : (_Fb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Fb.url) != null ? _Hb : "https://www.retrivora.com/api/telemetry"
3229
+ url: (_Ib = (_Hb = (_Fb = readString(env, "TELEMETRY_URL")) != null ? _Fb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Hb : (_Gb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Gb.url) != null ? _Ib : "https://www.retrivora.com/api/telemetry"
3118
3230
  }
3119
3231
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
3120
3232
  graphDb: {
@@ -4425,6 +4537,12 @@ var UniversalLLMAdapter = class {
4425
4537
  this.resolvedHeaders = __spreadValues(__spreadValues({
4426
4538
  "Content-Type": "application/json"
4427
4539
  }, config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}), this.opts.headers || {});
4540
+ console.log("[UniversalLLMAdapter] Initialized with:", {
4541
+ model: this.model,
4542
+ baseUrl: this.baseUrl,
4543
+ hasApiKey: !!this.apiKey,
4544
+ apiKeyPrefix: this.apiKey ? `${this.apiKey.slice(0, 12)}...` : void 0
4545
+ });
4428
4546
  this.http = import_axios2.default.create({
4429
4547
  baseURL: this.baseUrl,
4430
4548
  headers: this.resolvedHeaders,
@@ -4637,14 +4755,21 @@ ${context != null ? context : "None"}` },
4637
4755
  });
4638
4756
  }
4639
4757
  async embed(text) {
4640
- var _a3, _b, _c, _d, _e, _f, _g2;
4758
+ var _a3, _b, _c, _d, _e, _f, _g2, _h;
4641
4759
  const path2 = (_a3 = this.opts.embedPath) != null ? _a3 : "/embeddings";
4642
4760
  const payload = this.opts.embedPayloadTemplate ? buildPayload(this.opts.embedPayloadTemplate, { input: text, model: this.model }) : { input: text, model: this.model };
4643
4761
  try {
4762
+ console.log(`[UniversalLLMAdapter] Posting to embedding endpoint: ${this.baseUrl}${path2}`, {
4763
+ model: this.model,
4764
+ inputLength: typeof text === "string" ? text.length : "unknown"
4765
+ });
4644
4766
  const { data } = await this.http.post(path2, payload);
4645
4767
  const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4646
4768
  const vector = resolvePath(data, extractPath);
4647
- if (Array.isArray(vector)) return vector;
4769
+ if (Array.isArray(vector)) {
4770
+ console.log(`[UniversalLLMAdapter] Embedding HTTP request successful. Vector size: ${vector.length}`);
4771
+ return vector;
4772
+ }
4648
4773
  console.warn(
4649
4774
  `[UniversalLLMAdapter] Embedding API returned unexpected format for path '${extractPath}'. Response:`,
4650
4775
  data
@@ -4652,14 +4777,14 @@ ${context != null ? context : "None"}` },
4652
4777
  } catch (err) {
4653
4778
  console.warn(
4654
4779
  `[UniversalLLMAdapter] HTTP embedding request failed: ${(err == null ? void 0 : err.message) || err}`,
4655
- { path: path2, model: this.model }
4780
+ { path: path2, model: this.model, response: (_c = err == null ? void 0 : err.response) == null ? void 0 : _c.data }
4656
4781
  );
4657
4782
  const _g3 = globalThis;
4658
4783
  const dispatchEmbed = _g3.__retrivoraDispatchEmbedding;
4659
4784
  if (typeof dispatchEmbed === "function") {
4660
4785
  try {
4661
4786
  const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4662
- if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4787
+ if ((_e = (_d = res == null ? void 0 : res.data) == null ? void 0 : _d[0]) == null ? void 0 : _e.embedding) {
4663
4788
  return res.data[0].embedding;
4664
4789
  }
4665
4790
  } catch (dispatchErr) {
@@ -4668,10 +4793,12 @@ ${context != null ? context : "None"}` },
4668
4793
  }
4669
4794
  }
4670
4795
  try {
4796
+ console.log(`[UniversalLLMAdapter] Retrying embedding request to: ${this.baseUrl}${path2}`);
4671
4797
  const { data } = await this.http.post(path2, payload);
4672
- const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4798
+ const extractPath = (_f = this.opts.embedExtractPath) != null ? _f : "data[0].embedding";
4673
4799
  const vector = resolvePath(data, extractPath);
4674
4800
  if (Array.isArray(vector)) {
4801
+ console.log(`[UniversalLLMAdapter] Retry embedding HTTP request successful. Vector size: ${vector.length}`);
4675
4802
  return vector;
4676
4803
  }
4677
4804
  console.error(
@@ -4684,7 +4811,7 @@ ${context != null ? context : "None"}` },
4684
4811
  } catch (err) {
4685
4812
  console.error(
4686
4813
  `[UniversalLLMAdapter] Both embedding attempts failed. Path: ${path2}, Model: ${this.model}`,
4687
- { error: err == null ? void 0 : err.message, statusCode: (_f = err == null ? void 0 : err.response) == null ? void 0 : _f.status, response: (_g2 = err == null ? void 0 : err.response) == null ? void 0 : _g2.data }
4814
+ { error: err == null ? void 0 : err.message, statusCode: (_g2 = err == null ? void 0 : err.response) == null ? void 0 : _g2.status, response: (_h = err == null ? void 0 : err.response) == null ? void 0 : _h.data }
4688
4815
  );
4689
4816
  throw new Error(
4690
4817
  `[UniversalLLMAdapter] Failed to generate embedding after 2 attempts: ${(err == null ? void 0 : err.message) || err}`
@@ -10089,7 +10216,7 @@ var VectorPlugin = class {
10089
10216
  this.validationPromise = (async () => {
10090
10217
  var _a3;
10091
10218
  await ConfigValidator.validateAndThrow(resolvedConfig);
10092
- LicenseVerifier.verify(
10219
+ await LicenseVerifier.verifyAsync(
10093
10220
  resolvedConfig.licenseKey,
10094
10221
  resolvedConfig.projectId,
10095
10222
  (_a3 = resolvedConfig.vectorDb) == null ? void 0 : _a3.provider
@@ -10362,7 +10489,7 @@ var DatabaseStorage = class {
10362
10489
  * In non-production (development / test) environments this is a complete no-op —
10363
10490
  * all History and Feedback features are freely accessible for local development.
10364
10491
  */
10365
- checkPremiumSubscription() {
10492
+ async checkPremiumSubscription() {
10366
10493
  if (process.env.NODE_ENV !== "production") {
10367
10494
  return;
10368
10495
  }
@@ -10372,7 +10499,7 @@ var DatabaseStorage = class {
10372
10499
  );
10373
10500
  }
10374
10501
  try {
10375
- const payload = LicenseVerifier.verify(this.config.licenseKey, this.config.projectId);
10502
+ const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
10376
10503
  const tier = (payload.tier || "").toLowerCase();
10377
10504
  if (tier !== "premium" && tier !== "enterprise" && tier !== "growth" && tier !== "pro" && tier !== "developer_pro" && tier !== "free_trial" && tier !== "free_tier" && tier !== "free" && tier !== "hobby") {
10378
10505
  throw new Error(
@@ -10385,16 +10512,16 @@ var DatabaseStorage = class {
10385
10512
  );
10386
10513
  }
10387
10514
  }
10388
- checkHistoryEnabled() {
10515
+ async checkHistoryEnabled() {
10389
10516
  var _a3, _b;
10390
- this.checkPremiumSubscription();
10517
+ await this.checkPremiumSubscription();
10391
10518
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.history) == null ? void 0 : _b.enabled) === false) {
10392
10519
  throw new Error("[Retrivora SDK] Chat History is disabled in RagConfig.");
10393
10520
  }
10394
10521
  }
10395
- checkFeedbackEnabled() {
10522
+ async checkFeedbackEnabled() {
10396
10523
  var _a3, _b;
10397
- this.checkPremiumSubscription();
10524
+ await this.checkPremiumSubscription();
10398
10525
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.feedback) == null ? void 0 : _b.enabled) === false) {
10399
10526
  throw new Error("[Retrivora SDK] User Feedback is disabled in RagConfig.");
10400
10527
  }
@@ -10500,7 +10627,7 @@ var DatabaseStorage = class {
10500
10627
  }
10501
10628
  // ─── Message History Operations ──────────────────────────────────────────
10502
10629
  async saveMessage(sessionId, message) {
10503
- this.checkHistoryEnabled();
10630
+ await this.checkHistoryEnabled();
10504
10631
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10505
10632
  const msgId = message.id || `msg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10506
10633
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -10563,7 +10690,7 @@ var DatabaseStorage = class {
10563
10690
  }
10564
10691
  }
10565
10692
  async getHistory(sessionId, projectIds) {
10566
- this.checkHistoryEnabled();
10693
+ await this.checkHistoryEnabled();
10567
10694
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10568
10695
  return [];
10569
10696
  }
@@ -10597,7 +10724,7 @@ var DatabaseStorage = class {
10597
10724
  }
10598
10725
  }
10599
10726
  async clearHistory(sessionId, projectIds) {
10600
- this.checkHistoryEnabled();
10727
+ await this.checkHistoryEnabled();
10601
10728
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10602
10729
  return;
10603
10730
  }
@@ -10633,7 +10760,7 @@ var DatabaseStorage = class {
10633
10760
  );
10634
10761
  }
10635
10762
  async listSessions(projectIds) {
10636
- this.checkHistoryEnabled();
10763
+ await this.checkHistoryEnabled();
10637
10764
  let raw = [];
10638
10765
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10639
10766
  const pool = await this.getPGPool();
@@ -10652,7 +10779,7 @@ var DatabaseStorage = class {
10652
10779
  }
10653
10780
  // ─── Feedback Operations ──────────────────────────────────────────────────
10654
10781
  async saveFeedback(feedback) {
10655
- this.checkFeedbackEnabled();
10782
+ await this.checkFeedbackEnabled();
10656
10783
  const id = `fb_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10657
10784
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10658
10785
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -10702,7 +10829,7 @@ var DatabaseStorage = class {
10702
10829
  }
10703
10830
  }
10704
10831
  async getFeedback(messageId, projectIds) {
10705
- this.checkFeedbackEnabled();
10832
+ await this.checkFeedbackEnabled();
10706
10833
  let item = null;
10707
10834
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10708
10835
  const pool = await this.getPGPool();
@@ -10738,7 +10865,7 @@ var DatabaseStorage = class {
10738
10865
  return item;
10739
10866
  }
10740
10867
  async listFeedback(projectIds) {
10741
- this.checkFeedbackEnabled();
10868
+ await this.checkFeedbackEnabled();
10742
10869
  let raw = [];
10743
10870
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10744
10871
  const pool = await this.getPGPool();
@@ -10888,12 +11015,23 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
10888
11015
  var _a3;
10889
11016
  return req.headers.get("x-license-key") || bodyLicenseKey || ((_a3 = req.headers.get("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || process.env.RAG_LICENSE_KEY || "";
10890
11017
  }
10891
- function enforceLicense(req, config, bodyLicenseKey) {
11018
+ async function enforceLicense(req, config, bodyLicenseKey) {
10892
11019
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
10893
11020
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
10894
11021
  const projectId = config.projectId || "";
10895
11022
  try {
10896
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11023
+ let payload;
11024
+ try {
11025
+ payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11026
+ } catch (err) {
11027
+ return {
11028
+ ok: false,
11029
+ response: import_server.NextResponse.json(
11030
+ { error: `License validation failed: ${err.message}` },
11031
+ { status: 401 }
11032
+ )
11033
+ };
11034
+ }
10897
11035
  return { ok: true, payload };
10898
11036
  } catch (err) {
10899
11037
  const message = err instanceof Error ? err.message : "Missing or invalid RETRIVORA_LICENSE_KEY. Set NEXT_PUBLIC_RETRIVORA_LICENSE_KEY in your environment or contact your administrator.";
@@ -11068,7 +11206,7 @@ function createChatHandler(configOrPlugin, options) {
11068
11206
  try {
11069
11207
  const body = await req.json();
11070
11208
  const bodyObj = body != null ? body : {};
11071
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11209
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11072
11210
  if (!licenseCheck.ok) return licenseCheck.response;
11073
11211
  if (isFreeTier(licenseCheck.payload.tier)) {
11074
11212
  const estimatedInputTokens = Math.ceil(
@@ -11162,7 +11300,7 @@ function createStreamHandler(configOrPlugin, options) {
11162
11300
  });
11163
11301
  }
11164
11302
  const bodyObj = body != null ? body : {};
11165
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11303
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11166
11304
  if (!licenseCheck.ok) return licenseCheck.response;
11167
11305
  if (isFreeTier(licenseCheck.payload.tier)) {
11168
11306
  const estimatedInputTokens = Math.ceil(
@@ -11327,7 +11465,7 @@ function createIngestHandler(configOrPlugin, options) {
11327
11465
  const config = plugin.getConfig();
11328
11466
  try {
11329
11467
  const body = await req.json();
11330
- const licenseCheck = enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11468
+ const licenseCheck = await enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11331
11469
  if (!licenseCheck.ok) return licenseCheck.response;
11332
11470
  const { documents, namespace } = body;
11333
11471
  if (!Array.isArray(documents) || documents.length === 0) {
@@ -11403,7 +11541,8 @@ function createLicenseHandler(configOrPlugin, options) {
11403
11541
  const rawKey = req.headers.get("x-license-key") || (body == null ? void 0 : body.licenseKey) || ((_a3 = req.headers.get("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || "";
11404
11542
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11405
11543
  const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11406
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11544
+ console.log(`[DEBUG] createLicenseHandler: projectId="${projectId}", body.projectId="${body == null ? void 0 : body.projectId}", config.projectId="${config.projectId}"`);
11545
+ const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11407
11546
  return import_server.NextResponse.json({
11408
11547
  valid: true,
11409
11548
  licenseStatus: "ACTIVE",
@@ -11437,7 +11576,7 @@ function createUploadHandler(configOrPlugin, options) {
11437
11576
  const authResult = await checkAuth(req, onAuthorize);
11438
11577
  if (authResult) return authResult;
11439
11578
  const config = plugin.getConfig();
11440
- const licenseCheck = enforceLicense(req, config);
11579
+ const licenseCheck = await enforceLicense(req, config);
11441
11580
  if (!licenseCheck.ok) return licenseCheck.response;
11442
11581
  try {
11443
11582
  const formData = await req.formData();
@@ -11581,7 +11720,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11581
11720
  const authResult = await checkAuth(req, onAuthorize);
11582
11721
  if (authResult) return authResult;
11583
11722
  const config = plugin.getConfig();
11584
- const licenseCheck = enforceLicense(req, config);
11723
+ const licenseCheck = await enforceLicense(req, config);
11585
11724
  if (!licenseCheck.ok) return licenseCheck.response;
11586
11725
  let effectiveLicensePayload = licenseCheck.payload;
11587
11726
  try {
@@ -11594,7 +11733,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11594
11733
  namespace = body.namespace;
11595
11734
  bodyLicenseKey = body.licenseKey;
11596
11735
  if (bodyLicenseKey) {
11597
- const recheck = enforceLicense(req, config, bodyLicenseKey);
11736
+ const recheck = await enforceLicense(req, config, bodyLicenseKey);
11598
11737
  if (!recheck.ok) return recheck.response;
11599
11738
  effectiveLicensePayload = recheck.payload;
11600
11739
  }