@retrivora-ai/rag-engine 2.3.4 → 2.3.6

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.
Files changed (36) hide show
  1. package/dist/{BatchProcessor-CQDtlggz.d.ts → BatchProcessor-ByBl-1MA.d.ts} +81 -3
  2. package/dist/{BatchProcessor-tVzb9CdE.d.mts → BatchProcessor-Dfn23VAd.d.mts} +81 -3
  3. package/dist/{ILLMProvider-CcJ5N6XD.d.mts → ILLMProvider-B8TAVx3j.d.mts} +63 -1
  4. package/dist/{ILLMProvider-CcJ5N6XD.d.ts → ILLMProvider-B8TAVx3j.d.ts} +63 -1
  5. package/dist/handlers/index.d.mts +2 -2
  6. package/dist/handlers/index.d.ts +2 -2
  7. package/dist/handlers/index.js +419 -169
  8. package/dist/handlers/index.mjs +419 -169
  9. package/dist/{index-BwmyPJHp.d.ts → index-ejOWsaqb.d.ts} +1 -1
  10. package/dist/{index-CL-zF6bD.d.mts → index-xxQOFx-u.d.mts} +1 -1
  11. package/dist/index.css +9 -0
  12. package/dist/index.d.mts +19 -5
  13. package/dist/index.d.ts +19 -5
  14. package/dist/index.js +638 -189
  15. package/dist/index.mjs +678 -234
  16. package/dist/server.d.mts +6 -6
  17. package/dist/server.d.ts +6 -6
  18. package/dist/server.js +461 -173
  19. package/dist/server.mjs +457 -173
  20. package/package.json +2 -2
  21. package/src/components/ChatWidget.tsx +44 -19
  22. package/src/components/ChatWindow.tsx +30 -14
  23. package/src/components/ConfigProvider.tsx +86 -6
  24. package/src/components/DocumentUpload.tsx +8 -2
  25. package/src/config/RagConfig.ts +4 -0
  26. package/src/core/ConfigFetcher.ts +73 -11
  27. package/src/core/ConfigResolver.ts +1 -0
  28. package/src/core/LicenseValidator.ts +31 -13
  29. package/src/core/ProjectSettings.ts +247 -0
  30. package/src/handlers/index.ts +63 -7
  31. package/src/hooks/useProjectSettings.ts +105 -0
  32. package/src/index.css +9 -0
  33. package/src/index.ts +28 -0
  34. package/src/providers/vectordb/PineconeProvider.ts +17 -4
  35. package/src/server.ts +23 -1
  36. package/src/types/props.ts +14 -2
@@ -154,15 +154,342 @@ var init_BaseVectorProvider = __esm({
154
154
  }
155
155
  });
156
156
 
157
+ // src/core/ProjectSettings.ts
158
+ function createDefaultProjectSettings(projectId) {
159
+ return {
160
+ projectId,
161
+ branding: {
162
+ companyName: "Retrivora AI",
163
+ botName: "Retrivora Assistant",
164
+ welcomeMessage: "Hi, I can help you search your knowledge base.",
165
+ primaryColor: "#6366f1",
166
+ secondaryColor: "#8b5cf6",
167
+ fontFamily: "Inter",
168
+ borderRadius: 14,
169
+ logoUrl: "",
170
+ avatarUrl: "",
171
+ customCss: ""
172
+ },
173
+ ai: {
174
+ defaultModel: "llama-3.1-8b-instant",
175
+ embeddingModel: "text-embedding-3-small",
176
+ systemPrompt: "Answer using the connected knowledge base. Cite sources when available.",
177
+ memoryEnabled: true,
178
+ multiModelEnabled: true,
179
+ citationsEnabled: true,
180
+ fileUploadEnabled: true
181
+ },
182
+ auth: {
183
+ mode: "public",
184
+ allowedOrigins: [],
185
+ requireVerifiedEmail: false,
186
+ sessionTtlMinutes: 1440
187
+ },
188
+ widget: {
189
+ position: "bottom-right",
190
+ theme: "light",
191
+ lazyLoad: true,
192
+ autoReconnect: true,
193
+ persistConversations: true,
194
+ showRetrivoraBranding: false
195
+ },
196
+ telemetry: {
197
+ enabled: true,
198
+ collectBrowser: true,
199
+ collectCountry: false,
200
+ redactPii: true,
201
+ retentionDays: 30
202
+ },
203
+ lifecycleHooks: DEFAULT_LIFECYCLE_HOOKS,
204
+ conversationFeatures: DEFAULT_CONVERSATION_FEATURES
205
+ };
206
+ }
207
+ function cleanString(value, fallback, maxLength = 2e3) {
208
+ if (typeof value !== "string") return fallback;
209
+ return value.trim().slice(0, maxLength);
210
+ }
211
+ function cleanBoolean(value, fallback) {
212
+ return typeof value === "boolean" ? value : fallback;
213
+ }
214
+ function cleanNumber(value, fallback, min, max) {
215
+ const num = typeof value === "number" ? value : Number(value);
216
+ if (!Number.isFinite(num)) return fallback;
217
+ return Math.min(Math.max(Math.round(num), min), max);
218
+ }
219
+ function cleanEnum(value, fallback, allowed) {
220
+ return typeof value === "string" && allowed.includes(value) ? value : fallback;
221
+ }
222
+ function cleanStringList(value, fallback, maxItems = 20) {
223
+ if (!Array.isArray(value)) return fallback;
224
+ const cleaned = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, maxItems);
225
+ return cleaned.length > 0 ? Array.from(new Set(cleaned)) : fallback;
226
+ }
227
+ function normalizeProjectSettings(projectId, input) {
228
+ const defaults = createDefaultProjectSettings(projectId);
229
+ const branding = (input == null ? void 0 : input.branding) || {};
230
+ const ai = (input == null ? void 0 : input.ai) || {};
231
+ const auth = (input == null ? void 0 : input.auth) || {};
232
+ const widget = (input == null ? void 0 : input.widget) || {};
233
+ const telemetry = (input == null ? void 0 : input.telemetry) || {};
234
+ return {
235
+ projectId,
236
+ branding: {
237
+ companyName: cleanString(branding.companyName, defaults.branding.companyName, 120),
238
+ botName: cleanString(branding.botName, defaults.branding.botName, 120),
239
+ welcomeMessage: cleanString(branding.welcomeMessage, defaults.branding.welcomeMessage, 500),
240
+ primaryColor: cleanString(branding.primaryColor, defaults.branding.primaryColor, 32),
241
+ secondaryColor: cleanString(branding.secondaryColor, defaults.branding.secondaryColor, 32),
242
+ fontFamily: cleanString(branding.fontFamily, defaults.branding.fontFamily, 80),
243
+ borderRadius: cleanNumber(branding.borderRadius, defaults.branding.borderRadius, 0, 32),
244
+ logoUrl: cleanString(branding.logoUrl, defaults.branding.logoUrl, 500),
245
+ avatarUrl: cleanString(branding.avatarUrl, defaults.branding.avatarUrl, 500),
246
+ customCss: cleanString(branding.customCss, defaults.branding.customCss, 5e3)
247
+ },
248
+ ai: {
249
+ defaultModel: cleanString(ai.defaultModel, defaults.ai.defaultModel, 120),
250
+ embeddingModel: cleanString(ai.embeddingModel, defaults.ai.embeddingModel, 120),
251
+ systemPrompt: cleanString(ai.systemPrompt, defaults.ai.systemPrompt, 5e3),
252
+ memoryEnabled: cleanBoolean(ai.memoryEnabled, defaults.ai.memoryEnabled),
253
+ multiModelEnabled: cleanBoolean(ai.multiModelEnabled, defaults.ai.multiModelEnabled),
254
+ citationsEnabled: cleanBoolean(ai.citationsEnabled, defaults.ai.citationsEnabled),
255
+ fileUploadEnabled: cleanBoolean(ai.fileUploadEnabled, defaults.ai.fileUploadEnabled)
256
+ },
257
+ auth: {
258
+ mode: cleanEnum(auth.mode, defaults.auth.mode, ["public", "anonymous", "jwt", "oauth", "okta", "auth0", "supabase", "firebase", "sso", "custom_token"]),
259
+ allowedOrigins: cleanStringList(auth.allowedOrigins, defaults.auth.allowedOrigins, 25),
260
+ requireVerifiedEmail: cleanBoolean(auth.requireVerifiedEmail, defaults.auth.requireVerifiedEmail),
261
+ sessionTtlMinutes: cleanNumber(auth.sessionTtlMinutes, defaults.auth.sessionTtlMinutes, 15, 43200)
262
+ },
263
+ widget: {
264
+ position: cleanEnum(widget.position, defaults.widget.position, ["bottom-right", "bottom-left", "top-right", "top-left"]),
265
+ theme: cleanEnum(widget.theme, defaults.widget.theme, ["light", "dark", "system"]),
266
+ lazyLoad: cleanBoolean(widget.lazyLoad, defaults.widget.lazyLoad),
267
+ autoReconnect: cleanBoolean(widget.autoReconnect, defaults.widget.autoReconnect),
268
+ persistConversations: cleanBoolean(widget.persistConversations, defaults.widget.persistConversations),
269
+ showRetrivoraBranding: cleanBoolean(widget.showRetrivoraBranding, defaults.widget.showRetrivoraBranding)
270
+ },
271
+ telemetry: {
272
+ enabled: cleanBoolean(telemetry.enabled, defaults.telemetry.enabled),
273
+ collectBrowser: cleanBoolean(telemetry.collectBrowser, defaults.telemetry.collectBrowser),
274
+ collectCountry: cleanBoolean(telemetry.collectCountry, defaults.telemetry.collectCountry),
275
+ redactPii: cleanBoolean(telemetry.redactPii, defaults.telemetry.redactPii),
276
+ retentionDays: cleanNumber(telemetry.retentionDays, defaults.telemetry.retentionDays, 1, 365)
277
+ },
278
+ lifecycleHooks: cleanStringList(input == null ? void 0 : input.lifecycleHooks, defaults.lifecycleHooks, 30),
279
+ conversationFeatures: cleanStringList(input == null ? void 0 : input.conversationFeatures, defaults.conversationFeatures, 30),
280
+ updatedAt: input == null ? void 0 : input.updatedAt
281
+ };
282
+ }
283
+ var DEFAULT_LIFECYCLE_HOOKS, DEFAULT_CONVERSATION_FEATURES;
284
+ var init_ProjectSettings = __esm({
285
+ "src/core/ProjectSettings.ts"() {
286
+ "use strict";
287
+ DEFAULT_LIFECYCLE_HOOKS = [
288
+ "beforeInitialize",
289
+ "afterInitialize",
290
+ "beforeSend",
291
+ "afterResponse",
292
+ "onMessage",
293
+ "onCitationClick",
294
+ "onFeedback",
295
+ "onError",
296
+ "onReconnect",
297
+ "onFileUpload"
298
+ ];
299
+ DEFAULT_CONVERSATION_FEATURES = [
300
+ "History",
301
+ "Resume",
302
+ "Search",
303
+ "Export",
304
+ "Rename",
305
+ "Delete",
306
+ "Tags",
307
+ "Pinned",
308
+ "Unread",
309
+ "Ratings"
310
+ ];
311
+ }
312
+ });
313
+
314
+ // package.json
315
+ var package_default;
316
+ var init_package = __esm({
317
+ "package.json"() {
318
+ package_default = {
319
+ name: "@retrivora-ai/rag-engine",
320
+ version: "2.3.6",
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
+ author: "Abhinav Alkuchi",
323
+ license: "UNLICENSED",
324
+ keywords: [
325
+ "rag",
326
+ "retrieval-augmented-generation",
327
+ "chatbot",
328
+ "vector-database",
329
+ "pinecone",
330
+ "pgvector",
331
+ "postgresql",
332
+ "milvus",
333
+ "qdrant",
334
+ "chromadb",
335
+ "redis",
336
+ "weaviate",
337
+ "mongodb",
338
+ "openai",
339
+ "anthropic",
340
+ "ollama",
341
+ "nextjs",
342
+ "react",
343
+ "ai",
344
+ "llm",
345
+ "embeddings"
346
+ ],
347
+ main: "dist/index.js",
348
+ module: "dist/index.mjs",
349
+ types: "dist/index.d.ts",
350
+ exports: {
351
+ ".": {
352
+ types: "./dist/index.d.ts",
353
+ require: "./dist/index.js",
354
+ import: "./dist/index.mjs"
355
+ },
356
+ "./style.css": "./dist/index.css",
357
+ "./index.css": "./dist/index.css",
358
+ "./styles.css": "./dist/index.css",
359
+ "./handlers": {
360
+ types: "./dist/handlers/index.d.ts",
361
+ require: "./dist/handlers/index.js",
362
+ import: "./dist/handlers/index.mjs"
363
+ },
364
+ "./server": {
365
+ types: "./dist/server.d.ts",
366
+ require: "./dist/server.js",
367
+ import: "./dist/server.mjs"
368
+ }
369
+ },
370
+ browser: {
371
+ child_process: false,
372
+ fs: false,
373
+ net: false,
374
+ tls: false,
375
+ crypto: false,
376
+ os: false,
377
+ path: false,
378
+ stream: false,
379
+ http: false,
380
+ https: false,
381
+ zlib: false,
382
+ mongodb: false,
383
+ pg: false,
384
+ "pdf-parse": false,
385
+ mammoth: false
386
+ },
387
+ files: [
388
+ "dist",
389
+ "src",
390
+ ".env.example",
391
+ "README.md",
392
+ "FREE_TIER_ARCHITECTURE.md"
393
+ ],
394
+ scripts: {
395
+ dev: "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --watch --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style",
396
+ build: "npm run build:pkg",
397
+ "build:pkg": "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --dts --clean --no-splitting --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.css",
398
+ lint: "eslint",
399
+ typecheck: "tsc --noEmit -p tsconfig.build.json",
400
+ clean: "rm -rf dist"
401
+ },
402
+ peerDependencies: {
403
+ next: ">=15.0.0",
404
+ react: ">=18.0.0",
405
+ "react-dom": ">=18.0.0"
406
+ },
407
+ peerDependenciesMeta: {
408
+ next: {
409
+ optional: true
410
+ }
411
+ },
412
+ dependencies: {
413
+ "@anthropic-ai/sdk": "^0.95.1",
414
+ "@google/genai": "^0.8.0",
415
+ "@google/generative-ai": "^0.24.1",
416
+ "@pinecone-database/pinecone": "^7.2.0",
417
+ "@types/papaparse": "^5.5.2",
418
+ axios: "^1.15.0",
419
+ "lucide-react": "^1.8.0",
420
+ "next-themes": "^0.4.6",
421
+ openai: "^6.34.0",
422
+ papaparse: "^5.5.3",
423
+ "react-is": "^18.3.1",
424
+ "react-markdown": "^10.1.0",
425
+ recharts: "^3.8.1",
426
+ "remark-gfm": "^4.0.1",
427
+ xlsx: "^0.18.5"
428
+ },
429
+ optionalDependencies: {
430
+ "@langchain/core": "^1.1.42",
431
+ "@langchain/openai": "^1.4.5",
432
+ langchain: "^1.3.5",
433
+ llamaindex: "^0.11.9",
434
+ mammoth: "^1.8.0",
435
+ mongodb: "^7.1.1",
436
+ "pdf-parse": "^1.1.1",
437
+ pg: "^8.20.0"
438
+ },
439
+ devDependencies: {
440
+ "@tailwindcss/cli": "^4",
441
+ "@tailwindcss/postcss": "^4",
442
+ "@types/estree": "^1.0.9",
443
+ "@types/node": "^20",
444
+ "@types/pdf-parse": "^1.1.5",
445
+ "@types/pg": "^8.20.0",
446
+ "@types/react": "^19.2.14",
447
+ "@types/react-dom": "^19.2.3",
448
+ dotenv: "^17.4.2",
449
+ eslint: "^9",
450
+ "eslint-config-next": "16.2.4",
451
+ next: "16.2.10",
452
+ tailwindcss: "^4",
453
+ tsup: "^8.5.1",
454
+ typescript: "^5"
455
+ }
456
+ };
457
+ }
458
+ });
459
+
460
+ // src/version.ts
461
+ var SDK_VERSION;
462
+ var init_version = __esm({
463
+ "src/version.ts"() {
464
+ "use strict";
465
+ init_package();
466
+ SDK_VERSION = package_default.version || "2.1.3";
467
+ }
468
+ });
469
+
157
470
  // src/core/ConfigFetcher.ts
158
- var ConfigFetcher;
471
+ var CONTROL_PLANE_URL, LLM_PROXY_BASE_URL, ConfigFetcher;
159
472
  var init_ConfigFetcher = __esm({
160
473
  "src/core/ConfigFetcher.ts"() {
161
474
  "use strict";
475
+ init_ProjectSettings();
476
+ init_version();
477
+ CONTROL_PLANE_URL = "https://www.retrivora.com";
478
+ LLM_PROXY_BASE_URL = "https://www.retrivora.com/api/v1";
162
479
  ConfigFetcher = class {
163
480
  // 5-minute in-memory session cache
164
481
  /**
165
- * Fetch full project configuration (vectorDb + embedding + llm) from Retrivora Control Plane.
482
+ * Fetch full project configuration (vectorDb + embedding + llm + workspace) from Retrivora Control Plane.
483
+ *
484
+ * The SDK calls https://www.retrivora.com/api/v1/config with the project ID and license key.
485
+ * The server validates the license against the database and returns:
486
+ * - validity (tier, isActive, expiresAt)
487
+ * - LLM model info
488
+ * - embedding model info
489
+ * - Pinecone index name and workspace/namespace
490
+ *
491
+ * The Pinecone API key is NOT returned (server-only). The SDK uses local
492
+ * PINECONE_API_KEY if available, or vector operations are handled server-side.
166
493
  */
167
494
  static async fetchRemoteConfig(projectId, licenseKey) {
168
495
  var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
@@ -175,46 +502,60 @@ var init_ConfigFetcher = __esm({
175
502
  const controlPlaneUrls = [
176
503
  process.env.RETRIVORA_CONTROL_PLANE_URL,
177
504
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
178
- "https://www.retrivora.com",
179
- "https://retrivora.com",
180
- "http://localhost:3000",
181
- "http://localhost:3001"
182
- ].filter(Boolean);
505
+ CONTROL_PLANE_URL
506
+ ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
183
507
  for (const baseUrl of controlPlaneUrls) {
184
508
  try {
185
- const url = `${baseUrl.replace(/\/$/, "")}/api/v1/config?projectId=${encodeURIComponent(projectId)}${licenseKey ? `&licenseKey=${encodeURIComponent(licenseKey)}` : ""}`;
509
+ const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
186
510
  const res = await fetch(url, {
187
511
  method: "GET",
188
512
  headers: __spreadValues({
189
- "Content-Type": "application/json"
513
+ "Content-Type": "application/json",
514
+ "x-sdk-version": SDK_VERSION
190
515
  }, licenseKey ? { "x-license-key": licenseKey } : {})
191
516
  });
192
517
  if (res.ok) {
193
518
  const data = await res.json();
194
- if ((data == null ? void 0 : data.success) && ((_a3 = data == null ? void 0 : data.vectorDb) == null ? void 0 : _a3.apiKey)) {
519
+ if ((data == null ? void 0 : data.success) && (data == null ? void 0 : data.vectorDb)) {
195
520
  const fetchedProjectId = data.projectId || projectId;
196
521
  const config = {
197
522
  projectId: fetchedProjectId,
523
+ tier: data.tier,
524
+ isActive: data.isActive,
525
+ expiresAt: data.expiresAt,
198
526
  vectorDb: {
199
- apiKey: data.vectorDb.apiKey,
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.
529
+ apiKey: data.vectorDb.apiKey || "",
200
530
  indexName: data.vectorDb.indexName || "retrivora-free",
201
531
  provider: data.vectorDb.provider || "pinecone",
202
- projectId: fetchedProjectId
532
+ projectId: fetchedProjectId,
533
+ namespace: ((_a3 = data.workspace) == null ? void 0 : _a3.namespace) || data.vectorDb.namespace || fetchedProjectId
203
534
  },
204
535
  embedding: {
205
536
  provider: ((_b = data.embedding) == null ? void 0 : _b.provider) || "universal_rest",
206
537
  model: ((_c = data.embedding) == null ? void 0 : _c.model) || "text-embedding-004",
207
- baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || "https://llm.retrivora.com/api/v1",
538
+ // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
539
+ baseUrl: ((_d = data.embedding) == null ? void 0 : _d.baseUrl) || LLM_PROXY_BASE_URL,
208
540
  apiKey: ((_e = data.embedding) == null ? void 0 : _e.apiKey) || licenseKey || "",
209
541
  profile: ((_f = data.embedding) == null ? void 0 : _f.profile) || "litellm"
210
542
  },
211
543
  llm: {
212
544
  provider: ((_g2 = data.llm) == null ? void 0 : _g2.provider) || "universal_rest",
213
545
  model: ((_h = data.llm) == null ? void 0 : _h.model) || "llama-3.1-8b-instant",
214
- baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || "https://llm.retrivora.com/api/v1",
546
+ // Route through www.retrivora.com proxy, not llm.retrivora.com directly.
547
+ baseUrl: ((_i = data.llm) == null ? void 0 : _i.baseUrl) || LLM_PROXY_BASE_URL,
215
548
  apiKey: ((_j = data.llm) == null ? void 0 : _j.apiKey) || licenseKey || "",
216
549
  profile: ((_k = data.llm) == null ? void 0 : _k.profile) || "litellm"
217
- }
550
+ },
551
+ workspace: data.workspace || {
552
+ namespace: fetchedProjectId,
553
+ indexName: data.vectorDb.indexName || "retrivora-free"
554
+ },
555
+ projectSettings: normalizeProjectSettings(
556
+ fetchedProjectId,
557
+ data.projectSettings || data.settings
558
+ )
218
559
  };
219
560
  this.cache.set(cacheKey, { config, cachedAt: now });
220
561
  return config;
@@ -332,19 +673,26 @@ var init_PineconeProvider = __esm({
332
673
  })();
333
674
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
334
675
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
335
- if (remoteConfig == null ? void 0 : remoteConfig.apiKey) {
336
- key = remoteConfig.apiKey;
337
- this.apiKey = key;
676
+ if (remoteConfig) {
677
+ if (remoteConfig.apiKey) {
678
+ key = remoteConfig.apiKey;
679
+ this.apiKey = key;
680
+ }
338
681
  if (remoteConfig.indexName) {
339
682
  this.indexName = remoteConfig.indexName;
340
683
  }
341
684
  if (remoteConfig.projectId) {
342
685
  this.projectId = remoteConfig.projectId;
343
686
  }
687
+ if (remoteConfig.namespace) {
688
+ this.namespace = remoteConfig.namespace;
689
+ }
344
690
  }
345
691
  }
346
692
  if (!key) {
347
- console.warn("[PineconeProvider] Warning: No Pinecone API key available locally or remotely.");
693
+ console.warn(
694
+ "[PineconeProvider] Warning: No Pinecone API key available. Set PINECONE_API_KEY in your environment, or ensure the Retrivora Control Plane (https://www.retrivora.com) is reachable for proxy-based vector operations."
695
+ );
348
696
  return;
349
697
  }
350
698
  this.client = new import_pinecone.Pinecone({ apiKey: key });
@@ -2804,6 +3152,7 @@ var ConfigResolver = class {
2804
3152
  options: __spreadValues(__spreadValues({}, envConfig.embedding.options || {}), hostConfig.embedding.options || {})
2805
3153
  }) : envConfig.embedding,
2806
3154
  ui: hostConfig.ui ? mergeDefined(envConfig.ui, hostConfig.ui) : envConfig.ui,
3155
+ projectSettings: hostConfig.projectSettings || envConfig.projectSettings,
2807
3156
  rag: hostConfig.rag ? __spreadValues(__spreadValues({}, envConfig.rag), hostConfig.rag) : envConfig.rag,
2808
3157
  telemetry: hostConfig.telemetry ? __spreadValues(__spreadValues({}, envConfig.telemetry), hostConfig.telemetry) : envConfig.telemetry
2809
3158
  });
@@ -4706,149 +5055,8 @@ var ConfigValidator = class {
4706
5055
  }
4707
5056
  };
4708
5057
 
4709
- // package.json
4710
- var package_default = {
4711
- name: "@retrivora-ai/rag-engine",
4712
- version: "2.3.4",
4713
- description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
4714
- author: "Abhinav Alkuchi",
4715
- license: "UNLICENSED",
4716
- keywords: [
4717
- "rag",
4718
- "retrieval-augmented-generation",
4719
- "chatbot",
4720
- "vector-database",
4721
- "pinecone",
4722
- "pgvector",
4723
- "postgresql",
4724
- "milvus",
4725
- "qdrant",
4726
- "chromadb",
4727
- "redis",
4728
- "weaviate",
4729
- "mongodb",
4730
- "openai",
4731
- "anthropic",
4732
- "ollama",
4733
- "nextjs",
4734
- "react",
4735
- "ai",
4736
- "llm",
4737
- "embeddings"
4738
- ],
4739
- main: "dist/index.js",
4740
- module: "dist/index.mjs",
4741
- types: "dist/index.d.ts",
4742
- exports: {
4743
- ".": {
4744
- types: "./dist/index.d.ts",
4745
- require: "./dist/index.js",
4746
- import: "./dist/index.mjs"
4747
- },
4748
- "./style.css": "./dist/index.css",
4749
- "./index.css": "./dist/index.css",
4750
- "./styles.css": "./dist/index.css",
4751
- "./handlers": {
4752
- types: "./dist/handlers/index.d.ts",
4753
- require: "./dist/handlers/index.js",
4754
- import: "./dist/handlers/index.mjs"
4755
- },
4756
- "./server": {
4757
- types: "./dist/server.d.ts",
4758
- require: "./dist/server.js",
4759
- import: "./dist/server.mjs"
4760
- }
4761
- },
4762
- browser: {
4763
- child_process: false,
4764
- fs: false,
4765
- net: false,
4766
- tls: false,
4767
- crypto: false,
4768
- os: false,
4769
- path: false,
4770
- stream: false,
4771
- http: false,
4772
- https: false,
4773
- zlib: false,
4774
- mongodb: false,
4775
- pg: false,
4776
- "pdf-parse": false,
4777
- mammoth: false
4778
- },
4779
- files: [
4780
- "dist",
4781
- "src",
4782
- ".env.example",
4783
- "README.md",
4784
- "FREE_TIER_ARCHITECTURE.md"
4785
- ],
4786
- scripts: {
4787
- dev: "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --watch --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style",
4788
- build: "npm run build:pkg",
4789
- "build:pkg": "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --dts --clean --no-splitting --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.css",
4790
- lint: "eslint",
4791
- typecheck: "tsc --noEmit -p tsconfig.build.json",
4792
- clean: "rm -rf dist"
4793
- },
4794
- peerDependencies: {
4795
- next: ">=15.0.0",
4796
- react: ">=18.0.0",
4797
- "react-dom": ">=18.0.0"
4798
- },
4799
- peerDependenciesMeta: {
4800
- next: {
4801
- optional: true
4802
- }
4803
- },
4804
- dependencies: {
4805
- "@anthropic-ai/sdk": "^0.95.1",
4806
- "@google/genai": "^0.8.0",
4807
- "@google/generative-ai": "^0.24.1",
4808
- "@pinecone-database/pinecone": "^7.2.0",
4809
- "@types/papaparse": "^5.5.2",
4810
- axios: "^1.15.0",
4811
- "lucide-react": "^1.8.0",
4812
- "next-themes": "^0.4.6",
4813
- openai: "^6.34.0",
4814
- papaparse: "^5.5.3",
4815
- "react-is": "^18.3.1",
4816
- "react-markdown": "^10.1.0",
4817
- recharts: "^3.8.1",
4818
- "remark-gfm": "^4.0.1",
4819
- xlsx: "^0.18.5"
4820
- },
4821
- optionalDependencies: {
4822
- "@langchain/core": "^1.1.42",
4823
- "@langchain/openai": "^1.4.5",
4824
- langchain: "^1.3.5",
4825
- llamaindex: "^0.11.9",
4826
- mammoth: "^1.8.0",
4827
- mongodb: "^7.1.1",
4828
- "pdf-parse": "^1.1.1",
4829
- pg: "^8.20.0"
4830
- },
4831
- devDependencies: {
4832
- "@tailwindcss/cli": "^4",
4833
- "@tailwindcss/postcss": "^4",
4834
- "@types/estree": "^1.0.9",
4835
- "@types/node": "^20",
4836
- "@types/pdf-parse": "^1.1.5",
4837
- "@types/pg": "^8.20.0",
4838
- "@types/react": "^19.2.14",
4839
- "@types/react-dom": "^19.2.3",
4840
- dotenv: "^17.4.2",
4841
- eslint: "^9",
4842
- "eslint-config-next": "16.2.4",
4843
- next: "16.2.10",
4844
- tailwindcss: "^4",
4845
- tsup: "^8.5.1",
4846
- typescript: "^5"
4847
- }
4848
- };
4849
-
4850
- // src/version.ts
4851
- var SDK_VERSION = package_default.version || "2.1.3";
5058
+ // src/core/Pipeline.ts
5059
+ init_version();
4852
5060
 
4853
5061
  // src/rag/DocumentChunker.ts
4854
5062
  var DocumentChunker = class {
@@ -10517,6 +10725,7 @@ var DatabaseStorage = class {
10517
10725
  };
10518
10726
 
10519
10727
  // src/handlers/index.ts
10728
+ init_version();
10520
10729
  async function checkAuth(req, onAuthorize) {
10521
10730
  if (!onAuthorize) return null;
10522
10731
  try {
@@ -10626,7 +10835,7 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
10626
10835
  function enforceLicense(req, config, bodyLicenseKey) {
10627
10836
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
10628
10837
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
10629
- const projectId = config.projectId || "my-rag-app";
10838
+ const projectId = config.projectId || "";
10630
10839
  try {
10631
10840
  const payload = LicenseVerifier.verify(licenseKey, projectId);
10632
10841
  return { ok: true, payload };
@@ -10648,6 +10857,35 @@ function enforceLicense(req, config, bodyLicenseKey) {
10648
10857
  };
10649
10858
  }
10650
10859
  }
10860
+ function getAllowedNamespaces(projectId) {
10861
+ const trimmed = projectId.trim();
10862
+ const withoutPrefix = trimmed.startsWith("retrivora-") ? trimmed.replace(/^retrivora-/, "") : trimmed;
10863
+ return new Set([
10864
+ trimmed,
10865
+ withoutPrefix,
10866
+ `retrivora-${withoutPrefix}`
10867
+ ].filter(Boolean));
10868
+ }
10869
+ function resolveLicensedNamespace(payload, requestedNamespace) {
10870
+ const allowed = getAllowedNamespaces(payload.projectId);
10871
+ const requested = requestedNamespace == null ? void 0 : requestedNamespace.trim();
10872
+ if (requested && !allowed.has(requested)) {
10873
+ return {
10874
+ ok: false,
10875
+ response: new Response(JSON.stringify({
10876
+ error: {
10877
+ code: "NAMESPACE_FORBIDDEN",
10878
+ message: "Requested namespace is not authorized for this license."
10879
+ }
10880
+ }), {
10881
+ status: 403,
10882
+ headers: { "Content-Type": "application/json" }
10883
+ })
10884
+ };
10885
+ }
10886
+ const defaultNamespace = payload.projectId.startsWith("retrivora-") ? payload.projectId : `retrivora-${payload.projectId}`;
10887
+ return { ok: true, namespace: requested || defaultNamespace };
10888
+ }
10651
10889
  var MAX_MESSAGE_LENGTH = 8e3;
10652
10890
  function sanitizeInput(raw) {
10653
10891
  const stripped = raw.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "");
@@ -10808,6 +11046,8 @@ function createChatHandler(configOrPlugin, options) {
10808
11046
  }
10809
11047
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
10810
11048
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11049
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11050
+ if (!namespaceCheck.ok) return namespaceCheck.response;
10811
11051
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
10812
11052
  if (!sanitized.ok) {
10813
11053
  return import_server.NextResponse.json({ error: { code: "INVALID_INPUT", message: sanitized.error } }, { status: 400 });
@@ -10819,7 +11059,7 @@ function createChatHandler(configOrPlugin, options) {
10819
11059
  role: "user",
10820
11060
  content: message
10821
11061
  }).catch((err) => console.warn("[createChatHandler] Failed to save user message:", err));
10822
- const result = await plugin.chat(message, history, namespace);
11062
+ const result = await plugin.chat(message, history, namespaceCheck.namespace);
10823
11063
  const assistantMsgId = messageId || `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10824
11064
  await storage.saveMessage(sessionId, {
10825
11065
  id: assistantMsgId,
@@ -10900,6 +11140,8 @@ function createStreamHandler(configOrPlugin, options) {
10900
11140
  }
10901
11141
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
10902
11142
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11143
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11144
+ if (!namespaceCheck.ok) return namespaceCheck.response;
10903
11145
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
10904
11146
  if (!sanitized.ok) {
10905
11147
  return new Response(
@@ -10929,7 +11171,7 @@ function createStreamHandler(configOrPlugin, options) {
10929
11171
  }
10930
11172
  };
10931
11173
  try {
10932
- const pipelineStream = plugin.chatStream(message, history, namespace);
11174
+ const pipelineStream = plugin.chatStream(message, history, namespaceCheck.namespace);
10933
11175
  let fullReply = "";
10934
11176
  try {
10935
11177
  for (var iter = __forAwait(pipelineStream), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
@@ -11035,6 +11277,8 @@ function createIngestHandler(configOrPlugin, options) {
11035
11277
  if (!Array.isArray(documents) || documents.length === 0) {
11036
11278
  return import_server.NextResponse.json({ error: "documents array is required" }, { status: 400 });
11037
11279
  }
11280
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11281
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11038
11282
  if (isFreeTier(licenseCheck.payload.tier)) {
11039
11283
  const totalIncomingBytes = documents.reduce(
11040
11284
  (sum, d) => sum + Buffer.byteLength(d.content || "", "utf8"),
@@ -11056,7 +11300,7 @@ function createIngestHandler(configOrPlugin, options) {
11056
11300
  );
11057
11301
  }
11058
11302
  }
11059
- const results = await plugin.ingest(documents, namespace);
11303
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11060
11304
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Ingested ${documents.length} document(s)`);
11061
11305
  return import_server.NextResponse.json({ results });
11062
11306
  } catch (err) {
@@ -11102,7 +11346,7 @@ function createLicenseHandler(configOrPlugin, options) {
11102
11346
  const config = plugin.getConfig();
11103
11347
  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 || "";
11104
11348
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11105
- const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "my-rag-app";
11349
+ const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11106
11350
  const payload = LicenseVerifier.verify(licenseKey, projectId);
11107
11351
  return import_server.NextResponse.json({
11108
11352
  valid: true,
@@ -11144,6 +11388,8 @@ function createUploadHandler(configOrPlugin, options) {
11144
11388
  const namespace = formData.get("namespace") || void 0;
11145
11389
  const dimensionRaw = formData.get("dimension");
11146
11390
  const dimension = dimensionRaw ? parseInt(dimensionRaw, 10) : void 0;
11391
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11392
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11147
11393
  if (!files || files.length === 0) {
11148
11394
  return import_server.NextResponse.json({ error: "No files provided" }, { status: 400 });
11149
11395
  }
@@ -11260,7 +11506,7 @@ function createUploadHandler(configOrPlugin, options) {
11260
11506
  });
11261
11507
  }
11262
11508
  }
11263
- const results = await plugin.ingest(documents, namespace);
11509
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11264
11510
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Uploaded & ingested ${files.length} file(s)`);
11265
11511
  return import_server.NextResponse.json({ message: "Upload successful", results });
11266
11512
  } catch (err) {
@@ -11279,6 +11525,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11279
11525
  const config = plugin.getConfig();
11280
11526
  const licenseCheck = enforceLicense(req, config);
11281
11527
  if (!licenseCheck.ok) return licenseCheck.response;
11528
+ let effectiveLicensePayload = licenseCheck.payload;
11282
11529
  try {
11283
11530
  let query = "";
11284
11531
  let namespace = void 0;
@@ -11291,6 +11538,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11291
11538
  if (bodyLicenseKey) {
11292
11539
  const recheck = enforceLicense(req, config, bodyLicenseKey);
11293
11540
  if (!recheck.ok) return recheck.response;
11541
+ effectiveLicensePayload = recheck.payload;
11294
11542
  }
11295
11543
  } else {
11296
11544
  const url = new URL(req.url);
@@ -11300,7 +11548,9 @@ function createSuggestionsHandler(configOrPlugin, options) {
11300
11548
  if (!query || typeof query !== "string" || !query.trim()) {
11301
11549
  return import_server.NextResponse.json({ suggestions: [] });
11302
11550
  }
11303
- const suggestions = await plugin.getSuggestions(query, namespace);
11551
+ const namespaceCheck = resolveLicensedNamespace(effectiveLicensePayload, namespace);
11552
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11553
+ const suggestions = await plugin.getSuggestions(query, namespaceCheck.namespace);
11304
11554
  reportTelemetry(req, plugin, "AUTO_SUGGESTIONS", "success", `Fetched ${suggestions.length} suggestions for: ${query.slice(0, 30)}`);
11305
11555
  return import_server.NextResponse.json({ suggestions });
11306
11556
  } catch (err) {