@infuro/cms-core 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2432,33 +2432,162 @@ function localStoragePlugin(config = {}) {
2432
2432
  }
2433
2433
 
2434
2434
  // src/plugins/llm/llm-service.ts
2435
+ function parseOpenAiEmbeddingJson(data) {
2436
+ let embedding = data?.data?.[0]?.embedding;
2437
+ if (!Array.isArray(embedding) && Array.isArray(data?.embedding)) {
2438
+ embedding = data.embedding;
2439
+ }
2440
+ if (!Array.isArray(embedding) && Array.isArray(data?.data?.[0])) {
2441
+ const first = data.data[0];
2442
+ embedding = Array.isArray(first) ? first : first?.embedding;
2443
+ }
2444
+ return Array.isArray(embedding) ? embedding : null;
2445
+ }
2446
+ function parseHfInferenceEmbeddingBody(data) {
2447
+ if (data === null || data === void 0) return null;
2448
+ if (Array.isArray(data)) {
2449
+ if (data.length === 0) return null;
2450
+ const first = data[0];
2451
+ if (typeof first === "number") return data;
2452
+ if (Array.isArray(first) && first.length > 0 && typeof first[0] === "number") {
2453
+ return first;
2454
+ }
2455
+ if (Array.isArray(first) && Array.isArray(first[0]) && typeof first[0][0] === "number") {
2456
+ return first[0];
2457
+ }
2458
+ return null;
2459
+ }
2460
+ if (typeof data === "object" && data !== null && !Array.isArray(data)) {
2461
+ const o = data;
2462
+ if (typeof o.error === "string") return null;
2463
+ if ("embeddings" in o) return parseHfInferenceEmbeddingBody(o.embeddings);
2464
+ }
2465
+ return null;
2466
+ }
2467
+ var FALLBACK_CHAT_MODEL_OPENAI_SHAPE = "openai/gpt-4o-mini";
2468
+ var FALLBACK_CHAT_MODEL_HUGGINGFACE = "meta-llama/Meta-Llama-3.1-8B-Instruct";
2469
+ function defaultChatModelForGateway(baseURL) {
2470
+ const u = baseURL.toLowerCase();
2471
+ if (u.includes("huggingface.co") || u.includes("hf.co") || u.includes("hf-inference")) {
2472
+ return FALLBACK_CHAT_MODEL_HUGGINGFACE;
2473
+ }
2474
+ return FALLBACK_CHAT_MODEL_OPENAI_SHAPE;
2475
+ }
2476
+ function formatLlmGatewayError(status, bodyText, defaultChatModel) {
2477
+ let hint = "";
2478
+ try {
2479
+ const j = JSON.parse(bodyText);
2480
+ const code = j?.error?.code;
2481
+ if (code === "model_not_supported" || code === "model_not_found" || /not supported by any provider|does not exist/i.test(j?.error?.message ?? "")) {
2482
+ hint = ` Hint: set LLM_CHAT_MODEL (or CMS) to a model your gateway lists. HF router: Hub ids (e.g. "${FALLBACK_CHAT_MODEL_HUGGINGFACE}"); OpenRouter: e.g. "${FALLBACK_CHAT_MODEL_OPENAI_SHAPE}".`;
2483
+ }
2484
+ } catch {
2485
+ }
2486
+ return `LLM gateway error: ${status} ${bodyText}${hint}`;
2487
+ }
2435
2488
  var LlmService = class _LlmService {
2436
- constructor(baseURL, apiKey, defaultEmbeddingModel) {
2437
- this.baseURL = baseURL;
2489
+ static embedHttpErrorLogged = false;
2490
+ static embedShapeErrorLogged = false;
2491
+ static embedSuccessLogged = false;
2492
+ static hfDimensionMismatchWarned = false;
2493
+ static hfInferenceSdkErrorLogged = false;
2494
+ baseURL;
2495
+ apiKey;
2496
+ defaultEmbeddingModel;
2497
+ embeddingProvider;
2498
+ hfInferenceBaseURL;
2499
+ embeddingApiKey;
2500
+ defaultChatModel;
2501
+ constructor(baseURL, apiKey, defaultEmbeddingModel, embedOpts) {
2502
+ this.baseURL = baseURL.replace(/\/$/, "");
2438
2503
  this.apiKey = apiKey;
2439
2504
  this.defaultEmbeddingModel = defaultEmbeddingModel;
2505
+ const p = (embedOpts?.embeddingProvider ?? "openai").toLowerCase();
2506
+ this.embeddingProvider = p === "huggingface" ? "huggingface" : "openai";
2507
+ this.hfInferenceBaseURL = (embedOpts?.hfInferenceBaseUrl ?? "https://router.huggingface.co/v1").replace(
2508
+ /\/$/,
2509
+ ""
2510
+ );
2511
+ this.embeddingApiKey = (embedOpts?.embeddingApiKey ?? apiKey).trim();
2512
+ const fromOpts = embedOpts?.defaultChatModel?.trim();
2513
+ const fromEnv = typeof process !== "undefined" ? process.env.LLM_CHAT_MODEL?.trim() : "";
2514
+ const auto = defaultChatModelForGateway(this.baseURL);
2515
+ this.defaultChatModel = (fromOpts || fromEnv || auto).trim() || auto;
2516
+ }
2517
+ resolveChatModel(explicit) {
2518
+ const m = (explicit?.trim() || this.defaultChatModel).trim();
2519
+ return m || defaultChatModelForGateway(this.baseURL);
2440
2520
  }
2441
- static embedWarned = false;
2442
2521
  get base() {
2443
2522
  return this.baseURL.replace(/\/$/, "");
2444
2523
  }
2445
2524
  get url() {
2446
2525
  return `${this.base}/v1/chat/completions`;
2447
2526
  }
2448
- /**
2449
- * OpenAI-compatible embeddings. Returns [] if endpoint not available or unexpected response.
2450
- * Server must implement: POST /v1/embeddings
2451
- * Body: { model: string, input: string }
2452
- * Response: { data: [ { embedding: number[] } ] } or { embedding: number[] }
2453
- */
2527
+ llmDebugEnabled() {
2528
+ const v = process.env.LLM_DEBUG?.toLowerCase();
2529
+ return v === "1" || v === "true" || v === "yes";
2530
+ }
2531
+ /** Per-request embedding logs (noisy with many chunks). Set `LLM_EMBED_DEBUG=1`. */
2532
+ embedDebugEnabled() {
2533
+ const v = process.env.LLM_EMBED_DEBUG?.toLowerCase();
2534
+ return v === "1" || v === "true" || v === "yes";
2535
+ }
2536
+ logAgentComposition(options) {
2537
+ if (!this.llmDebugEnabled()) return;
2538
+ const { systemPrompt, context, history = [], userPrompt, model, temperature, max_tokens } = options;
2539
+ console.log("\n[LLM chatAgent] composing request");
2540
+ if (systemPrompt?.trim()) {
2541
+ console.log("[System instruction]\n", systemPrompt.trim());
2542
+ }
2543
+ if (context?.trim()) {
2544
+ console.log("[Context \u2014 merged into system message by chatAgent]\n", context.trim());
2545
+ }
2546
+ if (history.length > 0) {
2547
+ console.log("[Conversation so far]");
2548
+ for (const m of history) {
2549
+ console.log(` ${m.role}: ${m.content}`);
2550
+ }
2551
+ }
2552
+ console.log("[Current user message]\n", userPrompt);
2553
+ if (model !== void 0 || temperature !== void 0 || max_tokens !== void 0) {
2554
+ console.log("[Agent options]", { model, temperature, max_tokens });
2555
+ }
2556
+ }
2557
+ logChatCompletionsRequest(kind, messages, options, stream) {
2558
+ if (!this.llmDebugEnabled()) return;
2559
+ const model = this.resolveChatModel(options.model);
2560
+ console.log(`
2561
+ [LLM ${kind}] POST`, this.url);
2562
+ console.log("[Request options]", {
2563
+ model,
2564
+ temperature: options.temperature,
2565
+ max_tokens: options.max_tokens,
2566
+ stream
2567
+ });
2568
+ console.log("[Messages \u2014 wire payload]\n", JSON.stringify(messages, null, 2));
2569
+ }
2454
2570
  async embed(text, options = {}) {
2455
- const model = options.model ?? this.defaultEmbeddingModel ?? "text-embedding-3-small";
2456
2571
  const input = text.slice(0, 8e3);
2457
- const res = await fetch(`${this.base}/v1/embeddings`, {
2572
+ if (this.embeddingProvider === "huggingface") {
2573
+ const model2 = options.model ?? this.defaultEmbeddingModel ?? "sentence-transformers/all-MiniLM-L6-v2";
2574
+ return this.embedHuggingFaceInference(input, model2);
2575
+ }
2576
+ const model = options.model ?? this.defaultEmbeddingModel ?? "text-embedding-3-small";
2577
+ return this.fetchOpenAiShapeEmbeddings(`${this.base}/v1/embeddings`, model, input, this.apiKey);
2578
+ }
2579
+ /**
2580
+ * POST `{ url }` with OpenAI-style `{ model, input }` and Bearer token; parses `{ data:[{embedding}] }`.
2581
+ */
2582
+ async fetchOpenAiShapeEmbeddings(embedUrl, model, input, bearerToken) {
2583
+ if (this.embedDebugEnabled()) {
2584
+ console.info("[LLM embed] request", { url: embedUrl, model, inputChars: input.length });
2585
+ }
2586
+ const res = await fetch(embedUrl, {
2458
2587
  method: "POST",
2459
2588
  headers: {
2460
2589
  "Content-Type": "application/json",
2461
- Authorization: `Bearer ${this.apiKey}`
2590
+ Authorization: `Bearer ${bearerToken}`
2462
2591
  },
2463
2592
  body: JSON.stringify({
2464
2593
  model,
@@ -2467,9 +2596,17 @@ var LlmService = class _LlmService {
2467
2596
  });
2468
2597
  if (!res.ok) {
2469
2598
  const body = await res.text();
2470
- if (!_LlmService.embedWarned) {
2471
- _LlmService.embedWarned = true;
2472
- console.warn(`[LLM embed] ${res.status} ${res.statusText}: ${body.slice(0, 400)}`);
2599
+ const hint404 = res.status === 404 ? "This base URL does not expose OpenAI-compatible POST /v1/embeddings. For Hugging Face embeddings, set EMBEDDING_PROVIDER=huggingface and an HF token (EMBEDDING_API_KEY); the server uses @huggingface/inference (router /v1/embeddings is chat-only and is not used)." : "Embeddings HTTP error \u2014 knowledge_base_chunks.embedding will stay NULL for failed calls.";
2600
+ if (!_LlmService.embedHttpErrorLogged) {
2601
+ _LlmService.embedHttpErrorLogged = true;
2602
+ console.error("[LLM embed]", hint404, {
2603
+ url: embedUrl,
2604
+ status: res.status,
2605
+ statusText: res.statusText,
2606
+ bodyPreview: body.slice(0, 800)
2607
+ });
2608
+ } else if (this.embedDebugEnabled()) {
2609
+ console.warn("[LLM embed] repeat HTTP error", { status: res.status, bodyPreview: body.slice(0, 200) });
2473
2610
  }
2474
2611
  return [];
2475
2612
  }
@@ -2477,24 +2614,266 @@ var LlmService = class _LlmService {
2477
2614
  try {
2478
2615
  data = await res.json();
2479
2616
  } catch {
2480
- console.warn("[LLM embed] Response is not JSON");
2617
+ if (!_LlmService.embedShapeErrorLogged) {
2618
+ _LlmService.embedShapeErrorLogged = true;
2619
+ console.error("[LLM embed] Response body is not JSON \u2014 treating as no embedding.");
2620
+ }
2621
+ return [];
2622
+ }
2623
+ const embedding = parseOpenAiEmbeddingJson(data);
2624
+ if (!embedding) {
2625
+ if (!_LlmService.embedShapeErrorLogged) {
2626
+ _LlmService.embedShapeErrorLogged = true;
2627
+ console.error(
2628
+ "[LLM embed] Response OK but no parseable embedding array (OpenAI shape expected). knowledge_base_chunks will not update.",
2629
+ {
2630
+ url: embedUrl,
2631
+ topKeys: Object.keys(data),
2632
+ data0Type: Array.isArray(data?.data) ? typeof data.data[0] : "n/a"
2633
+ }
2634
+ );
2635
+ }
2481
2636
  return [];
2482
2637
  }
2483
- let embedding = data?.data?.[0]?.embedding;
2484
- if (!Array.isArray(embedding) && Array.isArray(data?.embedding)) {
2485
- embedding = data.embedding;
2638
+ if (!_LlmService.embedSuccessLogged) {
2639
+ _LlmService.embedSuccessLogged = true;
2640
+ console.info("[LLM embed] first success", { dimension: embedding.length, model });
2641
+ } else if (this.embedDebugEnabled()) {
2642
+ console.info("[LLM embed] ok", { dimension: embedding.length });
2643
+ }
2644
+ return embedding;
2645
+ }
2646
+ /**
2647
+ * Hugging Face–recommended path: Hub resolves a provider that supports `feature-extraction` for the model.
2648
+ */
2649
+ async embedViaHuggingfaceInferenceSdk(input, model) {
2650
+ const token = this.embeddingApiKey.trim();
2651
+ if (!token) return null;
2652
+ try {
2653
+ const { InferenceClient } = await import("@huggingface/inference");
2654
+ const hf = new InferenceClient(token);
2655
+ const raw = await hf.featureExtraction({
2656
+ model,
2657
+ inputs: input
2658
+ });
2659
+ const embedding = parseHfInferenceEmbeddingBody(raw);
2660
+ if (!embedding?.length) {
2661
+ if (this.embedDebugEnabled()) {
2662
+ console.warn("[LLM embed HF] Inference SDK returned no parseable vector", {
2663
+ model,
2664
+ shape: Array.isArray(raw) ? `array(len=${raw.length})` : typeof raw
2665
+ });
2666
+ }
2667
+ return null;
2668
+ }
2669
+ return embedding;
2670
+ } catch (err) {
2671
+ const message = err instanceof Error ? err.message : String(err);
2672
+ if (!_LlmService.hfInferenceSdkErrorLogged) {
2673
+ _LlmService.hfInferenceSdkErrorLogged = true;
2674
+ console.warn(
2675
+ "[LLM embed HF] @huggingface/inference featureExtraction failed \u2014 trying legacy HTTP URLs.",
2676
+ { model, message: message.slice(0, 500) }
2677
+ );
2678
+ } else if (this.embedDebugEnabled()) {
2679
+ console.warn("[LLM embed HF] repeat Inference SDK failure", { message: message.slice(0, 200) });
2680
+ }
2681
+ return null;
2682
+ }
2683
+ }
2684
+ /** Base URL for legacy `…/pipeline/…` and `…/models/{model}` tries (HF router only). */
2685
+ hfLegacyInferenceBase(normalizedBase) {
2686
+ if (/router\.huggingface\.co|api-inference\.huggingface\.co/i.test(normalizedBase)) {
2687
+ return "https://router.huggingface.co/hf-inference";
2688
+ }
2689
+ return normalizedBase;
2690
+ }
2691
+ /**
2692
+ * Hugging Face embeddings: `@huggingface/inference` (Hub-routed feature extraction), then
2693
+ * legacy direct `hf-inference` HTTP tries. Note: `https://router.huggingface.co/v1/embeddings` is not
2694
+ * offered for embeddings (OpenAI-compatible `/v1` on HF is chat-only).
2695
+ */
2696
+ async embedHuggingFaceInference(input, model) {
2697
+ const normalizedBase = this.hfInferenceBaseURL.replace(/\/$/, "");
2698
+ const fromSdk = await this.embedViaHuggingfaceInferenceSdk(input, model);
2699
+ if (fromSdk?.length) {
2700
+ if (!_LlmService.embedSuccessLogged) {
2701
+ _LlmService.embedSuccessLogged = true;
2702
+ console.info("[LLM embed HF] first success", { dimension: fromSdk.length, model, via: "@huggingface/inference" });
2703
+ if (!_LlmService.hfDimensionMismatchWarned && fromSdk.length !== 1536) {
2704
+ _LlmService.hfDimensionMismatchWarned = true;
2705
+ console.warn(
2706
+ `[LLM embed HF] Embedding dimensions=${fromSdk.length}; ensure knowledge_base_chunks.embedding uses vector(${fromSdk.length}) (see migrations).`
2707
+ );
2708
+ }
2709
+ } else if (this.embedDebugEnabled()) {
2710
+ console.info("[LLM embed HF] ok", { dimension: fromSdk.length, via: "@huggingface/inference" });
2711
+ }
2712
+ return fromSdk;
2713
+ }
2714
+ const legacyBase = this.hfLegacyInferenceBase(normalizedBase);
2715
+ const baseWithProvider = /\/hf-inference$/i.test(legacyBase) || !/router\.huggingface\.co/i.test(legacyBase) ? legacyBase : `${legacyBase.replace(/\/$/, "")}/hf-inference`;
2716
+ const bodyVariants = [
2717
+ {
2718
+ label: "inputs_parameters_mean_normalize",
2719
+ body: JSON.stringify({
2720
+ inputs: input,
2721
+ parameters: { pooling: "mean", normalize: true },
2722
+ options: { wait_for_model: true }
2723
+ })
2724
+ },
2725
+ {
2726
+ label: "inputs_string",
2727
+ body: JSON.stringify({ inputs: input, options: { wait_for_model: true } })
2728
+ },
2729
+ {
2730
+ label: "inputs_string_array",
2731
+ body: JSON.stringify({ inputs: [input], options: { wait_for_model: true } })
2732
+ },
2733
+ {
2734
+ label: "inputs_wrapped_sentences",
2735
+ body: JSON.stringify({ inputs: { sentences: [input] }, options: { wait_for_model: true } })
2736
+ },
2737
+ {
2738
+ label: "top_level_sentences",
2739
+ body: JSON.stringify({ sentences: [input], options: { wait_for_model: true } })
2740
+ }
2741
+ ];
2742
+ const headers = {
2743
+ "Content-Type": "application/json",
2744
+ Authorization: `Bearer ${this.embeddingApiKey}`
2745
+ };
2746
+ const candidateUrls = [];
2747
+ const pushUrl = (u) => {
2748
+ if (!candidateUrls.includes(u)) candidateUrls.push(u);
2749
+ };
2750
+ pushUrl(`${baseWithProvider}/pipeline/feature-extraction/${model}`);
2751
+ pushUrl(`${baseWithProvider}/models/${model}`);
2752
+ let lastUrl = "";
2753
+ let lastStatus = 0;
2754
+ let lastBodyPreview = "";
2755
+ let lastAttempt = "";
2756
+ for (const embedUrl of candidateUrls) {
2757
+ for (const { label, body } of bodyVariants) {
2758
+ if (this.embedDebugEnabled()) {
2759
+ console.info("[LLM embed HF] attempt", { url: embedUrl, model, inputChars: input.length, body: label });
2760
+ }
2761
+ const res = await fetch(embedUrl, {
2762
+ method: "POST",
2763
+ headers,
2764
+ body
2765
+ });
2766
+ const bodyText = await res.text();
2767
+ lastUrl = embedUrl;
2768
+ lastStatus = res.status;
2769
+ lastBodyPreview = bodyText.slice(0, 800);
2770
+ lastAttempt = `${embedUrl} (${label})`;
2771
+ if (!res.ok) {
2772
+ if (this.embedDebugEnabled()) {
2773
+ console.warn("[LLM embed HF] attempt failed, trying next if any", {
2774
+ url: embedUrl,
2775
+ body: label,
2776
+ status: res.status,
2777
+ bodyPreview: bodyText.slice(0, 200)
2778
+ });
2779
+ }
2780
+ continue;
2781
+ }
2782
+ let data;
2783
+ try {
2784
+ data = JSON.parse(bodyText);
2785
+ } catch {
2786
+ if (this.embedDebugEnabled()) {
2787
+ console.warn("[LLM embed HF] response not JSON, trying next if any", { url: embedUrl, body: label });
2788
+ }
2789
+ continue;
2790
+ }
2791
+ const embedding = parseHfInferenceEmbeddingBody(data);
2792
+ if (!embedding?.length) {
2793
+ if (this.embedDebugEnabled()) {
2794
+ const preview = typeof data === "object" && data !== null && !Array.isArray(data) ? Object.keys(data) : typeof data;
2795
+ console.warn("[LLM embed HF] no parseable embedding, trying next if any", {
2796
+ url: embedUrl,
2797
+ body: label,
2798
+ preview
2799
+ });
2800
+ }
2801
+ continue;
2802
+ }
2803
+ if (!_LlmService.embedSuccessLogged) {
2804
+ _LlmService.embedSuccessLogged = true;
2805
+ console.info("[LLM embed HF] first success", { dimension: embedding.length, model, url: embedUrl, body: label });
2806
+ if (!_LlmService.hfDimensionMismatchWarned && embedding.length !== 1536) {
2807
+ _LlmService.hfDimensionMismatchWarned = true;
2808
+ console.warn(
2809
+ `[LLM embed HF] Embedding dimensions=${embedding.length}; ensure knowledge_base_chunks.embedding uses vector(${embedding.length}) (see migrations).`
2810
+ );
2811
+ }
2812
+ } else if (this.embedDebugEnabled()) {
2813
+ console.info("[LLM embed HF] ok", { dimension: embedding.length, url: embedUrl, body: label });
2814
+ }
2815
+ return embedding;
2816
+ }
2817
+ }
2818
+ if (!_LlmService.embedHttpErrorLogged) {
2819
+ _LlmService.embedHttpErrorLogged = true;
2820
+ console.error(
2821
+ "[LLM embed HF] All Hugging Face embedding attempts failed \u2014 knowledge chunks stay without vectors.",
2822
+ {
2823
+ triedInferenceSdk: true,
2824
+ triedLegacyHttp: candidateUrls,
2825
+ lastAttempt,
2826
+ lastUrl,
2827
+ lastStatus,
2828
+ lastBodyPreview,
2829
+ hint: "Use an HF token with permission to call Inference Providers / Hub API mapping. Install ships @huggingface/inference; EMBEDDING_MODEL defaults to sentence-transformers/all-MiniLM-L6-v2. Router OpenAI /v1/embeddings is not used (chat-only)."
2830
+ }
2831
+ );
2832
+ } else if (this.embedDebugEnabled()) {
2833
+ console.warn("[LLM embed HF] repeat failure (all attempts)", {
2834
+ lastAttempt,
2835
+ lastUrl,
2836
+ lastStatus,
2837
+ bodyPreview: lastBodyPreview.slice(0, 200)
2838
+ });
2839
+ }
2840
+ return [];
2841
+ }
2842
+ buildAgentMessages(options) {
2843
+ const { systemPrompt, userPrompt, history = [], context } = options;
2844
+ const messages = [];
2845
+ let systemContent = systemPrompt?.trim();
2846
+ if (context) {
2847
+ systemContent = systemContent ? `${systemContent}
2848
+
2849
+ Context:
2850
+ ${context}` : `Use the following context to answer:
2851
+
2852
+ ${context}`;
2486
2853
  }
2487
- if (!Array.isArray(embedding) && Array.isArray(data?.data?.[0])) {
2488
- const first = data.data[0];
2489
- embedding = Array.isArray(first) ? first : first?.embedding;
2854
+ if (systemContent) {
2855
+ messages.push({ role: "system", content: systemContent });
2490
2856
  }
2491
- if (!Array.isArray(embedding) && !_LlmService.embedWarned) {
2492
- _LlmService.embedWarned = true;
2493
- console.warn("[LLM embed] Unexpected response shape. Keys:", Object.keys(data), "data[0] type:", Array.isArray(data?.data) ? typeof data.data[0] : "n/a");
2857
+ if (history.length > 0) {
2858
+ messages.push(...history);
2494
2859
  }
2495
- return Array.isArray(embedding) ? embedding : [];
2860
+ messages.push({ role: "user", content: userPrompt });
2861
+ return messages;
2862
+ }
2863
+ async chatAgent(options) {
2864
+ this.logAgentComposition(options);
2865
+ const messages = this.buildAgentMessages(options);
2866
+ const { model, temperature, max_tokens } = options;
2867
+ return this.chat(messages, { model, temperature, max_tokens });
2868
+ }
2869
+ async *streamChatAgent(options) {
2870
+ this.logAgentComposition(options);
2871
+ const messages = this.buildAgentMessages(options);
2872
+ const { model, temperature, max_tokens } = options;
2873
+ yield* this.streamChat(messages, { model, temperature, max_tokens });
2496
2874
  }
2497
2875
  async chat(messages, options = {}) {
2876
+ this.logChatCompletionsRequest("chat", messages, options, false);
2498
2877
  const res = await fetch(this.url, {
2499
2878
  method: "POST",
2500
2879
  headers: {
@@ -2502,7 +2881,7 @@ var LlmService = class _LlmService {
2502
2881
  Authorization: `Bearer ${this.apiKey}`
2503
2882
  },
2504
2883
  body: JSON.stringify({
2505
- model: options.model ?? "qwen2.5:3b-instruct",
2884
+ model: this.resolveChatModel(options.model),
2506
2885
  messages,
2507
2886
  stream: false,
2508
2887
  temperature: options.temperature,
@@ -2511,13 +2890,17 @@ var LlmService = class _LlmService {
2511
2890
  });
2512
2891
  if (!res.ok) {
2513
2892
  const text = await res.text();
2514
- throw new Error(`LLM gateway error: ${res.status} ${text}`);
2893
+ throw new Error(formatLlmGatewayError(res.status, text, this.defaultChatModel));
2515
2894
  }
2516
2895
  const data = await res.json();
2517
2896
  const content = data.choices?.[0]?.message?.content ?? "";
2897
+ if (this.llmDebugEnabled()) {
2898
+ console.log("\n[LLM chat] assistant reply\n", content);
2899
+ }
2518
2900
  return { content };
2519
2901
  }
2520
2902
  async *streamChat(messages, options = {}) {
2903
+ this.logChatCompletionsRequest("streamChat", messages, options, true);
2521
2904
  const res = await fetch(this.url, {
2522
2905
  method: "POST",
2523
2906
  headers: {
@@ -2525,7 +2908,7 @@ var LlmService = class _LlmService {
2525
2908
  Authorization: `Bearer ${this.apiKey}`
2526
2909
  },
2527
2910
  body: JSON.stringify({
2528
- model: options.model ?? "qwen2.5:3b-instruct",
2911
+ model: this.resolveChatModel(options.model),
2529
2912
  messages,
2530
2913
  stream: true,
2531
2914
  temperature: options.temperature,
@@ -2534,12 +2917,14 @@ var LlmService = class _LlmService {
2534
2917
  });
2535
2918
  if (!res.ok) {
2536
2919
  const text = await res.text();
2537
- throw new Error(`LLM gateway error: ${res.status} ${text}`);
2920
+ throw new Error(formatLlmGatewayError(res.status, text, this.defaultChatModel));
2538
2921
  }
2539
2922
  const reader = res.body?.getReader();
2540
2923
  if (!reader) return;
2541
2924
  const decoder = new TextDecoder();
2542
2925
  let buffer = "";
2926
+ const debug = this.llmDebugEnabled();
2927
+ let streamedReply = "";
2543
2928
  while (true) {
2544
2929
  const { value, done } = await reader.read();
2545
2930
  if (done) break;
@@ -2551,16 +2936,28 @@ var LlmService = class _LlmService {
2551
2936
  try {
2552
2937
  const json = JSON.parse(line.slice(6));
2553
2938
  const content = json.choices?.[0]?.delta?.content;
2554
- if (content) yield content;
2939
+ if (content) {
2940
+ if (debug) streamedReply += content;
2941
+ yield content;
2942
+ }
2555
2943
  } catch {
2556
2944
  }
2557
2945
  }
2558
2946
  }
2559
2947
  }
2948
+ if (debug) {
2949
+ console.log("\n[LLM streamChat] assistant reply (full)\n", streamedReply);
2950
+ }
2560
2951
  }
2561
2952
  };
2562
2953
 
2563
2954
  // src/plugins/llm/index.ts
2955
+ function normalizeEmbeddingProvider(raw) {
2956
+ if (!raw) return "openai";
2957
+ const s = raw.toLowerCase().trim();
2958
+ if (s === "huggingface" || s === "hf" || s === "hf_inference" || s === "inference") return "huggingface";
2959
+ return "openai";
2960
+ }
2564
2961
  function llmPlugin(config = {}) {
2565
2962
  return {
2566
2963
  name: "llm",
@@ -2573,7 +2970,18 @@ function llmPlugin(config = {}) {
2573
2970
  return void 0;
2574
2971
  }
2575
2972
  const embeddingModel = config.embeddingModel ?? context.config.EMBEDDING_MODEL;
2576
- return new LlmService(baseURL.replace(/\/$/, ""), apiKey, embeddingModel);
2973
+ const defaultChatModel = config.defaultChatModel?.trim() || (typeof context.config.LLM_CHAT_MODEL === "string" ? context.config.LLM_CHAT_MODEL.trim() : "") || void 0;
2974
+ const embeddingProvider = normalizeEmbeddingProvider(
2975
+ config.embeddingProvider ?? context.config.EMBEDDING_PROVIDER
2976
+ );
2977
+ const hfInferenceBaseUrl = config.hfInferenceBaseUrl ?? context.config.HF_INFERENCE_URL;
2978
+ const embeddingApiKey = config.embeddingApiKey ?? context.config.EMBEDDING_API_KEY;
2979
+ return new LlmService(baseURL.replace(/\/$/, ""), apiKey, embeddingModel, {
2980
+ embeddingProvider,
2981
+ hfInferenceBaseUrl,
2982
+ embeddingApiKey,
2983
+ defaultChatModel
2984
+ });
2577
2985
  }
2578
2986
  };
2579
2987
  }
@@ -3437,6 +3845,86 @@ init_email_queue();
3437
3845
  init_erp_queue();
3438
3846
  import { MoreThanOrEqual, ILike, In } from "typeorm";
3439
3847
 
3848
+ // src/entities/llm-agent.entity.ts
3849
+ import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
3850
+ var LlmAgent = class {
3851
+ id;
3852
+ name;
3853
+ slug;
3854
+ systemInstruction;
3855
+ model;
3856
+ temperature;
3857
+ maxTokens;
3858
+ validationRules;
3859
+ enabled;
3860
+ createdAt;
3861
+ updatedAt;
3862
+ deletedAt;
3863
+ deleted;
3864
+ createdBy;
3865
+ updatedBy;
3866
+ deletedBy;
3867
+ };
3868
+ __decorateClass([
3869
+ PrimaryGeneratedColumn()
3870
+ ], LlmAgent.prototype, "id", 2);
3871
+ __decorateClass([
3872
+ Column("varchar")
3873
+ ], LlmAgent.prototype, "name", 2);
3874
+ __decorateClass([
3875
+ Column("varchar")
3876
+ ], LlmAgent.prototype, "slug", 2);
3877
+ __decorateClass([
3878
+ Column("text", { name: "system_instruction", default: "" })
3879
+ ], LlmAgent.prototype, "systemInstruction", 2);
3880
+ __decorateClass([
3881
+ Column("varchar", { nullable: true })
3882
+ ], LlmAgent.prototype, "model", 2);
3883
+ __decorateClass([
3884
+ Column("double precision", { name: "temperature", nullable: true })
3885
+ ], LlmAgent.prototype, "temperature", 2);
3886
+ __decorateClass([
3887
+ Column("int", { name: "max_tokens", nullable: true })
3888
+ ], LlmAgent.prototype, "maxTokens", 2);
3889
+ __decorateClass([
3890
+ Column("text", { name: "validation_rules", nullable: true })
3891
+ ], LlmAgent.prototype, "validationRules", 2);
3892
+ __decorateClass([
3893
+ Column("boolean", { default: true })
3894
+ ], LlmAgent.prototype, "enabled", 2);
3895
+ __decorateClass([
3896
+ Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
3897
+ ], LlmAgent.prototype, "createdAt", 2);
3898
+ __decorateClass([
3899
+ Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
3900
+ ], LlmAgent.prototype, "updatedAt", 2);
3901
+ __decorateClass([
3902
+ Column({ type: "timestamp", nullable: true })
3903
+ ], LlmAgent.prototype, "deletedAt", 2);
3904
+ __decorateClass([
3905
+ Column("boolean", { default: false })
3906
+ ], LlmAgent.prototype, "deleted", 2);
3907
+ __decorateClass([
3908
+ Column("int", { nullable: true })
3909
+ ], LlmAgent.prototype, "createdBy", 2);
3910
+ __decorateClass([
3911
+ Column("int", { nullable: true })
3912
+ ], LlmAgent.prototype, "updatedBy", 2);
3913
+ __decorateClass([
3914
+ Column("int", { nullable: true })
3915
+ ], LlmAgent.prototype, "deletedBy", 2);
3916
+ LlmAgent = __decorateClass([
3917
+ Entity("llm_agents")
3918
+ ], LlmAgent);
3919
+ function llmAgentToChatAgentOptions(agent) {
3920
+ return {
3921
+ systemPrompt: agent.systemInstruction?.trim() || void 0,
3922
+ model: agent.model?.trim() || void 0,
3923
+ temperature: agent.temperature ?? void 0,
3924
+ max_tokens: agent.maxTokens ?? void 0
3925
+ };
3926
+ }
3927
+
3440
3928
  // src/lib/media-folder-path.ts
3441
3929
  function sanitizeMediaFolderPath(input) {
3442
3930
  if (input == null) return "";
@@ -3626,6 +4114,82 @@ async function extractZipMediaIntoParentTree(opts) {
3626
4114
  }
3627
4115
 
3628
4116
  // src/api/cms-handlers.ts
4117
+ function historyBeforeCurrentUser(history, currentUserContent) {
4118
+ const last = history[history.length - 1];
4119
+ if (last?.role === "user" && last.content === currentUserContent) {
4120
+ return history.slice(0, -1);
4121
+ }
4122
+ return [...history];
4123
+ }
4124
+ function pickStructuredRules(rules) {
4125
+ return {
4126
+ maxUserChars: rules.maxUserChars,
4127
+ maxMessageLength: rules.maxMessageLength,
4128
+ minUserChars: rules.minUserChars,
4129
+ minMessageLength: rules.minMessageLength,
4130
+ blockedSubstrings: rules.blockedSubstrings
4131
+ };
4132
+ }
4133
+ function guardrailsTextFromJsonObject(rules) {
4134
+ const g = typeof rules.guardrails === "string" && rules.guardrails.trim() || typeof rules.outputRules === "string" && rules.outputRules.trim() || typeof rules.outputInstructions === "string" && rules.outputInstructions.trim() || "";
4135
+ return g || null;
4136
+ }
4137
+ function parseLlmAgentValidationRules(validationRulesText) {
4138
+ const raw = validationRulesText?.trim();
4139
+ if (!raw) return { structured: {}, guardrailsForPrompt: null };
4140
+ try {
4141
+ const parsed = JSON.parse(raw);
4142
+ if (typeof parsed === "string") {
4143
+ const s = parsed.trim();
4144
+ return { structured: {}, guardrailsForPrompt: s || null };
4145
+ }
4146
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
4147
+ return { structured: {}, guardrailsForPrompt: raw };
4148
+ }
4149
+ const rules = parsed;
4150
+ return {
4151
+ structured: pickStructuredRules(rules),
4152
+ guardrailsForPrompt: guardrailsTextFromJsonObject(rules)
4153
+ };
4154
+ } catch {
4155
+ return { structured: {}, guardrailsForPrompt: raw };
4156
+ }
4157
+ }
4158
+ function validateUserMessageAgainstStructuredRules(message, structured) {
4159
+ const maxLen = structured.maxUserChars ?? structured.maxMessageLength;
4160
+ if (typeof maxLen === "number" && Number.isFinite(maxLen) && maxLen >= 0 && message.length > maxLen) {
4161
+ return { ok: false, error: `Message exceeds maximum length (${maxLen} characters)` };
4162
+ }
4163
+ const minLen = structured.minUserChars ?? structured.minMessageLength;
4164
+ if (typeof minLen === "number" && Number.isFinite(minLen) && minLen > 0 && message.length < minLen) {
4165
+ return { ok: false, error: `Message is shorter than minimum length (${minLen} characters)` };
4166
+ }
4167
+ const blocked = structured.blockedSubstrings;
4168
+ if (Array.isArray(blocked) && blocked.length > 0) {
4169
+ const lower = message.toLowerCase();
4170
+ for (const s of blocked) {
4171
+ if (typeof s !== "string" || !s.trim()) continue;
4172
+ if (lower.includes(s.toLowerCase())) {
4173
+ return { ok: false, error: "Message contains disallowed content" };
4174
+ }
4175
+ }
4176
+ }
4177
+ return { ok: true };
4178
+ }
4179
+ function validateUserMessageAgainstAgentRules(message, validationRulesText) {
4180
+ const { structured } = parseLlmAgentValidationRules(validationRulesText);
4181
+ return validateUserMessageAgainstStructuredRules(message, structured);
4182
+ }
4183
+ function mergeGuardrailsIntoSystemPrompt(baseSystem, guardrailsForPrompt) {
4184
+ const g = guardrailsForPrompt?.trim();
4185
+ const b = (baseSystem ?? "").trim();
4186
+ if (!g) return b;
4187
+ const block = `### Output guardrails (follow in every reply)
4188
+ ${g}`;
4189
+ return b ? `${b}
4190
+
4191
+ ${block}` : block;
4192
+ }
3629
4193
  function createDashboardStatsHandler(config) {
3630
4194
  const { dataSource, entityMap, json, requireAuth, requirePermission, requireEntityPermission } = config;
3631
4195
  return async function GET(req) {
@@ -4707,9 +5271,24 @@ function createSettingsApiHandlers(config) {
4707
5271
  }
4708
5272
  var KB_CHUNK_LIMIT = 10;
4709
5273
  var KB_CONTEXT_MAX_CHARS = 4e3;
5274
+ var RAG_LOG = "[rag-context]";
4710
5275
  function getQueryTerms(message) {
4711
5276
  return message.replace(/[^\w\s]/g, " ").split(/\s+/).filter((w) => w.length > 2).slice(0, 6);
4712
5277
  }
5278
+ function normalizeChatModeSetting(raw) {
5279
+ if (raw === "external" || raw === "llm") return raw;
5280
+ return "whatsapp";
5281
+ }
5282
+ async function loadLlmSettingsMap(dataSource, entityMap) {
5283
+ if (!entityMap.configs) return {};
5284
+ const repo = dataSource.getRepository(entityMap.configs);
5285
+ const rows = await repo.find({ where: { settings: "llm", deleted: false } });
5286
+ const out = {};
5287
+ for (const row of rows) {
5288
+ out[row.key] = row.value;
5289
+ }
5290
+ return out;
5291
+ }
4713
5292
  function createChatHandlers(config) {
4714
5293
  const { dataSource, entityMap, json, getCms } = config;
4715
5294
  const contactRepo = () => dataSource.getRepository(entityMap.contacts);
@@ -4717,6 +5296,26 @@ function createChatHandlers(config) {
4717
5296
  const msgRepo = () => dataSource.getRepository(entityMap.chat_messages);
4718
5297
  const chunkRepo = () => dataSource.getRepository(entityMap.knowledge_base_chunks);
4719
5298
  return {
5299
+ async publicConfig(_req) {
5300
+ try {
5301
+ const map = await loadLlmSettingsMap(dataSource, entityMap);
5302
+ const mode = normalizeChatModeSetting(map.chatMode);
5303
+ const body = {
5304
+ enabled: map.enabled !== "false",
5305
+ chatMode: mode,
5306
+ agentSlug: mode === "llm" ? (map.attachedAgentSlug ?? "").trim() : "",
5307
+ botName: map.botName ?? "",
5308
+ icon: map.icon ?? "",
5309
+ iconImageUrl: map.iconImageUrl ?? "",
5310
+ iconBackgroundColor: map.iconBackgroundColor ?? "#6366f1",
5311
+ headerColor: map.headerColor ?? "#6366f1",
5312
+ whatsappPhone: map.whatsappPhone ?? ""
5313
+ };
5314
+ return json(body);
5315
+ } catch {
5316
+ return json({ error: "Failed to load chat config" }, { status: 500 });
5317
+ }
5318
+ },
4720
5319
  async identify(req) {
4721
5320
  try {
4722
5321
  const body = await req.json();
@@ -4764,20 +5363,78 @@ function createChatHandlers(config) {
4764
5363
  relations: ["messages"]
4765
5364
  });
4766
5365
  if (!conv) return json({ error: "Conversation not found" }, { status: 404 });
4767
- const msgRepoInst = msgRepo();
4768
- await msgRepoInst.save(msgRepoInst.create({ conversationId, role: "user", content: message }));
4769
5366
  const cms = await getCms();
4770
5367
  const llm = cms.getPlugin("llm");
4771
5368
  if (!llm?.chat) return json({ error: "LLM not configured" }, { status: 503 });
5369
+ const llmSettings = await loadLlmSettingsMap(dataSource, entityMap);
5370
+ const supportMode = normalizeChatModeSetting(llmSettings.chatMode);
5371
+ let effectiveSlug = (body?.agentSlug ?? "").trim();
5372
+ if (!effectiveSlug && supportMode === "llm" && entityMap.llm_agents) {
5373
+ effectiveSlug = (llmSettings.attachedAgentSlug ?? "").trim();
5374
+ }
5375
+ let agentRow = null;
5376
+ if (effectiveSlug) {
5377
+ if (!entityMap.llm_agents) {
5378
+ return json({ error: "LLM agents are not configured on this deployment" }, { status: 400 });
5379
+ }
5380
+ const agentRepo = dataSource.getRepository(
5381
+ entityMap.llm_agents
5382
+ );
5383
+ agentRow = await agentRepo.findOne({
5384
+ where: { slug: effectiveSlug, deleted: false, enabled: true }
5385
+ });
5386
+ if (!agentRow && (body?.agentSlug ?? "").trim()) {
5387
+ return json({ error: "Agent not found or disabled", agentSlug: effectiveSlug }, { status: 404 });
5388
+ }
5389
+ }
5390
+ console.info(RAG_LOG, "step 1 | resolve agent", {
5391
+ agentSlug: effectiveSlug || "(none)",
5392
+ agentFound: !!agentRow,
5393
+ agentId: agentRow?.id ?? null
5394
+ });
5395
+ const parsedValidation = agentRow ? parseLlmAgentValidationRules(agentRow.validationRules) : { structured: {}, guardrailsForPrompt: null };
5396
+ if (agentRow) {
5397
+ const v = validateUserMessageAgainstStructuredRules(message, parsedValidation.structured);
5398
+ if (!v.ok) return json({ error: v.error, reason: "validation_failed" }, { status: 400 });
5399
+ }
5400
+ let kbDocumentScope;
5401
+ const Junction = entityMap.llm_agent_knowledge_documents;
5402
+ if (agentRow && Junction) {
5403
+ const linkRepo = dataSource.getRepository(Junction);
5404
+ const links = await linkRepo.find({ where: { agentId: agentRow.id } });
5405
+ const ids = [...new Set(links.map((l) => l.documentId))];
5406
+ if (ids.length > 0) kbDocumentScope = ids;
5407
+ }
5408
+ console.info(RAG_LOG, "step 2 | knowledge scope", {
5409
+ scopedDocumentIds: kbDocumentScope ?? "(all documents)",
5410
+ documentCount: kbDocumentScope?.length ?? "all"
5411
+ });
5412
+ const msgRepoInst = msgRepo();
5413
+ await msgRepoInst.save(msgRepoInst.create({ conversationId, role: "user", content: message }));
4772
5414
  let contextParts = [];
5415
+ console.info(RAG_LOG, "step 3 | embed user query", {
5416
+ messageChars: message.length,
5417
+ embedAvailable: !!llm.embed
5418
+ });
4773
5419
  const queryEmbedding = llm.embed ? await llm.embed(message) : null;
5420
+ console.info(RAG_LOG, "step 4 | query embedding result", {
5421
+ dimensions: queryEmbedding?.length ?? 0,
5422
+ hasEmbedding: !!(queryEmbedding && queryEmbedding.length > 0)
5423
+ });
4774
5424
  if (queryEmbedding && queryEmbedding.length > 0) {
4775
5425
  const vectorStr = "[" + queryEmbedding.join(",") + "]";
4776
5426
  try {
4777
- const rows = await dataSource.query(
5427
+ const rows = kbDocumentScope?.length ? await dataSource.query(
5428
+ `SELECT id, content FROM knowledge_base_chunks WHERE embedding IS NOT NULL AND "documentId" = ANY($3::int[]) ORDER BY embedding <=> $1::vector LIMIT $2`,
5429
+ [vectorStr, KB_CHUNK_LIMIT, kbDocumentScope]
5430
+ ) : await dataSource.query(
4778
5431
  `SELECT id, content FROM knowledge_base_chunks WHERE embedding IS NOT NULL ORDER BY embedding <=> $1::vector LIMIT $2`,
4779
5432
  [vectorStr, KB_CHUNK_LIMIT]
4780
5433
  );
5434
+ console.info(RAG_LOG, "step 5 | vector search results", {
5435
+ rowsReturned: rows.length,
5436
+ chunkIds: rows.map((r) => r.id)
5437
+ });
4781
5438
  let totalLen = 0;
4782
5439
  for (const r of rows) {
4783
5440
  const text = (r.content ?? "").trim();
@@ -4785,13 +5442,24 @@ function createChatHandlers(config) {
4785
5442
  contextParts.push(text);
4786
5443
  totalLen += text.length;
4787
5444
  }
4788
- } catch {
5445
+ console.info(RAG_LOG, "step 5a | vector context selected", {
5446
+ chunksUsed: contextParts.length,
5447
+ totalChars: totalLen
5448
+ });
5449
+ } catch (vecErr) {
5450
+ console.warn(RAG_LOG, "step 5 | vector search failed; falling back to keyword", {
5451
+ err: vecErr instanceof Error ? vecErr.message : String(vecErr)
5452
+ });
4789
5453
  }
4790
5454
  }
4791
5455
  if (contextParts.length === 0) {
4792
5456
  const terms = getQueryTerms(message);
5457
+ console.info(RAG_LOG, "step 6 | keyword fallback", {
5458
+ reason: !(queryEmbedding && queryEmbedding.length > 0) ? "no embedding" : "vector search returned nothing",
5459
+ searchTerms: terms
5460
+ });
4793
5461
  if (terms.length > 0) {
4794
- const conditions = terms.map((t) => ({ content: ILike(`%${t}%`) }));
5462
+ const conditions = kbDocumentScope?.length ? terms.map((t) => ({ content: ILike(`%${t}%`), documentId: In(kbDocumentScope) })) : terms.map((t) => ({ content: ILike(`%${t}%`) }));
4795
5463
  const chunks = await chunkRepo().find({
4796
5464
  where: conditions,
4797
5465
  take: KB_CHUNK_LIMIT,
@@ -4806,19 +5474,66 @@ function createChatHandlers(config) {
4806
5474
  contextParts.push(text);
4807
5475
  totalLen += text.length;
4808
5476
  }
5477
+ console.info(RAG_LOG, "step 6a | keyword results", {
5478
+ chunksFound: chunks.length,
5479
+ chunksUsed: contextParts.length,
5480
+ totalChars: totalLen
5481
+ });
4809
5482
  }
4810
5483
  }
4811
- const history = (conv.messages ?? []).sort((a, b) => new Date(a.createdAt ?? 0).getTime() - new Date(b.createdAt ?? 0).getTime()).map((m) => ({ role: m.role, content: m.content }));
4812
- const systemContent = contextParts.length > 0 ? `Use the following context about the company and its products to answer. If the answer is not in the context, say so.
5484
+ const historyRaw = (conv.messages ?? []).sort((a, b) => new Date(a.createdAt ?? 0).getTime() - new Date(b.createdAt ?? 0).getTime()).map((m) => ({ role: m.role, content: m.content }));
5485
+ const history = historyBeforeCurrentUser(historyRaw, message);
5486
+ let content;
5487
+ const ragContext = contextParts.length > 0 ? contextParts.join("\n\n") : void 0;
5488
+ console.info(RAG_LOG, "step 7 | final context", {
5489
+ method: contextParts.length > 0 ? "rag" : "none",
5490
+ contextChunks: contextParts.length,
5491
+ contextChars: ragContext?.length ?? 0,
5492
+ contextPreview: ragContext ? ragContext.slice(0, 200) + (ragContext.length > 200 ? "\u2026" : "") : "(no context)"
5493
+ });
5494
+ if (agentRow && llm.chatAgent) {
5495
+ const fromAgent = llmAgentToChatAgentOptions(agentRow);
5496
+ const systemPrompt = mergeGuardrailsIntoSystemPrompt(
5497
+ fromAgent.systemPrompt,
5498
+ parsedValidation.guardrailsForPrompt
5499
+ );
5500
+ const res = await llm.chatAgent({
5501
+ ...fromAgent,
5502
+ systemPrompt: systemPrompt || void 0,
5503
+ context: ragContext,
5504
+ history,
5505
+ userPrompt: message
5506
+ });
5507
+ content = res.content;
5508
+ } else {
5509
+ const ragSystem = contextParts.length > 0 ? `Use the following context about the company and its products to answer. If the answer is not in the context, say so.
4813
5510
 
4814
5511
  Context:
4815
- ${contextParts.join("\n\n")}` : "You are a helpful assistant for the company. If you do not have specific information, say so.";
4816
- const messages = [
4817
- { role: "system", content: systemContent },
4818
- ...history,
4819
- { role: "user", content: message }
4820
- ];
4821
- const { content } = await llm.chat(messages);
5512
+ ${contextParts.join("\n\n")}` : "";
5513
+ const defaultSystem = "You are a helpful assistant for the company. If you do not have specific information, say so.";
5514
+ let systemContent;
5515
+ if (agentRow) {
5516
+ const base = agentRow.systemInstruction?.trim() || "";
5517
+ systemContent = mergeGuardrailsIntoSystemPrompt(
5518
+ [base, ragSystem].filter(Boolean).join("\n\n") || defaultSystem,
5519
+ parsedValidation.guardrailsForPrompt
5520
+ );
5521
+ } else {
5522
+ systemContent = ragSystem || defaultSystem;
5523
+ }
5524
+ const messages = [
5525
+ { role: "system", content: systemContent },
5526
+ ...history,
5527
+ { role: "user", content: message }
5528
+ ];
5529
+ const chatOpts = agentRow ? {
5530
+ model: agentRow.model ?? void 0,
5531
+ temperature: agentRow.temperature ?? void 0,
5532
+ max_tokens: agentRow.maxTokens ?? void 0
5533
+ } : {};
5534
+ const res = await llm.chat(messages, chatOpts);
5535
+ content = res.content;
5536
+ }
4822
5537
  await msgRepoInst.save(msgRepoInst.create({ conversationId, role: "assistant", content }));
4823
5538
  return json({ content });
4824
5539
  } catch (err) {
@@ -4877,13 +5592,13 @@ async function loadPublicThemeSettings(config) {
4877
5592
  }
4878
5593
 
4879
5594
  // src/entities/user.entity.ts
4880
- import { Entity as Entity3, PrimaryGeneratedColumn as PrimaryGeneratedColumn3, Column as Column3, ManyToOne as ManyToOne2, JoinColumn as JoinColumn2 } from "typeorm";
5595
+ import { Entity as Entity4, PrimaryGeneratedColumn as PrimaryGeneratedColumn4, Column as Column4, ManyToOne as ManyToOne2, JoinColumn as JoinColumn2 } from "typeorm";
4881
5596
 
4882
5597
  // src/entities/user-group.entity.ts
4883
- import { Entity as Entity2, PrimaryGeneratedColumn as PrimaryGeneratedColumn2, Column as Column2, OneToMany } from "typeorm";
5598
+ import { Entity as Entity3, PrimaryGeneratedColumn as PrimaryGeneratedColumn3, Column as Column3, OneToMany } from "typeorm";
4884
5599
 
4885
5600
  // src/entities/permission.entity.ts
4886
- import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from "typeorm";
5601
+ import { Entity as Entity2, PrimaryGeneratedColumn as PrimaryGeneratedColumn2, Column as Column2, ManyToOne, JoinColumn } from "typeorm";
4887
5602
  var Permission = class {
4888
5603
  id;
4889
5604
  groupId;
@@ -4902,53 +5617,53 @@ var Permission = class {
4902
5617
  group;
4903
5618
  };
4904
5619
  __decorateClass([
4905
- PrimaryGeneratedColumn()
5620
+ PrimaryGeneratedColumn2()
4906
5621
  ], Permission.prototype, "id", 2);
4907
5622
  __decorateClass([
4908
- Column("int")
5623
+ Column2("int")
4909
5624
  ], Permission.prototype, "groupId", 2);
4910
5625
  __decorateClass([
4911
- Column("varchar")
5626
+ Column2("varchar")
4912
5627
  ], Permission.prototype, "entity", 2);
4913
5628
  __decorateClass([
4914
- Column("boolean", { default: false })
5629
+ Column2("boolean", { default: false })
4915
5630
  ], Permission.prototype, "canCreate", 2);
4916
5631
  __decorateClass([
4917
- Column("boolean", { default: false })
5632
+ Column2("boolean", { default: false })
4918
5633
  ], Permission.prototype, "canRead", 2);
4919
5634
  __decorateClass([
4920
- Column("boolean", { default: false })
5635
+ Column2("boolean", { default: false })
4921
5636
  ], Permission.prototype, "canUpdate", 2);
4922
5637
  __decorateClass([
4923
- Column("boolean", { default: false })
5638
+ Column2("boolean", { default: false })
4924
5639
  ], Permission.prototype, "canDelete", 2);
4925
5640
  __decorateClass([
4926
- Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5641
+ Column2({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
4927
5642
  ], Permission.prototype, "createdAt", 2);
4928
5643
  __decorateClass([
4929
- Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5644
+ Column2({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
4930
5645
  ], Permission.prototype, "updatedAt", 2);
4931
5646
  __decorateClass([
4932
- Column({ type: "timestamp", nullable: true })
5647
+ Column2({ type: "timestamp", nullable: true })
4933
5648
  ], Permission.prototype, "deletedAt", 2);
4934
5649
  __decorateClass([
4935
- Column("boolean", { default: false })
5650
+ Column2("boolean", { default: false })
4936
5651
  ], Permission.prototype, "deleted", 2);
4937
5652
  __decorateClass([
4938
- Column("int", { nullable: true })
5653
+ Column2("int", { nullable: true })
4939
5654
  ], Permission.prototype, "createdBy", 2);
4940
5655
  __decorateClass([
4941
- Column("int", { nullable: true })
5656
+ Column2("int", { nullable: true })
4942
5657
  ], Permission.prototype, "updatedBy", 2);
4943
5658
  __decorateClass([
4944
- Column("int", { nullable: true })
5659
+ Column2("int", { nullable: true })
4945
5660
  ], Permission.prototype, "deletedBy", 2);
4946
5661
  __decorateClass([
4947
5662
  ManyToOne(() => UserGroup, (g) => g.permissions, { onDelete: "CASCADE" }),
4948
5663
  JoinColumn({ name: "groupId" })
4949
5664
  ], Permission.prototype, "group", 2);
4950
5665
  Permission = __decorateClass([
4951
- Entity("permissions")
5666
+ Entity2("permissions")
4952
5667
  ], Permission);
4953
5668
 
4954
5669
  // src/entities/user-group.entity.ts
@@ -4966,31 +5681,31 @@ var UserGroup = class {
4966
5681
  users;
4967
5682
  };
4968
5683
  __decorateClass([
4969
- PrimaryGeneratedColumn2()
5684
+ PrimaryGeneratedColumn3()
4970
5685
  ], UserGroup.prototype, "id", 2);
4971
5686
  __decorateClass([
4972
- Column2("varchar", { unique: true })
5687
+ Column3("varchar", { unique: true })
4973
5688
  ], UserGroup.prototype, "name", 2);
4974
5689
  __decorateClass([
4975
- Column2({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5690
+ Column3({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
4976
5691
  ], UserGroup.prototype, "createdAt", 2);
4977
5692
  __decorateClass([
4978
- Column2({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5693
+ Column3({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
4979
5694
  ], UserGroup.prototype, "updatedAt", 2);
4980
5695
  __decorateClass([
4981
- Column2({ type: "timestamp", nullable: true })
5696
+ Column3({ type: "timestamp", nullable: true })
4982
5697
  ], UserGroup.prototype, "deletedAt", 2);
4983
5698
  __decorateClass([
4984
- Column2("boolean", { default: false })
5699
+ Column3("boolean", { default: false })
4985
5700
  ], UserGroup.prototype, "deleted", 2);
4986
5701
  __decorateClass([
4987
- Column2("int", { nullable: true })
5702
+ Column3("int", { nullable: true })
4988
5703
  ], UserGroup.prototype, "createdBy", 2);
4989
5704
  __decorateClass([
4990
- Column2("int", { nullable: true })
5705
+ Column3("int", { nullable: true })
4991
5706
  ], UserGroup.prototype, "updatedBy", 2);
4992
5707
  __decorateClass([
4993
- Column2("int", { nullable: true })
5708
+ Column3("int", { nullable: true })
4994
5709
  ], UserGroup.prototype, "deletedBy", 2);
4995
5710
  __decorateClass([
4996
5711
  OneToMany(() => Permission, (p) => p.group)
@@ -4999,7 +5714,7 @@ __decorateClass([
4999
5714
  OneToMany(() => User, (u) => u.group)
5000
5715
  ], UserGroup.prototype, "users", 2);
5001
5716
  UserGroup = __decorateClass([
5002
- Entity2("user_groups")
5717
+ Entity3("user_groups")
5003
5718
  ], UserGroup);
5004
5719
 
5005
5720
  // src/entities/user.entity.ts
@@ -5024,66 +5739,66 @@ var User = class {
5024
5739
  group;
5025
5740
  };
5026
5741
  __decorateClass([
5027
- PrimaryGeneratedColumn3()
5742
+ PrimaryGeneratedColumn4()
5028
5743
  ], User.prototype, "id", 2);
5029
5744
  __decorateClass([
5030
- Column3("varchar")
5745
+ Column4("varchar")
5031
5746
  ], User.prototype, "name", 2);
5032
5747
  __decorateClass([
5033
- Column3("varchar", { unique: true })
5748
+ Column4("varchar", { unique: true })
5034
5749
  ], User.prototype, "email", 2);
5035
5750
  __decorateClass([
5036
- Column3("varchar", { nullable: true })
5751
+ Column4("varchar", { nullable: true })
5037
5752
  ], User.prototype, "phone", 2);
5038
5753
  __decorateClass([
5039
- Column3({ type: "timestamp", nullable: true })
5754
+ Column4({ type: "timestamp", nullable: true })
5040
5755
  ], User.prototype, "phoneVerifiedAt", 2);
5041
5756
  __decorateClass([
5042
- Column3({ type: "timestamp", nullable: true })
5757
+ Column4({ type: "timestamp", nullable: true })
5043
5758
  ], User.prototype, "emailVerifiedAt", 2);
5044
5759
  __decorateClass([
5045
- Column3("varchar", { nullable: true })
5760
+ Column4("varchar", { nullable: true })
5046
5761
  ], User.prototype, "password", 2);
5047
5762
  __decorateClass([
5048
- Column3("boolean", { default: false })
5763
+ Column4("boolean", { default: false })
5049
5764
  ], User.prototype, "blocked", 2);
5050
5765
  __decorateClass([
5051
- Column3("boolean", { default: false })
5766
+ Column4("boolean", { default: false })
5052
5767
  ], User.prototype, "adminAccess", 2);
5053
5768
  __decorateClass([
5054
- Column3("int", { nullable: true })
5769
+ Column4("int", { nullable: true })
5055
5770
  ], User.prototype, "groupId", 2);
5056
5771
  __decorateClass([
5057
- Column3({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5772
+ Column4({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5058
5773
  ], User.prototype, "createdAt", 2);
5059
5774
  __decorateClass([
5060
- Column3({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5775
+ Column4({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5061
5776
  ], User.prototype, "updatedAt", 2);
5062
5777
  __decorateClass([
5063
- Column3({ type: "timestamp", nullable: true })
5778
+ Column4({ type: "timestamp", nullable: true })
5064
5779
  ], User.prototype, "deletedAt", 2);
5065
5780
  __decorateClass([
5066
- Column3("boolean", { default: false })
5781
+ Column4("boolean", { default: false })
5067
5782
  ], User.prototype, "deleted", 2);
5068
5783
  __decorateClass([
5069
- Column3("int", { nullable: true })
5784
+ Column4("int", { nullable: true })
5070
5785
  ], User.prototype, "createdBy", 2);
5071
5786
  __decorateClass([
5072
- Column3("int", { nullable: true })
5787
+ Column4("int", { nullable: true })
5073
5788
  ], User.prototype, "updatedBy", 2);
5074
5789
  __decorateClass([
5075
- Column3("int", { nullable: true })
5790
+ Column4("int", { nullable: true })
5076
5791
  ], User.prototype, "deletedBy", 2);
5077
5792
  __decorateClass([
5078
5793
  ManyToOne2(() => UserGroup, (g) => g.users, { onDelete: "SET NULL" }),
5079
5794
  JoinColumn2({ name: "groupId" })
5080
5795
  ], User.prototype, "group", 2);
5081
5796
  User = __decorateClass([
5082
- Entity3("users")
5797
+ Entity4("users")
5083
5798
  ], User);
5084
5799
 
5085
5800
  // src/entities/otp-challenge.entity.ts
5086
- import { Entity as Entity4, PrimaryGeneratedColumn as PrimaryGeneratedColumn4, Column as Column4, Index } from "typeorm";
5801
+ import { Entity as Entity5, PrimaryGeneratedColumn as PrimaryGeneratedColumn5, Column as Column5, Index } from "typeorm";
5087
5802
  var OtpChallenge = class {
5088
5803
  id;
5089
5804
  purpose;
@@ -5096,39 +5811,39 @@ var OtpChallenge = class {
5096
5811
  createdAt;
5097
5812
  };
5098
5813
  __decorateClass([
5099
- PrimaryGeneratedColumn4()
5814
+ PrimaryGeneratedColumn5()
5100
5815
  ], OtpChallenge.prototype, "id", 2);
5101
5816
  __decorateClass([
5102
- Column4("varchar")
5817
+ Column5("varchar")
5103
5818
  ], OtpChallenge.prototype, "purpose", 2);
5104
5819
  __decorateClass([
5105
- Column4("varchar")
5820
+ Column5("varchar")
5106
5821
  ], OtpChallenge.prototype, "channel", 2);
5107
5822
  __decorateClass([
5108
- Column4("varchar")
5823
+ Column5("varchar")
5109
5824
  ], OtpChallenge.prototype, "identifier", 2);
5110
5825
  __decorateClass([
5111
- Column4("varchar")
5826
+ Column5("varchar")
5112
5827
  ], OtpChallenge.prototype, "codeHash", 2);
5113
5828
  __decorateClass([
5114
- Column4({ type: "timestamp" })
5829
+ Column5({ type: "timestamp" })
5115
5830
  ], OtpChallenge.prototype, "expiresAt", 2);
5116
5831
  __decorateClass([
5117
- Column4("int", { default: 0 })
5832
+ Column5("int", { default: 0 })
5118
5833
  ], OtpChallenge.prototype, "attempts", 2);
5119
5834
  __decorateClass([
5120
- Column4({ type: "timestamp", nullable: true })
5835
+ Column5({ type: "timestamp", nullable: true })
5121
5836
  ], OtpChallenge.prototype, "consumedAt", 2);
5122
5837
  __decorateClass([
5123
- Column4({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5838
+ Column5({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5124
5839
  ], OtpChallenge.prototype, "createdAt", 2);
5125
5840
  OtpChallenge = __decorateClass([
5126
- Entity4("otp_challenges"),
5841
+ Entity5("otp_challenges"),
5127
5842
  Index(["purpose", "identifier"])
5128
5843
  ], OtpChallenge);
5129
5844
 
5130
5845
  // src/entities/password-reset-token.entity.ts
5131
- import { Entity as Entity5, PrimaryGeneratedColumn as PrimaryGeneratedColumn5, Column as Column5 } from "typeorm";
5846
+ import { Entity as Entity6, PrimaryGeneratedColumn as PrimaryGeneratedColumn6, Column as Column6 } from "typeorm";
5132
5847
  var PasswordResetToken = class {
5133
5848
  id;
5134
5849
  email;
@@ -5137,29 +5852,29 @@ var PasswordResetToken = class {
5137
5852
  createdAt;
5138
5853
  };
5139
5854
  __decorateClass([
5140
- PrimaryGeneratedColumn5()
5855
+ PrimaryGeneratedColumn6()
5141
5856
  ], PasswordResetToken.prototype, "id", 2);
5142
5857
  __decorateClass([
5143
- Column5("varchar")
5858
+ Column6("varchar")
5144
5859
  ], PasswordResetToken.prototype, "email", 2);
5145
5860
  __decorateClass([
5146
- Column5("varchar", { unique: true })
5861
+ Column6("varchar", { unique: true })
5147
5862
  ], PasswordResetToken.prototype, "token", 2);
5148
5863
  __decorateClass([
5149
- Column5({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5864
+ Column6({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5150
5865
  ], PasswordResetToken.prototype, "expiresAt", 2);
5151
5866
  __decorateClass([
5152
- Column5({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5867
+ Column6({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5153
5868
  ], PasswordResetToken.prototype, "createdAt", 2);
5154
5869
  PasswordResetToken = __decorateClass([
5155
- Entity5("password_reset_tokens")
5870
+ Entity6("password_reset_tokens")
5156
5871
  ], PasswordResetToken);
5157
5872
 
5158
5873
  // src/entities/blog.entity.ts
5159
5874
  import {
5160
- Entity as Entity10,
5161
- PrimaryGeneratedColumn as PrimaryGeneratedColumn10,
5162
- Column as Column10,
5875
+ Entity as Entity11,
5876
+ PrimaryGeneratedColumn as PrimaryGeneratedColumn11,
5877
+ Column as Column11,
5163
5878
  ManyToOne as ManyToOne4,
5164
5879
  OneToMany as OneToMany4,
5165
5880
  ManyToMany as ManyToMany2,
@@ -5168,7 +5883,7 @@ import {
5168
5883
  } from "typeorm";
5169
5884
 
5170
5885
  // src/entities/category.entity.ts
5171
- import { Entity as Entity6, PrimaryGeneratedColumn as PrimaryGeneratedColumn6, Column as Column6, OneToMany as OneToMany2 } from "typeorm";
5886
+ import { Entity as Entity7, PrimaryGeneratedColumn as PrimaryGeneratedColumn7, Column as Column7, OneToMany as OneToMany2 } from "typeorm";
5172
5887
  var Category = class {
5173
5888
  id;
5174
5889
  name;
@@ -5182,41 +5897,41 @@ var Category = class {
5182
5897
  blogs;
5183
5898
  };
5184
5899
  __decorateClass([
5185
- PrimaryGeneratedColumn6()
5900
+ PrimaryGeneratedColumn7()
5186
5901
  ], Category.prototype, "id", 2);
5187
5902
  __decorateClass([
5188
- Column6("varchar", { unique: true })
5903
+ Column7("varchar", { unique: true })
5189
5904
  ], Category.prototype, "name", 2);
5190
5905
  __decorateClass([
5191
- Column6({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5906
+ Column7({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5192
5907
  ], Category.prototype, "createdAt", 2);
5193
5908
  __decorateClass([
5194
- Column6({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5909
+ Column7({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5195
5910
  ], Category.prototype, "updatedAt", 2);
5196
5911
  __decorateClass([
5197
- Column6({ type: "timestamp", nullable: true })
5912
+ Column7({ type: "timestamp", nullable: true })
5198
5913
  ], Category.prototype, "deletedAt", 2);
5199
5914
  __decorateClass([
5200
- Column6("boolean", { default: false })
5915
+ Column7("boolean", { default: false })
5201
5916
  ], Category.prototype, "deleted", 2);
5202
5917
  __decorateClass([
5203
- Column6("int", { nullable: true })
5918
+ Column7("int", { nullable: true })
5204
5919
  ], Category.prototype, "createdBy", 2);
5205
5920
  __decorateClass([
5206
- Column6("int", { nullable: true })
5921
+ Column7("int", { nullable: true })
5207
5922
  ], Category.prototype, "updatedBy", 2);
5208
5923
  __decorateClass([
5209
- Column6("int", { nullable: true })
5924
+ Column7("int", { nullable: true })
5210
5925
  ], Category.prototype, "deletedBy", 2);
5211
5926
  __decorateClass([
5212
5927
  OneToMany2("Blog", "category")
5213
5928
  ], Category.prototype, "blogs", 2);
5214
5929
  Category = __decorateClass([
5215
- Entity6("categories")
5930
+ Entity7("categories")
5216
5931
  ], Category);
5217
5932
 
5218
5933
  // src/entities/seo.entity.ts
5219
- import { Entity as Entity7, PrimaryGeneratedColumn as PrimaryGeneratedColumn7, Column as Column7, OneToMany as OneToMany3 } from "typeorm";
5934
+ import { Entity as Entity8, PrimaryGeneratedColumn as PrimaryGeneratedColumn8, Column as Column8, OneToMany as OneToMany3 } from "typeorm";
5220
5935
  var Seo = class {
5221
5936
  id;
5222
5937
  title;
@@ -5236,59 +5951,59 @@ var Seo = class {
5236
5951
  blogs;
5237
5952
  };
5238
5953
  __decorateClass([
5239
- PrimaryGeneratedColumn7()
5954
+ PrimaryGeneratedColumn8()
5240
5955
  ], Seo.prototype, "id", 2);
5241
5956
  __decorateClass([
5242
- Column7("varchar", { nullable: true })
5957
+ Column8("varchar", { nullable: true })
5243
5958
  ], Seo.prototype, "title", 2);
5244
5959
  __decorateClass([
5245
- Column7("varchar", { nullable: true })
5960
+ Column8("varchar", { nullable: true })
5246
5961
  ], Seo.prototype, "description", 2);
5247
5962
  __decorateClass([
5248
- Column7("varchar", { nullable: true })
5963
+ Column8("varchar", { nullable: true })
5249
5964
  ], Seo.prototype, "keywords", 2);
5250
5965
  __decorateClass([
5251
- Column7("varchar", { nullable: true })
5966
+ Column8("varchar", { nullable: true })
5252
5967
  ], Seo.prototype, "ogTitle", 2);
5253
5968
  __decorateClass([
5254
- Column7("varchar", { nullable: true })
5969
+ Column8("varchar", { nullable: true })
5255
5970
  ], Seo.prototype, "ogDescription", 2);
5256
5971
  __decorateClass([
5257
- Column7("varchar", { nullable: true })
5972
+ Column8("varchar", { nullable: true })
5258
5973
  ], Seo.prototype, "ogImage", 2);
5259
5974
  __decorateClass([
5260
- Column7("varchar", { unique: true })
5975
+ Column8("varchar", { unique: true })
5261
5976
  ], Seo.prototype, "slug", 2);
5262
5977
  __decorateClass([
5263
- Column7({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5978
+ Column8({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5264
5979
  ], Seo.prototype, "createdAt", 2);
5265
5980
  __decorateClass([
5266
- Column7({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5981
+ Column8({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5267
5982
  ], Seo.prototype, "updatedAt", 2);
5268
5983
  __decorateClass([
5269
- Column7({ type: "timestamp", nullable: true })
5984
+ Column8({ type: "timestamp", nullable: true })
5270
5985
  ], Seo.prototype, "deletedAt", 2);
5271
5986
  __decorateClass([
5272
- Column7("boolean", { default: false })
5987
+ Column8("boolean", { default: false })
5273
5988
  ], Seo.prototype, "deleted", 2);
5274
5989
  __decorateClass([
5275
- Column7("int", { nullable: true })
5990
+ Column8("int", { nullable: true })
5276
5991
  ], Seo.prototype, "createdBy", 2);
5277
5992
  __decorateClass([
5278
- Column7("int", { nullable: true })
5993
+ Column8("int", { nullable: true })
5279
5994
  ], Seo.prototype, "updatedBy", 2);
5280
5995
  __decorateClass([
5281
- Column7("int", { nullable: true })
5996
+ Column8("int", { nullable: true })
5282
5997
  ], Seo.prototype, "deletedBy", 2);
5283
5998
  __decorateClass([
5284
5999
  OneToMany3(() => Blog, (blog) => blog.seo)
5285
6000
  ], Seo.prototype, "blogs", 2);
5286
6001
  Seo = __decorateClass([
5287
- Entity7("seos")
6002
+ Entity8("seos")
5288
6003
  ], Seo);
5289
6004
 
5290
6005
  // src/entities/comment.entity.ts
5291
- import { Entity as Entity8, PrimaryGeneratedColumn as PrimaryGeneratedColumn8, Column as Column8, ManyToOne as ManyToOne3, JoinColumn as JoinColumn3 } from "typeorm";
6006
+ import { Entity as Entity9, PrimaryGeneratedColumn as PrimaryGeneratedColumn9, Column as Column9, ManyToOne as ManyToOne3, JoinColumn as JoinColumn3 } from "typeorm";
5292
6007
  var Comment = class {
5293
6008
  id;
5294
6009
  content;
@@ -5305,37 +6020,37 @@ var Comment = class {
5305
6020
  blog;
5306
6021
  };
5307
6022
  __decorateClass([
5308
- PrimaryGeneratedColumn8()
6023
+ PrimaryGeneratedColumn9()
5309
6024
  ], Comment.prototype, "id", 2);
5310
6025
  __decorateClass([
5311
- Column8("text")
6026
+ Column9("text")
5312
6027
  ], Comment.prototype, "content", 2);
5313
6028
  __decorateClass([
5314
- Column8("int")
6029
+ Column9("int")
5315
6030
  ], Comment.prototype, "blogId", 2);
5316
6031
  __decorateClass([
5317
- Column8("int")
6032
+ Column9("int")
5318
6033
  ], Comment.prototype, "authorId", 2);
5319
6034
  __decorateClass([
5320
- Column8({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6035
+ Column9({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5321
6036
  ], Comment.prototype, "createdAt", 2);
5322
6037
  __decorateClass([
5323
- Column8({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6038
+ Column9({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5324
6039
  ], Comment.prototype, "updatedAt", 2);
5325
6040
  __decorateClass([
5326
- Column8({ type: "timestamp", nullable: true })
6041
+ Column9({ type: "timestamp", nullable: true })
5327
6042
  ], Comment.prototype, "deletedAt", 2);
5328
6043
  __decorateClass([
5329
- Column8("boolean", { default: false })
6044
+ Column9("boolean", { default: false })
5330
6045
  ], Comment.prototype, "deleted", 2);
5331
6046
  __decorateClass([
5332
- Column8("int", { nullable: true })
6047
+ Column9("int", { nullable: true })
5333
6048
  ], Comment.prototype, "createdBy", 2);
5334
6049
  __decorateClass([
5335
- Column8("int", { nullable: true })
6050
+ Column9("int", { nullable: true })
5336
6051
  ], Comment.prototype, "updatedBy", 2);
5337
6052
  __decorateClass([
5338
- Column8("int", { nullable: true })
6053
+ Column9("int", { nullable: true })
5339
6054
  ], Comment.prototype, "deletedBy", 2);
5340
6055
  __decorateClass([
5341
6056
  ManyToOne3(() => User, { onDelete: "CASCADE" }),
@@ -5346,11 +6061,11 @@ __decorateClass([
5346
6061
  JoinColumn3({ name: "blogId" })
5347
6062
  ], Comment.prototype, "blog", 2);
5348
6063
  Comment = __decorateClass([
5349
- Entity8("comments")
6064
+ Entity9("comments")
5350
6065
  ], Comment);
5351
6066
 
5352
6067
  // src/entities/tag.entity.ts
5353
- import { Entity as Entity9, PrimaryGeneratedColumn as PrimaryGeneratedColumn9, Column as Column9, ManyToMany } from "typeorm";
6068
+ import { Entity as Entity10, PrimaryGeneratedColumn as PrimaryGeneratedColumn10, Column as Column10, ManyToMany } from "typeorm";
5354
6069
  var Tag = class {
5355
6070
  id;
5356
6071
  name;
@@ -5364,37 +6079,37 @@ var Tag = class {
5364
6079
  blogs;
5365
6080
  };
5366
6081
  __decorateClass([
5367
- PrimaryGeneratedColumn9()
6082
+ PrimaryGeneratedColumn10()
5368
6083
  ], Tag.prototype, "id", 2);
5369
6084
  __decorateClass([
5370
- Column9("varchar", { unique: true })
6085
+ Column10("varchar", { unique: true })
5371
6086
  ], Tag.prototype, "name", 2);
5372
6087
  __decorateClass([
5373
- Column9({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6088
+ Column10({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5374
6089
  ], Tag.prototype, "createdAt", 2);
5375
6090
  __decorateClass([
5376
- Column9({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6091
+ Column10({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5377
6092
  ], Tag.prototype, "updatedAt", 2);
5378
6093
  __decorateClass([
5379
- Column9({ type: "timestamp", nullable: true })
6094
+ Column10({ type: "timestamp", nullable: true })
5380
6095
  ], Tag.prototype, "deletedAt", 2);
5381
6096
  __decorateClass([
5382
- Column9("boolean", { default: false })
6097
+ Column10("boolean", { default: false })
5383
6098
  ], Tag.prototype, "deleted", 2);
5384
6099
  __decorateClass([
5385
- Column9("int", { nullable: true })
6100
+ Column10("int", { nullable: true })
5386
6101
  ], Tag.prototype, "createdBy", 2);
5387
6102
  __decorateClass([
5388
- Column9("int", { nullable: true })
6103
+ Column10("int", { nullable: true })
5389
6104
  ], Tag.prototype, "updatedBy", 2);
5390
6105
  __decorateClass([
5391
- Column9("int", { nullable: true })
6106
+ Column10("int", { nullable: true })
5392
6107
  ], Tag.prototype, "deletedBy", 2);
5393
6108
  __decorateClass([
5394
6109
  ManyToMany(() => Blog, (blog) => blog.tags)
5395
6110
  ], Tag.prototype, "blogs", 2);
5396
6111
  Tag = __decorateClass([
5397
- Entity9("tags")
6112
+ Entity10("tags")
5398
6113
  ], Tag);
5399
6114
 
5400
6115
  // src/entities/blog.entity.ts
@@ -5422,52 +6137,52 @@ var Blog = class {
5422
6137
  tags;
5423
6138
  };
5424
6139
  __decorateClass([
5425
- PrimaryGeneratedColumn10()
6140
+ PrimaryGeneratedColumn11()
5426
6141
  ], Blog.prototype, "id", 2);
5427
6142
  __decorateClass([
5428
- Column10("varchar")
6143
+ Column11("varchar")
5429
6144
  ], Blog.prototype, "title", 2);
5430
6145
  __decorateClass([
5431
- Column10("text")
6146
+ Column11("text")
5432
6147
  ], Blog.prototype, "content", 2);
5433
6148
  __decorateClass([
5434
- Column10("varchar", { nullable: true })
6149
+ Column11("varchar", { nullable: true })
5435
6150
  ], Blog.prototype, "coverImage", 2);
5436
6151
  __decorateClass([
5437
- Column10("int")
6152
+ Column11("int")
5438
6153
  ], Blog.prototype, "authorId", 2);
5439
6154
  __decorateClass([
5440
- Column10("int", { nullable: true })
6155
+ Column11("int", { nullable: true })
5441
6156
  ], Blog.prototype, "categoryId", 2);
5442
6157
  __decorateClass([
5443
- Column10("int", { nullable: true })
6158
+ Column11("int", { nullable: true })
5444
6159
  ], Blog.prototype, "seoId", 2);
5445
6160
  __decorateClass([
5446
- Column10("boolean", { default: false })
6161
+ Column11("boolean", { default: false })
5447
6162
  ], Blog.prototype, "published", 2);
5448
6163
  __decorateClass([
5449
- Column10({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6164
+ Column11({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5450
6165
  ], Blog.prototype, "createdAt", 2);
5451
6166
  __decorateClass([
5452
- Column10({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6167
+ Column11({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5453
6168
  ], Blog.prototype, "updatedAt", 2);
5454
6169
  __decorateClass([
5455
- Column10({ type: "timestamp", nullable: true })
6170
+ Column11({ type: "timestamp", nullable: true })
5456
6171
  ], Blog.prototype, "deletedAt", 2);
5457
6172
  __decorateClass([
5458
- Column10("boolean", { default: false })
6173
+ Column11("boolean", { default: false })
5459
6174
  ], Blog.prototype, "deleted", 2);
5460
6175
  __decorateClass([
5461
- Column10("int", { nullable: true })
6176
+ Column11("int", { nullable: true })
5462
6177
  ], Blog.prototype, "createdBy", 2);
5463
6178
  __decorateClass([
5464
- Column10("int", { nullable: true })
6179
+ Column11("int", { nullable: true })
5465
6180
  ], Blog.prototype, "updatedBy", 2);
5466
6181
  __decorateClass([
5467
- Column10("int", { nullable: true })
6182
+ Column11("int", { nullable: true })
5468
6183
  ], Blog.prototype, "deletedBy", 2);
5469
6184
  __decorateClass([
5470
- Column10("varchar", { unique: true })
6185
+ Column11("varchar", { unique: true })
5471
6186
  ], Blog.prototype, "slug", 2);
5472
6187
  __decorateClass([
5473
6188
  ManyToOne4(() => User, { onDelete: "CASCADE" }),
@@ -5493,20 +6208,20 @@ __decorateClass([
5493
6208
  })
5494
6209
  ], Blog.prototype, "tags", 2);
5495
6210
  Blog = __decorateClass([
5496
- Entity10("blogs")
6211
+ Entity11("blogs")
5497
6212
  ], Blog);
5498
6213
 
5499
6214
  // src/entities/contact.entity.ts
5500
- import { Entity as Entity19, PrimaryGeneratedColumn as PrimaryGeneratedColumn19, Column as Column19, OneToMany as OneToMany8, ManyToOne as ManyToOne12, JoinColumn as JoinColumn12 } from "typeorm";
6215
+ import { Entity as Entity20, PrimaryGeneratedColumn as PrimaryGeneratedColumn20, Column as Column20, OneToMany as OneToMany8, ManyToOne as ManyToOne12, JoinColumn as JoinColumn12 } from "typeorm";
5501
6216
 
5502
6217
  // src/entities/form-submission.entity.ts
5503
- import { Entity as Entity13, PrimaryGeneratedColumn as PrimaryGeneratedColumn13, Column as Column13, ManyToOne as ManyToOne6, JoinColumn as JoinColumn6 } from "typeorm";
6218
+ import { Entity as Entity14, PrimaryGeneratedColumn as PrimaryGeneratedColumn14, Column as Column14, ManyToOne as ManyToOne6, JoinColumn as JoinColumn6 } from "typeorm";
5504
6219
 
5505
6220
  // src/entities/form.entity.ts
5506
- import { Entity as Entity12, PrimaryGeneratedColumn as PrimaryGeneratedColumn12, Column as Column12, OneToMany as OneToMany5 } from "typeorm";
6221
+ import { Entity as Entity13, PrimaryGeneratedColumn as PrimaryGeneratedColumn13, Column as Column13, OneToMany as OneToMany5 } from "typeorm";
5507
6222
 
5508
6223
  // src/entities/form-field.entity.ts
5509
- import { Entity as Entity11, PrimaryGeneratedColumn as PrimaryGeneratedColumn11, Column as Column11, ManyToOne as ManyToOne5, JoinColumn as JoinColumn5 } from "typeorm";
6224
+ import { Entity as Entity12, PrimaryGeneratedColumn as PrimaryGeneratedColumn12, Column as Column12, ManyToOne as ManyToOne5, JoinColumn as JoinColumn5 } from "typeorm";
5510
6225
  var FormField = class {
5511
6226
  id;
5512
6227
  formId;
@@ -5529,65 +6244,65 @@ var FormField = class {
5529
6244
  form;
5530
6245
  };
5531
6246
  __decorateClass([
5532
- PrimaryGeneratedColumn11()
6247
+ PrimaryGeneratedColumn12()
5533
6248
  ], FormField.prototype, "id", 2);
5534
6249
  __decorateClass([
5535
- Column11("int")
6250
+ Column12("int")
5536
6251
  ], FormField.prototype, "formId", 2);
5537
6252
  __decorateClass([
5538
- Column11("varchar")
6253
+ Column12("varchar")
5539
6254
  ], FormField.prototype, "label", 2);
5540
6255
  __decorateClass([
5541
- Column11("varchar")
6256
+ Column12("varchar")
5542
6257
  ], FormField.prototype, "type", 2);
5543
6258
  __decorateClass([
5544
- Column11("varchar", { nullable: true })
6259
+ Column12("varchar", { nullable: true })
5545
6260
  ], FormField.prototype, "placeholder", 2);
5546
6261
  __decorateClass([
5547
- Column11("varchar", { nullable: true })
6262
+ Column12("varchar", { nullable: true })
5548
6263
  ], FormField.prototype, "options", 2);
5549
6264
  __decorateClass([
5550
- Column11("boolean", { default: false })
6265
+ Column12("boolean", { default: false })
5551
6266
  ], FormField.prototype, "required", 2);
5552
6267
  __decorateClass([
5553
- Column11("varchar", { nullable: true })
6268
+ Column12("varchar", { nullable: true })
5554
6269
  ], FormField.prototype, "validation", 2);
5555
6270
  __decorateClass([
5556
- Column11("int")
6271
+ Column12("int")
5557
6272
  ], FormField.prototype, "order", 2);
5558
6273
  __decorateClass([
5559
- Column11("int", { default: 1 })
6274
+ Column12("int", { default: 1 })
5560
6275
  ], FormField.prototype, "groupId", 2);
5561
6276
  __decorateClass([
5562
- Column11("int", { default: 12 })
6277
+ Column12("int", { default: 12 })
5563
6278
  ], FormField.prototype, "columnWidth", 2);
5564
6279
  __decorateClass([
5565
- Column11({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6280
+ Column12({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5566
6281
  ], FormField.prototype, "createdAt", 2);
5567
6282
  __decorateClass([
5568
- Column11({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6283
+ Column12({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5569
6284
  ], FormField.prototype, "updatedAt", 2);
5570
6285
  __decorateClass([
5571
- Column11({ type: "timestamp", nullable: true })
6286
+ Column12({ type: "timestamp", nullable: true })
5572
6287
  ], FormField.prototype, "deletedAt", 2);
5573
6288
  __decorateClass([
5574
- Column11("boolean", { default: false })
6289
+ Column12("boolean", { default: false })
5575
6290
  ], FormField.prototype, "deleted", 2);
5576
6291
  __decorateClass([
5577
- Column11("int", { nullable: true })
6292
+ Column12("int", { nullable: true })
5578
6293
  ], FormField.prototype, "createdBy", 2);
5579
6294
  __decorateClass([
5580
- Column11("int", { nullable: true })
6295
+ Column12("int", { nullable: true })
5581
6296
  ], FormField.prototype, "updatedBy", 2);
5582
6297
  __decorateClass([
5583
- Column11("int", { nullable: true })
6298
+ Column12("int", { nullable: true })
5584
6299
  ], FormField.prototype, "deletedBy", 2);
5585
6300
  __decorateClass([
5586
6301
  ManyToOne5(() => Form, (f) => f.fields, { onDelete: "CASCADE" }),
5587
6302
  JoinColumn5({ name: "formId" })
5588
6303
  ], FormField.prototype, "form", 2);
5589
6304
  FormField = __decorateClass([
5590
- Entity11("form_fields")
6305
+ Entity12("form_fields")
5591
6306
  ], FormField);
5592
6307
 
5593
6308
  // src/entities/form.entity.ts
@@ -5609,43 +6324,43 @@ var Form = class {
5609
6324
  submissions;
5610
6325
  };
5611
6326
  __decorateClass([
5612
- PrimaryGeneratedColumn12()
6327
+ PrimaryGeneratedColumn13()
5613
6328
  ], Form.prototype, "id", 2);
5614
6329
  __decorateClass([
5615
- Column12("varchar")
6330
+ Column13("varchar")
5616
6331
  ], Form.prototype, "name", 2);
5617
6332
  __decorateClass([
5618
- Column12("text", { nullable: true })
6333
+ Column13("text", { nullable: true })
5619
6334
  ], Form.prototype, "description", 2);
5620
6335
  __decorateClass([
5621
- Column12("varchar", { nullable: true })
6336
+ Column13("varchar", { nullable: true })
5622
6337
  ], Form.prototype, "campaign", 2);
5623
6338
  __decorateClass([
5624
- Column12("varchar", { unique: true })
6339
+ Column13("varchar", { unique: true })
5625
6340
  ], Form.prototype, "slug", 2);
5626
6341
  __decorateClass([
5627
- Column12("boolean", { default: false })
6342
+ Column13("boolean", { default: false })
5628
6343
  ], Form.prototype, "published", 2);
5629
6344
  __decorateClass([
5630
- Column12({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6345
+ Column13({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5631
6346
  ], Form.prototype, "createdAt", 2);
5632
6347
  __decorateClass([
5633
- Column12({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6348
+ Column13({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5634
6349
  ], Form.prototype, "updatedAt", 2);
5635
6350
  __decorateClass([
5636
- Column12({ type: "timestamp", nullable: true })
6351
+ Column13({ type: "timestamp", nullable: true })
5637
6352
  ], Form.prototype, "deletedAt", 2);
5638
6353
  __decorateClass([
5639
- Column12("boolean", { default: false })
6354
+ Column13("boolean", { default: false })
5640
6355
  ], Form.prototype, "deleted", 2);
5641
6356
  __decorateClass([
5642
- Column12("int", { nullable: true })
6357
+ Column13("int", { nullable: true })
5643
6358
  ], Form.prototype, "createdBy", 2);
5644
6359
  __decorateClass([
5645
- Column12("int", { nullable: true })
6360
+ Column13("int", { nullable: true })
5646
6361
  ], Form.prototype, "updatedBy", 2);
5647
6362
  __decorateClass([
5648
- Column12("int", { nullable: true })
6363
+ Column13("int", { nullable: true })
5649
6364
  ], Form.prototype, "deletedBy", 2);
5650
6365
  __decorateClass([
5651
6366
  OneToMany5(() => FormField, (f) => f.form)
@@ -5654,7 +6369,7 @@ __decorateClass([
5654
6369
  OneToMany5(() => FormSubmission, (s) => s.form)
5655
6370
  ], Form.prototype, "submissions", 2);
5656
6371
  Form = __decorateClass([
5657
- Entity12("forms")
6372
+ Entity13("forms")
5658
6373
  ], Form);
5659
6374
 
5660
6375
  // src/entities/form-submission.entity.ts
@@ -5671,28 +6386,28 @@ var FormSubmission = class {
5671
6386
  contact;
5672
6387
  };
5673
6388
  __decorateClass([
5674
- PrimaryGeneratedColumn13()
6389
+ PrimaryGeneratedColumn14()
5675
6390
  ], FormSubmission.prototype, "id", 2);
5676
6391
  __decorateClass([
5677
- Column13("int")
6392
+ Column14("int")
5678
6393
  ], FormSubmission.prototype, "formId", 2);
5679
6394
  __decorateClass([
5680
- Column13("int", { nullable: true })
6395
+ Column14("int", { nullable: true })
5681
6396
  ], FormSubmission.prototype, "contactId", 2);
5682
6397
  __decorateClass([
5683
- Column13("jsonb")
6398
+ Column14("jsonb")
5684
6399
  ], FormSubmission.prototype, "data", 2);
5685
6400
  __decorateClass([
5686
- Column13("varchar", { nullable: true })
6401
+ Column14("varchar", { nullable: true })
5687
6402
  ], FormSubmission.prototype, "ipAddress", 2);
5688
6403
  __decorateClass([
5689
- Column13("varchar", { nullable: true })
6404
+ Column14("varchar", { nullable: true })
5690
6405
  ], FormSubmission.prototype, "userAgent", 2);
5691
6406
  __decorateClass([
5692
- Column13({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6407
+ Column14({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5693
6408
  ], FormSubmission.prototype, "createdAt", 2);
5694
6409
  __decorateClass([
5695
- Column13({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6410
+ Column14({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5696
6411
  ], FormSubmission.prototype, "updatedAt", 2);
5697
6412
  __decorateClass([
5698
6413
  ManyToOne6(() => Form, (f) => f.submissions, { onDelete: "CASCADE" }),
@@ -5703,11 +6418,11 @@ __decorateClass([
5703
6418
  JoinColumn6({ name: "contactId" })
5704
6419
  ], FormSubmission.prototype, "contact", 2);
5705
6420
  FormSubmission = __decorateClass([
5706
- Entity13("form_submissions")
6421
+ Entity14("form_submissions")
5707
6422
  ], FormSubmission);
5708
6423
 
5709
6424
  // src/entities/address.entity.ts
5710
- import { Entity as Entity14, PrimaryGeneratedColumn as PrimaryGeneratedColumn14, Column as Column14, ManyToOne as ManyToOne7, JoinColumn as JoinColumn7 } from "typeorm";
6425
+ import { Entity as Entity15, PrimaryGeneratedColumn as PrimaryGeneratedColumn15, Column as Column15, ManyToOne as ManyToOne7, JoinColumn as JoinColumn7 } from "typeorm";
5711
6426
  var Address = class {
5712
6427
  id;
5713
6428
  contactId;
@@ -5723,48 +6438,48 @@ var Address = class {
5723
6438
  contact;
5724
6439
  };
5725
6440
  __decorateClass([
5726
- PrimaryGeneratedColumn14()
6441
+ PrimaryGeneratedColumn15()
5727
6442
  ], Address.prototype, "id", 2);
5728
6443
  __decorateClass([
5729
- Column14("int")
6444
+ Column15("int")
5730
6445
  ], Address.prototype, "contactId", 2);
5731
6446
  __decorateClass([
5732
- Column14("varchar", { nullable: true })
6447
+ Column15("varchar", { nullable: true })
5733
6448
  ], Address.prototype, "tag", 2);
5734
6449
  __decorateClass([
5735
- Column14("varchar", { nullable: true })
6450
+ Column15("varchar", { nullable: true })
5736
6451
  ], Address.prototype, "line1", 2);
5737
6452
  __decorateClass([
5738
- Column14("varchar", { nullable: true })
6453
+ Column15("varchar", { nullable: true })
5739
6454
  ], Address.prototype, "line2", 2);
5740
6455
  __decorateClass([
5741
- Column14("varchar", { nullable: true })
6456
+ Column15("varchar", { nullable: true })
5742
6457
  ], Address.prototype, "city", 2);
5743
6458
  __decorateClass([
5744
- Column14("varchar", { nullable: true })
6459
+ Column15("varchar", { nullable: true })
5745
6460
  ], Address.prototype, "state", 2);
5746
6461
  __decorateClass([
5747
- Column14("varchar", { nullable: true })
6462
+ Column15("varchar", { nullable: true })
5748
6463
  ], Address.prototype, "postalCode", 2);
5749
6464
  __decorateClass([
5750
- Column14("varchar", { nullable: true })
6465
+ Column15("varchar", { nullable: true })
5751
6466
  ], Address.prototype, "country", 2);
5752
6467
  __decorateClass([
5753
- Column14({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6468
+ Column15({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5754
6469
  ], Address.prototype, "createdAt", 2);
5755
6470
  __decorateClass([
5756
- Column14({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6471
+ Column15({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5757
6472
  ], Address.prototype, "updatedAt", 2);
5758
6473
  __decorateClass([
5759
6474
  ManyToOne7(() => Contact, (c) => c.addresses, { onDelete: "CASCADE" }),
5760
6475
  JoinColumn7({ name: "contactId" })
5761
6476
  ], Address.prototype, "contact", 2);
5762
6477
  Address = __decorateClass([
5763
- Entity14("addresses")
6478
+ Entity15("addresses")
5764
6479
  ], Address);
5765
6480
 
5766
6481
  // src/entities/order.entity.ts
5767
- import { Entity as Entity15, PrimaryGeneratedColumn as PrimaryGeneratedColumn15, Column as Column15, ManyToOne as ManyToOne8, OneToMany as OneToMany6, JoinColumn as JoinColumn8 } from "typeorm";
6482
+ import { Entity as Entity16, PrimaryGeneratedColumn as PrimaryGeneratedColumn16, Column as Column16, ManyToOne as ManyToOne8, OneToMany as OneToMany6, JoinColumn as JoinColumn8 } from "typeorm";
5768
6483
  var Order = class {
5769
6484
  id;
5770
6485
  orderNumber;
@@ -5796,67 +6511,67 @@ var Order = class {
5796
6511
  payments;
5797
6512
  };
5798
6513
  __decorateClass([
5799
- PrimaryGeneratedColumn15()
6514
+ PrimaryGeneratedColumn16()
5800
6515
  ], Order.prototype, "id", 2);
5801
6516
  __decorateClass([
5802
- Column15("varchar", { unique: true })
6517
+ Column16("varchar", { unique: true })
5803
6518
  ], Order.prototype, "orderNumber", 2);
5804
6519
  __decorateClass([
5805
- Column15("varchar", { default: "sale" })
6520
+ Column16("varchar", { default: "sale" })
5806
6521
  ], Order.prototype, "orderKind", 2);
5807
6522
  __decorateClass([
5808
- Column15("int", { nullable: true })
6523
+ Column16("int", { nullable: true })
5809
6524
  ], Order.prototype, "parentOrderId", 2);
5810
6525
  __decorateClass([
5811
- Column15("int")
6526
+ Column16("int")
5812
6527
  ], Order.prototype, "contactId", 2);
5813
6528
  __decorateClass([
5814
- Column15("int", { nullable: true })
6529
+ Column16("int", { nullable: true })
5815
6530
  ], Order.prototype, "billingAddressId", 2);
5816
6531
  __decorateClass([
5817
- Column15("int", { nullable: true })
6532
+ Column16("int", { nullable: true })
5818
6533
  ], Order.prototype, "shippingAddressId", 2);
5819
6534
  __decorateClass([
5820
- Column15("varchar", { default: "pending" })
6535
+ Column16("varchar", { default: "pending" })
5821
6536
  ], Order.prototype, "status", 2);
5822
6537
  __decorateClass([
5823
- Column15("decimal", { precision: 12, scale: 2, default: 0 })
6538
+ Column16("decimal", { precision: 12, scale: 2, default: 0 })
5824
6539
  ], Order.prototype, "subtotal", 2);
5825
6540
  __decorateClass([
5826
- Column15("decimal", { precision: 12, scale: 2, default: 0 })
6541
+ Column16("decimal", { precision: 12, scale: 2, default: 0 })
5827
6542
  ], Order.prototype, "tax", 2);
5828
6543
  __decorateClass([
5829
- Column15("decimal", { precision: 12, scale: 2, default: 0 })
6544
+ Column16("decimal", { precision: 12, scale: 2, default: 0 })
5830
6545
  ], Order.prototype, "discount", 2);
5831
6546
  __decorateClass([
5832
- Column15("decimal", { precision: 12, scale: 2, default: 0 })
6547
+ Column16("decimal", { precision: 12, scale: 2, default: 0 })
5833
6548
  ], Order.prototype, "total", 2);
5834
6549
  __decorateClass([
5835
- Column15("varchar", { default: "INR" })
6550
+ Column16("varchar", { default: "INR" })
5836
6551
  ], Order.prototype, "currency", 2);
5837
6552
  __decorateClass([
5838
- Column15("jsonb", { nullable: true })
6553
+ Column16("jsonb", { nullable: true })
5839
6554
  ], Order.prototype, "metadata", 2);
5840
6555
  __decorateClass([
5841
- Column15({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6556
+ Column16({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5842
6557
  ], Order.prototype, "createdAt", 2);
5843
6558
  __decorateClass([
5844
- Column15({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6559
+ Column16({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5845
6560
  ], Order.prototype, "updatedAt", 2);
5846
6561
  __decorateClass([
5847
- Column15({ type: "timestamp", nullable: true })
6562
+ Column16({ type: "timestamp", nullable: true })
5848
6563
  ], Order.prototype, "deletedAt", 2);
5849
6564
  __decorateClass([
5850
- Column15("boolean", { default: false })
6565
+ Column16("boolean", { default: false })
5851
6566
  ], Order.prototype, "deleted", 2);
5852
6567
  __decorateClass([
5853
- Column15("int", { nullable: true })
6568
+ Column16("int", { nullable: true })
5854
6569
  ], Order.prototype, "createdBy", 2);
5855
6570
  __decorateClass([
5856
- Column15("int", { nullable: true })
6571
+ Column16("int", { nullable: true })
5857
6572
  ], Order.prototype, "updatedBy", 2);
5858
6573
  __decorateClass([
5859
- Column15("int", { nullable: true })
6574
+ Column16("int", { nullable: true })
5860
6575
  ], Order.prototype, "deletedBy", 2);
5861
6576
  __decorateClass([
5862
6577
  ManyToOne8(() => Order, (o) => o.children, { nullable: true, onDelete: "SET NULL" }),
@@ -5884,11 +6599,11 @@ __decorateClass([
5884
6599
  OneToMany6("Payment", "order")
5885
6600
  ], Order.prototype, "payments", 2);
5886
6601
  Order = __decorateClass([
5887
- Entity15("orders")
6602
+ Entity16("orders")
5888
6603
  ], Order);
5889
6604
 
5890
6605
  // src/entities/payment.entity.ts
5891
- import { Entity as Entity16, PrimaryGeneratedColumn as PrimaryGeneratedColumn16, Column as Column16, ManyToOne as ManyToOne9, JoinColumn as JoinColumn9 } from "typeorm";
6606
+ import { Entity as Entity17, PrimaryGeneratedColumn as PrimaryGeneratedColumn17, Column as Column17, ManyToOne as ManyToOne9, JoinColumn as JoinColumn9 } from "typeorm";
5892
6607
  var Payment = class {
5893
6608
  id;
5894
6609
  orderId;
@@ -5911,55 +6626,55 @@ var Payment = class {
5911
6626
  contact;
5912
6627
  };
5913
6628
  __decorateClass([
5914
- PrimaryGeneratedColumn16()
6629
+ PrimaryGeneratedColumn17()
5915
6630
  ], Payment.prototype, "id", 2);
5916
6631
  __decorateClass([
5917
- Column16("int")
6632
+ Column17("int")
5918
6633
  ], Payment.prototype, "orderId", 2);
5919
6634
  __decorateClass([
5920
- Column16("int", { nullable: true })
6635
+ Column17("int", { nullable: true })
5921
6636
  ], Payment.prototype, "contactId", 2);
5922
6637
  __decorateClass([
5923
- Column16("decimal", { precision: 12, scale: 2 })
6638
+ Column17("decimal", { precision: 12, scale: 2 })
5924
6639
  ], Payment.prototype, "amount", 2);
5925
6640
  __decorateClass([
5926
- Column16("varchar", { default: "INR" })
6641
+ Column17("varchar", { default: "INR" })
5927
6642
  ], Payment.prototype, "currency", 2);
5928
6643
  __decorateClass([
5929
- Column16("varchar", { default: "pending" })
6644
+ Column17("varchar", { default: "pending" })
5930
6645
  ], Payment.prototype, "status", 2);
5931
6646
  __decorateClass([
5932
- Column16("varchar", { nullable: true })
6647
+ Column17("varchar", { nullable: true })
5933
6648
  ], Payment.prototype, "method", 2);
5934
6649
  __decorateClass([
5935
- Column16("varchar", { nullable: true })
6650
+ Column17("varchar", { nullable: true })
5936
6651
  ], Payment.prototype, "externalReference", 2);
5937
6652
  __decorateClass([
5938
- Column16("jsonb", { nullable: true })
6653
+ Column17("jsonb", { nullable: true })
5939
6654
  ], Payment.prototype, "metadata", 2);
5940
6655
  __decorateClass([
5941
- Column16({ type: "timestamp", nullable: true })
6656
+ Column17({ type: "timestamp", nullable: true })
5942
6657
  ], Payment.prototype, "paidAt", 2);
5943
6658
  __decorateClass([
5944
- Column16({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6659
+ Column17({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5945
6660
  ], Payment.prototype, "createdAt", 2);
5946
6661
  __decorateClass([
5947
- Column16({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6662
+ Column17({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
5948
6663
  ], Payment.prototype, "updatedAt", 2);
5949
6664
  __decorateClass([
5950
- Column16({ type: "timestamp", nullable: true })
6665
+ Column17({ type: "timestamp", nullable: true })
5951
6666
  ], Payment.prototype, "deletedAt", 2);
5952
6667
  __decorateClass([
5953
- Column16("boolean", { default: false })
6668
+ Column17("boolean", { default: false })
5954
6669
  ], Payment.prototype, "deleted", 2);
5955
6670
  __decorateClass([
5956
- Column16("int", { nullable: true })
6671
+ Column17("int", { nullable: true })
5957
6672
  ], Payment.prototype, "createdBy", 2);
5958
6673
  __decorateClass([
5959
- Column16("int", { nullable: true })
6674
+ Column17("int", { nullable: true })
5960
6675
  ], Payment.prototype, "updatedBy", 2);
5961
6676
  __decorateClass([
5962
- Column16("int", { nullable: true })
6677
+ Column17("int", { nullable: true })
5963
6678
  ], Payment.prototype, "deletedBy", 2);
5964
6679
  __decorateClass([
5965
6680
  ManyToOne9(() => Order, (o) => o.payments, { onDelete: "CASCADE" }),
@@ -5970,14 +6685,14 @@ __decorateClass([
5970
6685
  JoinColumn9({ name: "contactId" })
5971
6686
  ], Payment.prototype, "contact", 2);
5972
6687
  Payment = __decorateClass([
5973
- Entity16("payments")
6688
+ Entity17("payments")
5974
6689
  ], Payment);
5975
6690
 
5976
6691
  // src/entities/chat-conversation.entity.ts
5977
- import { Entity as Entity18, PrimaryGeneratedColumn as PrimaryGeneratedColumn18, Column as Column18, ManyToOne as ManyToOne11, OneToMany as OneToMany7, JoinColumn as JoinColumn11 } from "typeorm";
6692
+ import { Entity as Entity19, PrimaryGeneratedColumn as PrimaryGeneratedColumn19, Column as Column19, ManyToOne as ManyToOne11, OneToMany as OneToMany7, JoinColumn as JoinColumn11 } from "typeorm";
5978
6693
 
5979
6694
  // src/entities/chat-message.entity.ts
5980
- import { Entity as Entity17, PrimaryGeneratedColumn as PrimaryGeneratedColumn17, Column as Column17, ManyToOne as ManyToOne10, JoinColumn as JoinColumn10 } from "typeorm";
6695
+ import { Entity as Entity18, PrimaryGeneratedColumn as PrimaryGeneratedColumn18, Column as Column18, ManyToOne as ManyToOne10, JoinColumn as JoinColumn10 } from "typeorm";
5981
6696
  var ChatMessage = class {
5982
6697
  id;
5983
6698
  conversationId;
@@ -5987,26 +6702,26 @@ var ChatMessage = class {
5987
6702
  conversation;
5988
6703
  };
5989
6704
  __decorateClass([
5990
- PrimaryGeneratedColumn17()
6705
+ PrimaryGeneratedColumn18()
5991
6706
  ], ChatMessage.prototype, "id", 2);
5992
6707
  __decorateClass([
5993
- Column17("int")
6708
+ Column18("int")
5994
6709
  ], ChatMessage.prototype, "conversationId", 2);
5995
6710
  __decorateClass([
5996
- Column17("varchar")
6711
+ Column18("varchar")
5997
6712
  ], ChatMessage.prototype, "role", 2);
5998
6713
  __decorateClass([
5999
- Column17("text")
6714
+ Column18("text")
6000
6715
  ], ChatMessage.prototype, "content", 2);
6001
6716
  __decorateClass([
6002
- Column17({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6717
+ Column18({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6003
6718
  ], ChatMessage.prototype, "createdAt", 2);
6004
6719
  __decorateClass([
6005
6720
  ManyToOne10(() => ChatConversation, (c) => c.messages, { onDelete: "CASCADE" }),
6006
6721
  JoinColumn10({ name: "conversationId" })
6007
6722
  ], ChatMessage.prototype, "conversation", 2);
6008
6723
  ChatMessage = __decorateClass([
6009
- Entity17("chat_messages")
6724
+ Entity18("chat_messages")
6010
6725
  ], ChatMessage);
6011
6726
 
6012
6727
  // src/entities/chat-conversation.entity.ts
@@ -6019,16 +6734,16 @@ var ChatConversation = class {
6019
6734
  messages;
6020
6735
  };
6021
6736
  __decorateClass([
6022
- PrimaryGeneratedColumn18()
6737
+ PrimaryGeneratedColumn19()
6023
6738
  ], ChatConversation.prototype, "id", 2);
6024
6739
  __decorateClass([
6025
- Column18("int")
6740
+ Column19("int")
6026
6741
  ], ChatConversation.prototype, "contactId", 2);
6027
6742
  __decorateClass([
6028
- Column18({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6743
+ Column19({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6029
6744
  ], ChatConversation.prototype, "createdAt", 2);
6030
6745
  __decorateClass([
6031
- Column18({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6746
+ Column19({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6032
6747
  ], ChatConversation.prototype, "updatedAt", 2);
6033
6748
  __decorateClass([
6034
6749
  ManyToOne11(() => Contact, (c) => c.chatConversations, { onDelete: "CASCADE" }),
@@ -6038,7 +6753,7 @@ __decorateClass([
6038
6753
  OneToMany7(() => ChatMessage, (m) => m.conversation)
6039
6754
  ], ChatConversation.prototype, "messages", 2);
6040
6755
  ChatConversation = __decorateClass([
6041
- Entity18("chat_conversations")
6756
+ Entity19("chat_conversations")
6042
6757
  ], ChatConversation);
6043
6758
 
6044
6759
  // src/entities/contact.entity.ts
@@ -6067,52 +6782,52 @@ var Contact = class {
6067
6782
  chatConversations;
6068
6783
  };
6069
6784
  __decorateClass([
6070
- PrimaryGeneratedColumn19()
6785
+ PrimaryGeneratedColumn20()
6071
6786
  ], Contact.prototype, "id", 2);
6072
6787
  __decorateClass([
6073
- Column19("varchar")
6788
+ Column20("varchar")
6074
6789
  ], Contact.prototype, "name", 2);
6075
6790
  __decorateClass([
6076
- Column19("varchar", { unique: true })
6791
+ Column20("varchar", { unique: true })
6077
6792
  ], Contact.prototype, "email", 2);
6078
6793
  __decorateClass([
6079
- Column19("varchar", { nullable: true })
6794
+ Column20("varchar", { nullable: true })
6080
6795
  ], Contact.prototype, "phone", 2);
6081
6796
  __decorateClass([
6082
- Column19("varchar", { nullable: true })
6797
+ Column20("varchar", { nullable: true })
6083
6798
  ], Contact.prototype, "type", 2);
6084
6799
  __decorateClass([
6085
- Column19("varchar", { nullable: true })
6800
+ Column20("varchar", { nullable: true })
6086
6801
  ], Contact.prototype, "company", 2);
6087
6802
  __decorateClass([
6088
- Column19("varchar", { nullable: true })
6803
+ Column20("varchar", { nullable: true })
6089
6804
  ], Contact.prototype, "taxId", 2);
6090
6805
  __decorateClass([
6091
- Column19("text", { nullable: true })
6806
+ Column20("text", { nullable: true })
6092
6807
  ], Contact.prototype, "notes", 2);
6093
6808
  __decorateClass([
6094
- Column19({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6809
+ Column20({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6095
6810
  ], Contact.prototype, "createdAt", 2);
6096
6811
  __decorateClass([
6097
- Column19({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6812
+ Column20({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6098
6813
  ], Contact.prototype, "updatedAt", 2);
6099
6814
  __decorateClass([
6100
- Column19({ type: "timestamp", nullable: true })
6815
+ Column20({ type: "timestamp", nullable: true })
6101
6816
  ], Contact.prototype, "deletedAt", 2);
6102
6817
  __decorateClass([
6103
- Column19("boolean", { default: false })
6818
+ Column20("boolean", { default: false })
6104
6819
  ], Contact.prototype, "deleted", 2);
6105
6820
  __decorateClass([
6106
- Column19("int", { nullable: true })
6821
+ Column20("int", { nullable: true })
6107
6822
  ], Contact.prototype, "createdBy", 2);
6108
6823
  __decorateClass([
6109
- Column19("int", { nullable: true })
6824
+ Column20("int", { nullable: true })
6110
6825
  ], Contact.prototype, "updatedBy", 2);
6111
6826
  __decorateClass([
6112
- Column19("int", { nullable: true })
6827
+ Column20("int", { nullable: true })
6113
6828
  ], Contact.prototype, "deletedBy", 2);
6114
6829
  __decorateClass([
6115
- Column19("int", { nullable: true })
6830
+ Column20("int", { nullable: true })
6116
6831
  ], Contact.prototype, "userId", 2);
6117
6832
  __decorateClass([
6118
6833
  ManyToOne12(() => User, { onDelete: "SET NULL" }),
@@ -6134,11 +6849,11 @@ __decorateClass([
6134
6849
  OneToMany8(() => ChatConversation, (c) => c.contact)
6135
6850
  ], Contact.prototype, "chatConversations", 2);
6136
6851
  Contact = __decorateClass([
6137
- Entity19("contacts")
6852
+ Entity20("contacts")
6138
6853
  ], Contact);
6139
6854
 
6140
6855
  // src/entities/config.entity.ts
6141
- import { Entity as Entity20, PrimaryGeneratedColumn as PrimaryGeneratedColumn20, Column as Column20, Unique } from "typeorm";
6856
+ import { Entity as Entity21, PrimaryGeneratedColumn as PrimaryGeneratedColumn21, Column as Column21, Unique } from "typeorm";
6142
6857
  var Config = class {
6143
6858
  id;
6144
6859
  settings;
@@ -6155,51 +6870,51 @@ var Config = class {
6155
6870
  deletedBy;
6156
6871
  };
6157
6872
  __decorateClass([
6158
- PrimaryGeneratedColumn20()
6873
+ PrimaryGeneratedColumn21()
6159
6874
  ], Config.prototype, "id", 2);
6160
6875
  __decorateClass([
6161
- Column20("varchar")
6876
+ Column21("varchar")
6162
6877
  ], Config.prototype, "settings", 2);
6163
6878
  __decorateClass([
6164
- Column20("varchar")
6879
+ Column21("varchar")
6165
6880
  ], Config.prototype, "key", 2);
6166
6881
  __decorateClass([
6167
- Column20("varchar")
6882
+ Column21("varchar")
6168
6883
  ], Config.prototype, "value", 2);
6169
6884
  __decorateClass([
6170
- Column20("varchar", { default: "private" })
6885
+ Column21("varchar", { default: "private" })
6171
6886
  ], Config.prototype, "type", 2);
6172
6887
  __decorateClass([
6173
- Column20("boolean", { default: false })
6888
+ Column21("boolean", { default: false })
6174
6889
  ], Config.prototype, "encrypted", 2);
6175
6890
  __decorateClass([
6176
- Column20({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6891
+ Column21({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6177
6892
  ], Config.prototype, "createdAt", 2);
6178
6893
  __decorateClass([
6179
- Column20({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6894
+ Column21({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6180
6895
  ], Config.prototype, "updatedAt", 2);
6181
6896
  __decorateClass([
6182
- Column20({ type: "timestamp", nullable: true })
6897
+ Column21({ type: "timestamp", nullable: true })
6183
6898
  ], Config.prototype, "deletedAt", 2);
6184
6899
  __decorateClass([
6185
- Column20("boolean", { default: false })
6900
+ Column21("boolean", { default: false })
6186
6901
  ], Config.prototype, "deleted", 2);
6187
6902
  __decorateClass([
6188
- Column20("int", { nullable: true })
6903
+ Column21("int", { nullable: true })
6189
6904
  ], Config.prototype, "createdBy", 2);
6190
6905
  __decorateClass([
6191
- Column20("int", { nullable: true })
6906
+ Column21("int", { nullable: true })
6192
6907
  ], Config.prototype, "updatedBy", 2);
6193
6908
  __decorateClass([
6194
- Column20("int", { nullable: true })
6909
+ Column21("int", { nullable: true })
6195
6910
  ], Config.prototype, "deletedBy", 2);
6196
6911
  Config = __decorateClass([
6197
- Entity20("configs"),
6912
+ Entity21("configs"),
6198
6913
  Unique(["settings", "key"])
6199
6914
  ], Config);
6200
6915
 
6201
6916
  // src/entities/message-template.entity.ts
6202
- import { Entity as Entity21, PrimaryGeneratedColumn as PrimaryGeneratedColumn21, Column as Column21 } from "typeorm";
6917
+ import { Entity as Entity22, PrimaryGeneratedColumn as PrimaryGeneratedColumn22, Column as Column22 } from "typeorm";
6203
6918
  var MessageTemplate = class {
6204
6919
  id;
6205
6920
  channel;
@@ -6219,59 +6934,59 @@ var MessageTemplate = class {
6219
6934
  deletedBy;
6220
6935
  };
6221
6936
  __decorateClass([
6222
- PrimaryGeneratedColumn21()
6937
+ PrimaryGeneratedColumn22()
6223
6938
  ], MessageTemplate.prototype, "id", 2);
6224
6939
  __decorateClass([
6225
- Column21("varchar")
6940
+ Column22("varchar")
6226
6941
  ], MessageTemplate.prototype, "channel", 2);
6227
6942
  __decorateClass([
6228
- Column21("varchar", { name: "template_key" })
6943
+ Column22("varchar", { name: "template_key" })
6229
6944
  ], MessageTemplate.prototype, "templateKey", 2);
6230
6945
  __decorateClass([
6231
- Column21("varchar", { nullable: true })
6946
+ Column22("varchar", { nullable: true })
6232
6947
  ], MessageTemplate.prototype, "name", 2);
6233
6948
  __decorateClass([
6234
- Column21("varchar", { nullable: true })
6949
+ Column22("varchar", { nullable: true })
6235
6950
  ], MessageTemplate.prototype, "subject", 2);
6236
6951
  __decorateClass([
6237
- Column21("text", { default: "" })
6952
+ Column22("text", { default: "" })
6238
6953
  ], MessageTemplate.prototype, "body", 2);
6239
6954
  __decorateClass([
6240
- Column21("varchar", { name: "external_template_ref", nullable: true })
6955
+ Column22("varchar", { name: "external_template_ref", nullable: true })
6241
6956
  ], MessageTemplate.prototype, "externalTemplateRef", 2);
6242
6957
  __decorateClass([
6243
- Column21({ type: "jsonb", nullable: true })
6958
+ Column22({ type: "jsonb", nullable: true })
6244
6959
  ], MessageTemplate.prototype, "providerMeta", 2);
6245
6960
  __decorateClass([
6246
- Column21("boolean", { default: true })
6961
+ Column22("boolean", { default: true })
6247
6962
  ], MessageTemplate.prototype, "enabled", 2);
6248
6963
  __decorateClass([
6249
- Column21({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6964
+ Column22({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6250
6965
  ], MessageTemplate.prototype, "createdAt", 2);
6251
6966
  __decorateClass([
6252
- Column21({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6967
+ Column22({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6253
6968
  ], MessageTemplate.prototype, "updatedAt", 2);
6254
6969
  __decorateClass([
6255
- Column21({ type: "timestamp", nullable: true })
6970
+ Column22({ type: "timestamp", nullable: true })
6256
6971
  ], MessageTemplate.prototype, "deletedAt", 2);
6257
6972
  __decorateClass([
6258
- Column21("boolean", { default: false })
6973
+ Column22("boolean", { default: false })
6259
6974
  ], MessageTemplate.prototype, "deleted", 2);
6260
6975
  __decorateClass([
6261
- Column21("int", { nullable: true })
6976
+ Column22("int", { nullable: true })
6262
6977
  ], MessageTemplate.prototype, "createdBy", 2);
6263
6978
  __decorateClass([
6264
- Column21("int", { nullable: true })
6979
+ Column22("int", { nullable: true })
6265
6980
  ], MessageTemplate.prototype, "updatedBy", 2);
6266
6981
  __decorateClass([
6267
- Column21("int", { nullable: true })
6982
+ Column22("int", { nullable: true })
6268
6983
  ], MessageTemplate.prototype, "deletedBy", 2);
6269
6984
  MessageTemplate = __decorateClass([
6270
- Entity21("message_templates")
6985
+ Entity22("message_templates")
6271
6986
  ], MessageTemplate);
6272
6987
 
6273
6988
  // src/entities/media.entity.ts
6274
- import { Entity as Entity22, PrimaryGeneratedColumn as PrimaryGeneratedColumn22, Column as Column22, ManyToOne as ManyToOne13, OneToMany as OneToMany9, JoinColumn as JoinColumn13 } from "typeorm";
6989
+ import { Entity as Entity23, PrimaryGeneratedColumn as PrimaryGeneratedColumn23, Column as Column23, ManyToOne as ManyToOne13, OneToMany as OneToMany9, JoinColumn as JoinColumn13 } from "typeorm";
6275
6990
  var Media = class {
6276
6991
  id;
6277
6992
  kind;
@@ -6290,13 +7005,13 @@ var Media = class {
6290
7005
  deleted;
6291
7006
  };
6292
7007
  __decorateClass([
6293
- PrimaryGeneratedColumn22()
7008
+ PrimaryGeneratedColumn23()
6294
7009
  ], Media.prototype, "id", 2);
6295
7010
  __decorateClass([
6296
- Column22({ type: "varchar", length: 16, default: "file" })
7011
+ Column23({ type: "varchar", length: 16, default: "file" })
6297
7012
  ], Media.prototype, "kind", 2);
6298
7013
  __decorateClass([
6299
- Column22({ type: "int", nullable: true })
7014
+ Column23({ type: "int", nullable: true })
6300
7015
  ], Media.prototype, "parentId", 2);
6301
7016
  __decorateClass([
6302
7017
  ManyToOne13(() => Media, (m) => m.children, { onDelete: "CASCADE" }),
@@ -6306,41 +7021,41 @@ __decorateClass([
6306
7021
  OneToMany9(() => Media, (m) => m.parent)
6307
7022
  ], Media.prototype, "children", 2);
6308
7023
  __decorateClass([
6309
- Column22("varchar")
7024
+ Column23("varchar")
6310
7025
  ], Media.prototype, "filename", 2);
6311
7026
  __decorateClass([
6312
- Column22("varchar", { nullable: true })
7027
+ Column23("varchar", { nullable: true })
6313
7028
  ], Media.prototype, "url", 2);
6314
7029
  __decorateClass([
6315
- Column22("varchar", { nullable: true })
7030
+ Column23("varchar", { nullable: true })
6316
7031
  ], Media.prototype, "mimeType", 2);
6317
7032
  __decorateClass([
6318
- Column22("int", { default: 0 })
7033
+ Column23("int", { default: 0 })
6319
7034
  ], Media.prototype, "size", 2);
6320
7035
  __decorateClass([
6321
- Column22("varchar", { nullable: true })
7036
+ Column23("varchar", { nullable: true })
6322
7037
  ], Media.prototype, "alt", 2);
6323
7038
  __decorateClass([
6324
- Column22("boolean", { default: false })
7039
+ Column23("boolean", { default: false })
6325
7040
  ], Media.prototype, "isPublic", 2);
6326
7041
  __decorateClass([
6327
- Column22({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7042
+ Column23({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6328
7043
  ], Media.prototype, "createdAt", 2);
6329
7044
  __decorateClass([
6330
- Column22({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7045
+ Column23({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6331
7046
  ], Media.prototype, "updatedAt", 2);
6332
7047
  __decorateClass([
6333
- Column22({ type: "timestamp", nullable: true })
7048
+ Column23({ type: "timestamp", nullable: true })
6334
7049
  ], Media.prototype, "deletedAt", 2);
6335
7050
  __decorateClass([
6336
- Column22("boolean", { default: false })
7051
+ Column23("boolean", { default: false })
6337
7052
  ], Media.prototype, "deleted", 2);
6338
7053
  Media = __decorateClass([
6339
- Entity22("media")
7054
+ Entity23("media")
6340
7055
  ], Media);
6341
7056
 
6342
7057
  // src/entities/page.entity.ts
6343
- import { Entity as Entity23, PrimaryGeneratedColumn as PrimaryGeneratedColumn23, Column as Column23, ManyToOne as ManyToOne14, JoinColumn as JoinColumn14 } from "typeorm";
7058
+ import { Entity as Entity24, PrimaryGeneratedColumn as PrimaryGeneratedColumn24, Column as Column24, ManyToOne as ManyToOne14, JoinColumn as JoinColumn14 } from "typeorm";
6344
7059
  var Page = class {
6345
7060
  id;
6346
7061
  title;
@@ -6361,64 +7076,64 @@ var Page = class {
6361
7076
  deletedBy;
6362
7077
  };
6363
7078
  __decorateClass([
6364
- PrimaryGeneratedColumn23()
7079
+ PrimaryGeneratedColumn24()
6365
7080
  ], Page.prototype, "id", 2);
6366
7081
  __decorateClass([
6367
- Column23("varchar")
7082
+ Column24("varchar")
6368
7083
  ], Page.prototype, "title", 2);
6369
7084
  __decorateClass([
6370
- Column23("varchar", { unique: true })
7085
+ Column24("varchar", { unique: true })
6371
7086
  ], Page.prototype, "slug", 2);
6372
7087
  __decorateClass([
6373
- Column23({ type: "jsonb", default: {} })
7088
+ Column24({ type: "jsonb", default: {} })
6374
7089
  ], Page.prototype, "content", 2);
6375
7090
  __decorateClass([
6376
- Column23("boolean", { default: false })
7091
+ Column24("boolean", { default: false })
6377
7092
  ], Page.prototype, "published", 2);
6378
7093
  __decorateClass([
6379
- Column23("varchar", { default: "default" })
7094
+ Column24("varchar", { default: "default" })
6380
7095
  ], Page.prototype, "theme", 2);
6381
7096
  __decorateClass([
6382
- Column23("int", { nullable: true })
7097
+ Column24("int", { nullable: true })
6383
7098
  ], Page.prototype, "parentId", 2);
6384
7099
  __decorateClass([
6385
7100
  ManyToOne14(() => Page, { onDelete: "SET NULL" }),
6386
7101
  JoinColumn14({ name: "parentId" })
6387
7102
  ], Page.prototype, "parent", 2);
6388
7103
  __decorateClass([
6389
- Column23("int", { nullable: true })
7104
+ Column24("int", { nullable: true })
6390
7105
  ], Page.prototype, "seoId", 2);
6391
7106
  __decorateClass([
6392
7107
  ManyToOne14(() => Seo, { onDelete: "SET NULL" }),
6393
7108
  JoinColumn14({ name: "seoId" })
6394
7109
  ], Page.prototype, "seo", 2);
6395
7110
  __decorateClass([
6396
- Column23({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7111
+ Column24({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6397
7112
  ], Page.prototype, "createdAt", 2);
6398
7113
  __decorateClass([
6399
- Column23({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7114
+ Column24({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6400
7115
  ], Page.prototype, "updatedAt", 2);
6401
7116
  __decorateClass([
6402
- Column23({ type: "timestamp", nullable: true })
7117
+ Column24({ type: "timestamp", nullable: true })
6403
7118
  ], Page.prototype, "deletedAt", 2);
6404
7119
  __decorateClass([
6405
- Column23("boolean", { default: false })
7120
+ Column24("boolean", { default: false })
6406
7121
  ], Page.prototype, "deleted", 2);
6407
7122
  __decorateClass([
6408
- Column23("int", { nullable: true })
7123
+ Column24("int", { nullable: true })
6409
7124
  ], Page.prototype, "createdBy", 2);
6410
7125
  __decorateClass([
6411
- Column23("int", { nullable: true })
7126
+ Column24("int", { nullable: true })
6412
7127
  ], Page.prototype, "updatedBy", 2);
6413
7128
  __decorateClass([
6414
- Column23("int", { nullable: true })
7129
+ Column24("int", { nullable: true })
6415
7130
  ], Page.prototype, "deletedBy", 2);
6416
7131
  Page = __decorateClass([
6417
- Entity23("pages")
7132
+ Entity24("pages")
6418
7133
  ], Page);
6419
7134
 
6420
7135
  // src/entities/product-category.entity.ts
6421
- import { Entity as Entity24, PrimaryGeneratedColumn as PrimaryGeneratedColumn24, Column as Column24, ManyToOne as ManyToOne15, OneToMany as OneToMany10, JoinColumn as JoinColumn15 } from "typeorm";
7136
+ import { Entity as Entity25, PrimaryGeneratedColumn as PrimaryGeneratedColumn25, Column as Column25, ManyToOne as ManyToOne15, OneToMany as OneToMany10, JoinColumn as JoinColumn15 } from "typeorm";
6422
7137
  var ProductCategory = class {
6423
7138
  id;
6424
7139
  name;
@@ -6442,52 +7157,52 @@ var ProductCategory = class {
6442
7157
  collections;
6443
7158
  };
6444
7159
  __decorateClass([
6445
- PrimaryGeneratedColumn24()
7160
+ PrimaryGeneratedColumn25()
6446
7161
  ], ProductCategory.prototype, "id", 2);
6447
7162
  __decorateClass([
6448
- Column24("varchar")
7163
+ Column25("varchar")
6449
7164
  ], ProductCategory.prototype, "name", 2);
6450
7165
  __decorateClass([
6451
- Column24("varchar", { unique: true })
7166
+ Column25("varchar", { unique: true })
6452
7167
  ], ProductCategory.prototype, "slug", 2);
6453
7168
  __decorateClass([
6454
- Column24("int", { nullable: true })
7169
+ Column25("int", { nullable: true })
6455
7170
  ], ProductCategory.prototype, "parentId", 2);
6456
7171
  __decorateClass([
6457
- Column24("varchar", { nullable: true })
7172
+ Column25("varchar", { nullable: true })
6458
7173
  ], ProductCategory.prototype, "image", 2);
6459
7174
  __decorateClass([
6460
- Column24("text", { nullable: true })
7175
+ Column25("text", { nullable: true })
6461
7176
  ], ProductCategory.prototype, "description", 2);
6462
7177
  __decorateClass([
6463
- Column24("jsonb", { nullable: true })
7178
+ Column25("jsonb", { nullable: true })
6464
7179
  ], ProductCategory.prototype, "metadata", 2);
6465
7180
  __decorateClass([
6466
- Column24("boolean", { default: true })
7181
+ Column25("boolean", { default: true })
6467
7182
  ], ProductCategory.prototype, "active", 2);
6468
7183
  __decorateClass([
6469
- Column24("int", { default: 0 })
7184
+ Column25("int", { default: 0 })
6470
7185
  ], ProductCategory.prototype, "sortOrder", 2);
6471
7186
  __decorateClass([
6472
- Column24({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7187
+ Column25({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6473
7188
  ], ProductCategory.prototype, "createdAt", 2);
6474
7189
  __decorateClass([
6475
- Column24({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7190
+ Column25({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6476
7191
  ], ProductCategory.prototype, "updatedAt", 2);
6477
7192
  __decorateClass([
6478
- Column24({ type: "timestamp", nullable: true })
7193
+ Column25({ type: "timestamp", nullable: true })
6479
7194
  ], ProductCategory.prototype, "deletedAt", 2);
6480
7195
  __decorateClass([
6481
- Column24("boolean", { default: false })
7196
+ Column25("boolean", { default: false })
6482
7197
  ], ProductCategory.prototype, "deleted", 2);
6483
7198
  __decorateClass([
6484
- Column24("int", { nullable: true })
7199
+ Column25("int", { nullable: true })
6485
7200
  ], ProductCategory.prototype, "createdBy", 2);
6486
7201
  __decorateClass([
6487
- Column24("int", { nullable: true })
7202
+ Column25("int", { nullable: true })
6488
7203
  ], ProductCategory.prototype, "updatedBy", 2);
6489
7204
  __decorateClass([
6490
- Column24("int", { nullable: true })
7205
+ Column25("int", { nullable: true })
6491
7206
  ], ProductCategory.prototype, "deletedBy", 2);
6492
7207
  __decorateClass([
6493
7208
  ManyToOne15(() => ProductCategory, (c) => c.children, { onDelete: "SET NULL" }),
@@ -6503,14 +7218,14 @@ __decorateClass([
6503
7218
  OneToMany10("Collection", "category")
6504
7219
  ], ProductCategory.prototype, "collections", 2);
6505
7220
  ProductCategory = __decorateClass([
6506
- Entity24("product_categories")
7221
+ Entity25("product_categories")
6507
7222
  ], ProductCategory);
6508
7223
 
6509
7224
  // src/entities/collection.entity.ts
6510
- import { Entity as Entity26, PrimaryGeneratedColumn as PrimaryGeneratedColumn26, Column as Column26, ManyToOne as ManyToOne17, OneToMany as OneToMany12, JoinColumn as JoinColumn17 } from "typeorm";
7225
+ import { Entity as Entity27, PrimaryGeneratedColumn as PrimaryGeneratedColumn27, Column as Column27, ManyToOne as ManyToOne17, OneToMany as OneToMany12, JoinColumn as JoinColumn17 } from "typeorm";
6511
7226
 
6512
7227
  // src/entities/brand.entity.ts
6513
- import { Entity as Entity25, PrimaryGeneratedColumn as PrimaryGeneratedColumn25, Column as Column25, OneToMany as OneToMany11, ManyToOne as ManyToOne16, JoinColumn as JoinColumn16 } from "typeorm";
7228
+ import { Entity as Entity26, PrimaryGeneratedColumn as PrimaryGeneratedColumn26, Column as Column26, OneToMany as OneToMany11, ManyToOne as ManyToOne16, JoinColumn as JoinColumn16 } from "typeorm";
6514
7229
  var Brand = class {
6515
7230
  id;
6516
7231
  name;
@@ -6533,52 +7248,52 @@ var Brand = class {
6533
7248
  collections;
6534
7249
  };
6535
7250
  __decorateClass([
6536
- PrimaryGeneratedColumn25()
7251
+ PrimaryGeneratedColumn26()
6537
7252
  ], Brand.prototype, "id", 2);
6538
7253
  __decorateClass([
6539
- Column25("varchar")
7254
+ Column26("varchar")
6540
7255
  ], Brand.prototype, "name", 2);
6541
7256
  __decorateClass([
6542
- Column25("varchar", { unique: true })
7257
+ Column26("varchar", { unique: true })
6543
7258
  ], Brand.prototype, "slug", 2);
6544
7259
  __decorateClass([
6545
- Column25("varchar", { nullable: true })
7260
+ Column26("varchar", { nullable: true })
6546
7261
  ], Brand.prototype, "logo", 2);
6547
7262
  __decorateClass([
6548
- Column25("jsonb", { nullable: true })
7263
+ Column26("jsonb", { nullable: true })
6549
7264
  ], Brand.prototype, "metadata", 2);
6550
7265
  __decorateClass([
6551
- Column25("text", { nullable: true })
7266
+ Column26("text", { nullable: true })
6552
7267
  ], Brand.prototype, "description", 2);
6553
7268
  __decorateClass([
6554
- Column25("boolean", { default: true })
7269
+ Column26("boolean", { default: true })
6555
7270
  ], Brand.prototype, "active", 2);
6556
7271
  __decorateClass([
6557
- Column25("int", { default: 0 })
7272
+ Column26("int", { default: 0 })
6558
7273
  ], Brand.prototype, "sortOrder", 2);
6559
7274
  __decorateClass([
6560
- Column25({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7275
+ Column26({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6561
7276
  ], Brand.prototype, "createdAt", 2);
6562
7277
  __decorateClass([
6563
- Column25({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7278
+ Column26({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6564
7279
  ], Brand.prototype, "updatedAt", 2);
6565
7280
  __decorateClass([
6566
- Column25({ type: "timestamp", nullable: true })
7281
+ Column26({ type: "timestamp", nullable: true })
6567
7282
  ], Brand.prototype, "deletedAt", 2);
6568
7283
  __decorateClass([
6569
- Column25("boolean", { default: false })
7284
+ Column26("boolean", { default: false })
6570
7285
  ], Brand.prototype, "deleted", 2);
6571
7286
  __decorateClass([
6572
- Column25("int", { nullable: true })
7287
+ Column26("int", { nullable: true })
6573
7288
  ], Brand.prototype, "createdBy", 2);
6574
7289
  __decorateClass([
6575
- Column25("int", { nullable: true })
7290
+ Column26("int", { nullable: true })
6576
7291
  ], Brand.prototype, "updatedBy", 2);
6577
7292
  __decorateClass([
6578
- Column25("int", { nullable: true })
7293
+ Column26("int", { nullable: true })
6579
7294
  ], Brand.prototype, "deletedBy", 2);
6580
7295
  __decorateClass([
6581
- Column25("int", { nullable: true })
7296
+ Column26("int", { nullable: true })
6582
7297
  ], Brand.prototype, "seoId", 2);
6583
7298
  __decorateClass([
6584
7299
  ManyToOne16(() => Seo, { onDelete: "SET NULL" }),
@@ -6591,7 +7306,7 @@ __decorateClass([
6591
7306
  OneToMany11("Collection", "brand")
6592
7307
  ], Brand.prototype, "collections", 2);
6593
7308
  Brand = __decorateClass([
6594
- Entity25("brands")
7309
+ Entity26("brands")
6595
7310
  ], Brand);
6596
7311
 
6597
7312
  // src/entities/collection.entity.ts
@@ -6622,64 +7337,64 @@ var Collection = class {
6622
7337
  products;
6623
7338
  };
6624
7339
  __decorateClass([
6625
- PrimaryGeneratedColumn26()
7340
+ PrimaryGeneratedColumn27()
6626
7341
  ], Collection.prototype, "id", 2);
6627
7342
  __decorateClass([
6628
- Column26("int", { nullable: true })
7343
+ Column27("int", { nullable: true })
6629
7344
  ], Collection.prototype, "categoryId", 2);
6630
7345
  __decorateClass([
6631
- Column26("int", { nullable: true })
7346
+ Column27("int", { nullable: true })
6632
7347
  ], Collection.prototype, "brandId", 2);
6633
7348
  __decorateClass([
6634
- Column26("varchar")
7349
+ Column27("varchar")
6635
7350
  ], Collection.prototype, "name", 2);
6636
7351
  __decorateClass([
6637
- Column26("varchar", { unique: true })
7352
+ Column27("varchar", { unique: true })
6638
7353
  ], Collection.prototype, "slug", 2);
6639
7354
  __decorateClass([
6640
- Column26("varchar", { nullable: true })
7355
+ Column27("varchar", { nullable: true })
6641
7356
  ], Collection.prototype, "hsn", 2);
6642
7357
  __decorateClass([
6643
- Column26("text", { nullable: true })
7358
+ Column27("text", { nullable: true })
6644
7359
  ], Collection.prototype, "description", 2);
6645
7360
  __decorateClass([
6646
- Column26("varchar", { nullable: true })
7361
+ Column27("varchar", { nullable: true })
6647
7362
  ], Collection.prototype, "image", 2);
6648
7363
  __decorateClass([
6649
- Column26("jsonb", { nullable: true })
7364
+ Column27("jsonb", { nullable: true })
6650
7365
  ], Collection.prototype, "metadata", 2);
6651
7366
  __decorateClass([
6652
- Column26("jsonb", { nullable: true })
7367
+ Column27("jsonb", { nullable: true })
6653
7368
  ], Collection.prototype, "variants", 2);
6654
7369
  __decorateClass([
6655
- Column26("boolean", { default: true })
7370
+ Column27("boolean", { default: true })
6656
7371
  ], Collection.prototype, "active", 2);
6657
7372
  __decorateClass([
6658
- Column26("int", { default: 0 })
7373
+ Column27("int", { default: 0 })
6659
7374
  ], Collection.prototype, "sortOrder", 2);
6660
7375
  __decorateClass([
6661
- Column26({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7376
+ Column27({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6662
7377
  ], Collection.prototype, "createdAt", 2);
6663
7378
  __decorateClass([
6664
- Column26({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7379
+ Column27({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6665
7380
  ], Collection.prototype, "updatedAt", 2);
6666
7381
  __decorateClass([
6667
- Column26({ type: "timestamp", nullable: true })
7382
+ Column27({ type: "timestamp", nullable: true })
6668
7383
  ], Collection.prototype, "deletedAt", 2);
6669
7384
  __decorateClass([
6670
- Column26("boolean", { default: false })
7385
+ Column27("boolean", { default: false })
6671
7386
  ], Collection.prototype, "deleted", 2);
6672
7387
  __decorateClass([
6673
- Column26("int", { nullable: true })
7388
+ Column27("int", { nullable: true })
6674
7389
  ], Collection.prototype, "createdBy", 2);
6675
7390
  __decorateClass([
6676
- Column26("int", { nullable: true })
7391
+ Column27("int", { nullable: true })
6677
7392
  ], Collection.prototype, "updatedBy", 2);
6678
7393
  __decorateClass([
6679
- Column26("int", { nullable: true })
7394
+ Column27("int", { nullable: true })
6680
7395
  ], Collection.prototype, "deletedBy", 2);
6681
7396
  __decorateClass([
6682
- Column26("int", { nullable: true })
7397
+ Column27("int", { nullable: true })
6683
7398
  ], Collection.prototype, "seoId", 2);
6684
7399
  __decorateClass([
6685
7400
  ManyToOne17(() => Seo, { onDelete: "SET NULL" }),
@@ -6697,11 +7412,11 @@ __decorateClass([
6697
7412
  OneToMany12("Product", "collection")
6698
7413
  ], Collection.prototype, "products", 2);
6699
7414
  Collection = __decorateClass([
6700
- Entity26("collections")
7415
+ Entity27("collections")
6701
7416
  ], Collection);
6702
7417
 
6703
7418
  // src/entities/product.entity.ts
6704
- import { Entity as Entity27, PrimaryGeneratedColumn as PrimaryGeneratedColumn27, Column as Column27, ManyToOne as ManyToOne18, OneToMany as OneToMany13, JoinColumn as JoinColumn18 } from "typeorm";
7419
+ import { Entity as Entity28, PrimaryGeneratedColumn as PrimaryGeneratedColumn28, Column as Column28, ManyToOne as ManyToOne18, OneToMany as OneToMany13, JoinColumn as JoinColumn18 } from "typeorm";
6705
7420
  var Product = class {
6706
7421
  id;
6707
7422
  collectionId;
@@ -6735,76 +7450,76 @@ var Product = class {
6735
7450
  taxes;
6736
7451
  };
6737
7452
  __decorateClass([
6738
- PrimaryGeneratedColumn27()
7453
+ PrimaryGeneratedColumn28()
6739
7454
  ], Product.prototype, "id", 2);
6740
7455
  __decorateClass([
6741
- Column27("int", { nullable: true })
7456
+ Column28("int", { nullable: true })
6742
7457
  ], Product.prototype, "collectionId", 2);
6743
7458
  __decorateClass([
6744
- Column27("int", { nullable: true })
7459
+ Column28("int", { nullable: true })
6745
7460
  ], Product.prototype, "brandId", 2);
6746
7461
  __decorateClass([
6747
- Column27("int", { nullable: true })
7462
+ Column28("int", { nullable: true })
6748
7463
  ], Product.prototype, "categoryId", 2);
6749
7464
  __decorateClass([
6750
- Column27("varchar", { nullable: true })
7465
+ Column28("varchar", { nullable: true })
6751
7466
  ], Product.prototype, "sku", 2);
6752
7467
  __decorateClass([
6753
- Column27("varchar", { nullable: true })
7468
+ Column28("varchar", { nullable: true })
6754
7469
  ], Product.prototype, "hsn", 2);
6755
7470
  __decorateClass([
6756
- Column27("varchar", { nullable: true })
7471
+ Column28("varchar", { nullable: true })
6757
7472
  ], Product.prototype, "uom", 2);
6758
7473
  __decorateClass([
6759
- Column27("varchar", { default: "product" })
7474
+ Column28("varchar", { default: "product" })
6760
7475
  ], Product.prototype, "type", 2);
6761
7476
  __decorateClass([
6762
- Column27("varchar", { unique: true, nullable: true })
7477
+ Column28("varchar", { unique: true, nullable: true })
6763
7478
  ], Product.prototype, "slug", 2);
6764
7479
  __decorateClass([
6765
- Column27("varchar", { nullable: true })
7480
+ Column28("varchar", { nullable: true })
6766
7481
  ], Product.prototype, "name", 2);
6767
7482
  __decorateClass([
6768
- Column27("decimal", { precision: 12, scale: 2 })
7483
+ Column28("decimal", { precision: 12, scale: 2 })
6769
7484
  ], Product.prototype, "price", 2);
6770
7485
  __decorateClass([
6771
- Column27("decimal", { precision: 12, scale: 2, nullable: true })
7486
+ Column28("decimal", { precision: 12, scale: 2, nullable: true })
6772
7487
  ], Product.prototype, "compareAtPrice", 2);
6773
7488
  __decorateClass([
6774
- Column27("int", { default: 0 })
7489
+ Column28("int", { default: 0 })
6775
7490
  ], Product.prototype, "quantity", 2);
6776
7491
  __decorateClass([
6777
- Column27("varchar", { default: "draft" })
7492
+ Column28("varchar", { default: "draft" })
6778
7493
  ], Product.prototype, "status", 2);
6779
7494
  __decorateClass([
6780
- Column27("boolean", { default: false })
7495
+ Column28("boolean", { default: false })
6781
7496
  ], Product.prototype, "featured", 2);
6782
7497
  __decorateClass([
6783
- Column27("jsonb", { nullable: true })
7498
+ Column28("jsonb", { nullable: true })
6784
7499
  ], Product.prototype, "metadata", 2);
6785
7500
  __decorateClass([
6786
- Column27({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7501
+ Column28({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6787
7502
  ], Product.prototype, "createdAt", 2);
6788
7503
  __decorateClass([
6789
- Column27({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7504
+ Column28({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6790
7505
  ], Product.prototype, "updatedAt", 2);
6791
7506
  __decorateClass([
6792
- Column27({ type: "timestamp", nullable: true })
7507
+ Column28({ type: "timestamp", nullable: true })
6793
7508
  ], Product.prototype, "deletedAt", 2);
6794
7509
  __decorateClass([
6795
- Column27("boolean", { default: false })
7510
+ Column28("boolean", { default: false })
6796
7511
  ], Product.prototype, "deleted", 2);
6797
7512
  __decorateClass([
6798
- Column27("int", { nullable: true })
7513
+ Column28("int", { nullable: true })
6799
7514
  ], Product.prototype, "createdBy", 2);
6800
7515
  __decorateClass([
6801
- Column27("int", { nullable: true })
7516
+ Column28("int", { nullable: true })
6802
7517
  ], Product.prototype, "updatedBy", 2);
6803
7518
  __decorateClass([
6804
- Column27("int", { nullable: true })
7519
+ Column28("int", { nullable: true })
6805
7520
  ], Product.prototype, "deletedBy", 2);
6806
7521
  __decorateClass([
6807
- Column27("int", { nullable: true })
7522
+ Column28("int", { nullable: true })
6808
7523
  ], Product.prototype, "seoId", 2);
6809
7524
  __decorateClass([
6810
7525
  ManyToOne18(() => Seo, { onDelete: "SET NULL" }),
@@ -6829,11 +7544,11 @@ __decorateClass([
6829
7544
  OneToMany13("ProductTax", "product")
6830
7545
  ], Product.prototype, "taxes", 2);
6831
7546
  Product = __decorateClass([
6832
- Entity27("products")
7547
+ Entity28("products")
6833
7548
  ], Product);
6834
7549
 
6835
7550
  // src/entities/attribute.entity.ts
6836
- import { Entity as Entity28, PrimaryGeneratedColumn as PrimaryGeneratedColumn28, Column as Column28 } from "typeorm";
7551
+ import { Entity as Entity29, PrimaryGeneratedColumn as PrimaryGeneratedColumn29, Column as Column29 } from "typeorm";
6837
7552
  var Attribute = class {
6838
7553
  id;
6839
7554
  name;
@@ -6852,56 +7567,56 @@ var Attribute = class {
6852
7567
  deletedBy;
6853
7568
  };
6854
7569
  __decorateClass([
6855
- PrimaryGeneratedColumn28()
7570
+ PrimaryGeneratedColumn29()
6856
7571
  ], Attribute.prototype, "id", 2);
6857
7572
  __decorateClass([
6858
- Column28("varchar")
7573
+ Column29("varchar")
6859
7574
  ], Attribute.prototype, "name", 2);
6860
7575
  __decorateClass([
6861
- Column28("varchar", { unique: true })
7576
+ Column29("varchar", { unique: true })
6862
7577
  ], Attribute.prototype, "slug", 2);
6863
7578
  __decorateClass([
6864
- Column28("varchar", { default: "text" })
7579
+ Column29("varchar", { default: "text" })
6865
7580
  ], Attribute.prototype, "type", 2);
6866
7581
  __decorateClass([
6867
- Column28("jsonb", { nullable: true })
7582
+ Column29("jsonb", { nullable: true })
6868
7583
  ], Attribute.prototype, "options", 2);
6869
7584
  __decorateClass([
6870
- Column28("jsonb", { nullable: true })
7585
+ Column29("jsonb", { nullable: true })
6871
7586
  ], Attribute.prototype, "metadata", 2);
6872
7587
  __decorateClass([
6873
- Column28("boolean", { default: true })
7588
+ Column29("boolean", { default: true })
6874
7589
  ], Attribute.prototype, "active", 2);
6875
7590
  __decorateClass([
6876
- Column28("int", { default: 0 })
7591
+ Column29("int", { default: 0 })
6877
7592
  ], Attribute.prototype, "sortOrder", 2);
6878
7593
  __decorateClass([
6879
- Column28({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7594
+ Column29({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6880
7595
  ], Attribute.prototype, "createdAt", 2);
6881
7596
  __decorateClass([
6882
- Column28({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7597
+ Column29({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6883
7598
  ], Attribute.prototype, "updatedAt", 2);
6884
7599
  __decorateClass([
6885
- Column28({ type: "timestamp", nullable: true })
7600
+ Column29({ type: "timestamp", nullable: true })
6886
7601
  ], Attribute.prototype, "deletedAt", 2);
6887
7602
  __decorateClass([
6888
- Column28("boolean", { default: false })
7603
+ Column29("boolean", { default: false })
6889
7604
  ], Attribute.prototype, "deleted", 2);
6890
7605
  __decorateClass([
6891
- Column28("int", { nullable: true })
7606
+ Column29("int", { nullable: true })
6892
7607
  ], Attribute.prototype, "createdBy", 2);
6893
7608
  __decorateClass([
6894
- Column28("int", { nullable: true })
7609
+ Column29("int", { nullable: true })
6895
7610
  ], Attribute.prototype, "updatedBy", 2);
6896
7611
  __decorateClass([
6897
- Column28("int", { nullable: true })
7612
+ Column29("int", { nullable: true })
6898
7613
  ], Attribute.prototype, "deletedBy", 2);
6899
7614
  Attribute = __decorateClass([
6900
- Entity28("attributes")
7615
+ Entity29("attributes")
6901
7616
  ], Attribute);
6902
7617
 
6903
7618
  // src/entities/product-attribute.entity.ts
6904
- import { Entity as Entity29, PrimaryGeneratedColumn as PrimaryGeneratedColumn29, Column as Column29, ManyToOne as ManyToOne19, JoinColumn as JoinColumn19 } from "typeorm";
7619
+ import { Entity as Entity30, PrimaryGeneratedColumn as PrimaryGeneratedColumn30, Column as Column30, ManyToOne as ManyToOne19, JoinColumn as JoinColumn19 } from "typeorm";
6905
7620
  var ProductAttribute = class {
6906
7621
  id;
6907
7622
  productId;
@@ -6914,25 +7629,25 @@ var ProductAttribute = class {
6914
7629
  attribute;
6915
7630
  };
6916
7631
  __decorateClass([
6917
- PrimaryGeneratedColumn29()
7632
+ PrimaryGeneratedColumn30()
6918
7633
  ], ProductAttribute.prototype, "id", 2);
6919
7634
  __decorateClass([
6920
- Column29("int")
7635
+ Column30("int")
6921
7636
  ], ProductAttribute.prototype, "productId", 2);
6922
7637
  __decorateClass([
6923
- Column29("int")
7638
+ Column30("int")
6924
7639
  ], ProductAttribute.prototype, "attributeId", 2);
6925
7640
  __decorateClass([
6926
- Column29("varchar")
7641
+ Column30("varchar")
6927
7642
  ], ProductAttribute.prototype, "value", 2);
6928
7643
  __decorateClass([
6929
- Column29("jsonb", { nullable: true })
7644
+ Column30("jsonb", { nullable: true })
6930
7645
  ], ProductAttribute.prototype, "metadata", 2);
6931
7646
  __decorateClass([
6932
- Column29({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7647
+ Column30({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6933
7648
  ], ProductAttribute.prototype, "createdAt", 2);
6934
7649
  __decorateClass([
6935
- Column29({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7650
+ Column30({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6936
7651
  ], ProductAttribute.prototype, "updatedAt", 2);
6937
7652
  __decorateClass([
6938
7653
  ManyToOne19(() => Product, (p) => p.attributes, { onDelete: "CASCADE" }),
@@ -6943,11 +7658,11 @@ __decorateClass([
6943
7658
  JoinColumn19({ name: "attributeId" })
6944
7659
  ], ProductAttribute.prototype, "attribute", 2);
6945
7660
  ProductAttribute = __decorateClass([
6946
- Entity29("product_attributes")
7661
+ Entity30("product_attributes")
6947
7662
  ], ProductAttribute);
6948
7663
 
6949
7664
  // src/entities/tax.entity.ts
6950
- import { Entity as Entity30, PrimaryGeneratedColumn as PrimaryGeneratedColumn30, Column as Column30 } from "typeorm";
7665
+ import { Entity as Entity31, PrimaryGeneratedColumn as PrimaryGeneratedColumn31, Column as Column31 } from "typeorm";
6951
7666
  var Tax = class {
6952
7667
  id;
6953
7668
  name;
@@ -6966,56 +7681,56 @@ var Tax = class {
6966
7681
  deletedBy;
6967
7682
  };
6968
7683
  __decorateClass([
6969
- PrimaryGeneratedColumn30()
7684
+ PrimaryGeneratedColumn31()
6970
7685
  ], Tax.prototype, "id", 2);
6971
7686
  __decorateClass([
6972
- Column30("varchar")
7687
+ Column31("varchar")
6973
7688
  ], Tax.prototype, "name", 2);
6974
7689
  __decorateClass([
6975
- Column30("varchar", { unique: true })
7690
+ Column31("varchar", { unique: true })
6976
7691
  ], Tax.prototype, "slug", 2);
6977
7692
  __decorateClass([
6978
- Column30("decimal", { precision: 5, scale: 2 })
7693
+ Column31("decimal", { precision: 5, scale: 2 })
6979
7694
  ], Tax.prototype, "rate", 2);
6980
7695
  __decorateClass([
6981
- Column30("boolean", { default: false })
7696
+ Column31("boolean", { default: false })
6982
7697
  ], Tax.prototype, "isDefault", 2);
6983
7698
  __decorateClass([
6984
- Column30("text", { nullable: true })
7699
+ Column31("text", { nullable: true })
6985
7700
  ], Tax.prototype, "description", 2);
6986
7701
  __decorateClass([
6987
- Column30("boolean", { default: true })
7702
+ Column31("boolean", { default: true })
6988
7703
  ], Tax.prototype, "active", 2);
6989
7704
  __decorateClass([
6990
- Column30("jsonb", { nullable: true })
7705
+ Column31("jsonb", { nullable: true })
6991
7706
  ], Tax.prototype, "metadata", 2);
6992
7707
  __decorateClass([
6993
- Column30({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7708
+ Column31({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6994
7709
  ], Tax.prototype, "createdAt", 2);
6995
7710
  __decorateClass([
6996
- Column30({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7711
+ Column31({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
6997
7712
  ], Tax.prototype, "updatedAt", 2);
6998
7713
  __decorateClass([
6999
- Column30({ type: "timestamp", nullable: true })
7714
+ Column31({ type: "timestamp", nullable: true })
7000
7715
  ], Tax.prototype, "deletedAt", 2);
7001
7716
  __decorateClass([
7002
- Column30("boolean", { default: false })
7717
+ Column31("boolean", { default: false })
7003
7718
  ], Tax.prototype, "deleted", 2);
7004
7719
  __decorateClass([
7005
- Column30("int", { nullable: true })
7720
+ Column31("int", { nullable: true })
7006
7721
  ], Tax.prototype, "createdBy", 2);
7007
7722
  __decorateClass([
7008
- Column30("int", { nullable: true })
7723
+ Column31("int", { nullable: true })
7009
7724
  ], Tax.prototype, "updatedBy", 2);
7010
7725
  __decorateClass([
7011
- Column30("int", { nullable: true })
7726
+ Column31("int", { nullable: true })
7012
7727
  ], Tax.prototype, "deletedBy", 2);
7013
7728
  Tax = __decorateClass([
7014
- Entity30("taxes")
7729
+ Entity31("taxes")
7015
7730
  ], Tax);
7016
7731
 
7017
7732
  // src/entities/product-tax.entity.ts
7018
- import { Entity as Entity31, PrimaryGeneratedColumn as PrimaryGeneratedColumn31, Column as Column31, ManyToOne as ManyToOne20, JoinColumn as JoinColumn20 } from "typeorm";
7733
+ import { Entity as Entity32, PrimaryGeneratedColumn as PrimaryGeneratedColumn32, Column as Column32, ManyToOne as ManyToOne20, JoinColumn as JoinColumn20 } from "typeorm";
7019
7734
  var ProductTax = class {
7020
7735
  id;
7021
7736
  productId;
@@ -7027,22 +7742,22 @@ var ProductTax = class {
7027
7742
  tax;
7028
7743
  };
7029
7744
  __decorateClass([
7030
- PrimaryGeneratedColumn31()
7745
+ PrimaryGeneratedColumn32()
7031
7746
  ], ProductTax.prototype, "id", 2);
7032
7747
  __decorateClass([
7033
- Column31("int")
7748
+ Column32("int")
7034
7749
  ], ProductTax.prototype, "productId", 2);
7035
7750
  __decorateClass([
7036
- Column31("int")
7751
+ Column32("int")
7037
7752
  ], ProductTax.prototype, "taxId", 2);
7038
7753
  __decorateClass([
7039
- Column31("decimal", { precision: 5, scale: 2, nullable: true })
7754
+ Column32("decimal", { precision: 5, scale: 2, nullable: true })
7040
7755
  ], ProductTax.prototype, "rate", 2);
7041
7756
  __decorateClass([
7042
- Column31({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7757
+ Column32({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7043
7758
  ], ProductTax.prototype, "createdAt", 2);
7044
7759
  __decorateClass([
7045
- Column31({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7760
+ Column32({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7046
7761
  ], ProductTax.prototype, "updatedAt", 2);
7047
7762
  __decorateClass([
7048
7763
  ManyToOne20(() => Product, (p) => p.taxes, { onDelete: "CASCADE" }),
@@ -7053,11 +7768,11 @@ __decorateClass([
7053
7768
  JoinColumn20({ name: "taxId" })
7054
7769
  ], ProductTax.prototype, "tax", 2);
7055
7770
  ProductTax = __decorateClass([
7056
- Entity31("product_taxes")
7771
+ Entity32("product_taxes")
7057
7772
  ], ProductTax);
7058
7773
 
7059
7774
  // src/entities/order-item.entity.ts
7060
- import { Entity as Entity32, PrimaryGeneratedColumn as PrimaryGeneratedColumn32, Column as Column32, ManyToOne as ManyToOne21, JoinColumn as JoinColumn21 } from "typeorm";
7775
+ import { Entity as Entity33, PrimaryGeneratedColumn as PrimaryGeneratedColumn33, Column as Column33, ManyToOne as ManyToOne21, JoinColumn as JoinColumn21 } from "typeorm";
7061
7776
  var OrderItem = class {
7062
7777
  id;
7063
7778
  orderId;
@@ -7078,49 +7793,49 @@ var OrderItem = class {
7078
7793
  product;
7079
7794
  };
7080
7795
  __decorateClass([
7081
- PrimaryGeneratedColumn32()
7796
+ PrimaryGeneratedColumn33()
7082
7797
  ], OrderItem.prototype, "id", 2);
7083
7798
  __decorateClass([
7084
- Column32("int")
7799
+ Column33("int")
7085
7800
  ], OrderItem.prototype, "orderId", 2);
7086
7801
  __decorateClass([
7087
- Column32("int")
7802
+ Column33("int")
7088
7803
  ], OrderItem.prototype, "productId", 2);
7089
7804
  __decorateClass([
7090
- Column32("int", { default: 1 })
7805
+ Column33("int", { default: 1 })
7091
7806
  ], OrderItem.prototype, "quantity", 2);
7092
7807
  __decorateClass([
7093
- Column32("decimal", { precision: 12, scale: 2 })
7808
+ Column33("decimal", { precision: 12, scale: 2 })
7094
7809
  ], OrderItem.prototype, "unitPrice", 2);
7095
7810
  __decorateClass([
7096
- Column32("decimal", { precision: 12, scale: 2, default: 0 })
7811
+ Column33("decimal", { precision: 12, scale: 2, default: 0 })
7097
7812
  ], OrderItem.prototype, "tax", 2);
7098
7813
  __decorateClass([
7099
- Column32("decimal", { precision: 12, scale: 2 })
7814
+ Column33("decimal", { precision: 12, scale: 2 })
7100
7815
  ], OrderItem.prototype, "total", 2);
7101
7816
  __decorateClass([
7102
- Column32("varchar", { nullable: true })
7817
+ Column33("varchar", { nullable: true })
7103
7818
  ], OrderItem.prototype, "hsn", 2);
7104
7819
  __decorateClass([
7105
- Column32("varchar", { nullable: true })
7820
+ Column33("varchar", { nullable: true })
7106
7821
  ], OrderItem.prototype, "uom", 2);
7107
7822
  __decorateClass([
7108
- Column32("varchar", { nullable: true })
7823
+ Column33("varchar", { nullable: true })
7109
7824
  ], OrderItem.prototype, "productType", 2);
7110
7825
  __decorateClass([
7111
- Column32("decimal", { precision: 5, scale: 2, nullable: true })
7826
+ Column33("decimal", { precision: 5, scale: 2, nullable: true })
7112
7827
  ], OrderItem.prototype, "taxRate", 2);
7113
7828
  __decorateClass([
7114
- Column32("varchar", { nullable: true })
7829
+ Column33("varchar", { nullable: true })
7115
7830
  ], OrderItem.prototype, "taxCode", 2);
7116
7831
  __decorateClass([
7117
- Column32("jsonb", { nullable: true })
7832
+ Column33("jsonb", { nullable: true })
7118
7833
  ], OrderItem.prototype, "metadata", 2);
7119
7834
  __decorateClass([
7120
- Column32({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7835
+ Column33({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7121
7836
  ], OrderItem.prototype, "createdAt", 2);
7122
7837
  __decorateClass([
7123
- Column32({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7838
+ Column33({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7124
7839
  ], OrderItem.prototype, "updatedAt", 2);
7125
7840
  __decorateClass([
7126
7841
  ManyToOne21(() => Order, (o) => o.items, { onDelete: "CASCADE" }),
@@ -7131,14 +7846,14 @@ __decorateClass([
7131
7846
  JoinColumn21({ name: "productId" })
7132
7847
  ], OrderItem.prototype, "product", 2);
7133
7848
  OrderItem = __decorateClass([
7134
- Entity32("order_items")
7849
+ Entity33("order_items")
7135
7850
  ], OrderItem);
7136
7851
 
7137
7852
  // src/entities/knowledge-base-document.entity.ts
7138
- import { Entity as Entity34, PrimaryGeneratedColumn as PrimaryGeneratedColumn34, Column as Column34, OneToMany as OneToMany14 } from "typeorm";
7853
+ import { Entity as Entity35, PrimaryGeneratedColumn as PrimaryGeneratedColumn35, Column as Column35, OneToMany as OneToMany14 } from "typeorm";
7139
7854
 
7140
7855
  // src/entities/knowledge-base-chunk.entity.ts
7141
- import { Entity as Entity33, PrimaryGeneratedColumn as PrimaryGeneratedColumn33, Column as Column33, ManyToOne as ManyToOne22, JoinColumn as JoinColumn22 } from "typeorm";
7856
+ import { Entity as Entity34, PrimaryGeneratedColumn as PrimaryGeneratedColumn34, Column as Column34, ManyToOne as ManyToOne22, JoinColumn as JoinColumn22 } from "typeorm";
7142
7857
  var KnowledgeBaseChunk = class {
7143
7858
  id;
7144
7859
  documentId;
@@ -7148,26 +7863,26 @@ var KnowledgeBaseChunk = class {
7148
7863
  document;
7149
7864
  };
7150
7865
  __decorateClass([
7151
- PrimaryGeneratedColumn33()
7866
+ PrimaryGeneratedColumn34()
7152
7867
  ], KnowledgeBaseChunk.prototype, "id", 2);
7153
7868
  __decorateClass([
7154
- Column33("int")
7869
+ Column34("int")
7155
7870
  ], KnowledgeBaseChunk.prototype, "documentId", 2);
7156
7871
  __decorateClass([
7157
- Column33("text")
7872
+ Column34("text")
7158
7873
  ], KnowledgeBaseChunk.prototype, "content", 2);
7159
7874
  __decorateClass([
7160
- Column33("int", { default: 0 })
7875
+ Column34("int", { default: 0 })
7161
7876
  ], KnowledgeBaseChunk.prototype, "chunkIndex", 2);
7162
7877
  __decorateClass([
7163
- Column33({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7878
+ Column34({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7164
7879
  ], KnowledgeBaseChunk.prototype, "createdAt", 2);
7165
7880
  __decorateClass([
7166
7881
  ManyToOne22(() => KnowledgeBaseDocument, (d) => d.chunks, { onDelete: "CASCADE" }),
7167
7882
  JoinColumn22({ name: "documentId" })
7168
7883
  ], KnowledgeBaseChunk.prototype, "document", 2);
7169
7884
  KnowledgeBaseChunk = __decorateClass([
7170
- Entity33("knowledge_base_chunks")
7885
+ Entity34("knowledge_base_chunks")
7171
7886
  ], KnowledgeBaseChunk);
7172
7887
 
7173
7888
  // src/entities/knowledge-base-document.entity.ts
@@ -7181,32 +7896,32 @@ var KnowledgeBaseDocument = class {
7181
7896
  chunks;
7182
7897
  };
7183
7898
  __decorateClass([
7184
- PrimaryGeneratedColumn34()
7899
+ PrimaryGeneratedColumn35()
7185
7900
  ], KnowledgeBaseDocument.prototype, "id", 2);
7186
7901
  __decorateClass([
7187
- Column34("varchar")
7902
+ Column35("varchar")
7188
7903
  ], KnowledgeBaseDocument.prototype, "name", 2);
7189
7904
  __decorateClass([
7190
- Column34("varchar", { nullable: true })
7905
+ Column35("varchar", { nullable: true })
7191
7906
  ], KnowledgeBaseDocument.prototype, "sourceUrl", 2);
7192
7907
  __decorateClass([
7193
- Column34("text")
7908
+ Column35("text")
7194
7909
  ], KnowledgeBaseDocument.prototype, "content", 2);
7195
7910
  __decorateClass([
7196
- Column34({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7911
+ Column35({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7197
7912
  ], KnowledgeBaseDocument.prototype, "createdAt", 2);
7198
7913
  __decorateClass([
7199
- Column34({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7914
+ Column35({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7200
7915
  ], KnowledgeBaseDocument.prototype, "updatedAt", 2);
7201
7916
  __decorateClass([
7202
7917
  OneToMany14(() => KnowledgeBaseChunk, (c) => c.document)
7203
7918
  ], KnowledgeBaseDocument.prototype, "chunks", 2);
7204
7919
  KnowledgeBaseDocument = __decorateClass([
7205
- Entity34("knowledge_base_documents")
7920
+ Entity35("knowledge_base_documents")
7206
7921
  ], KnowledgeBaseDocument);
7207
7922
 
7208
7923
  // src/entities/cart.entity.ts
7209
- import { Entity as Entity35, PrimaryGeneratedColumn as PrimaryGeneratedColumn35, Column as Column35, ManyToOne as ManyToOne23, OneToMany as OneToMany15, JoinColumn as JoinColumn23 } from "typeorm";
7924
+ import { Entity as Entity36, PrimaryGeneratedColumn as PrimaryGeneratedColumn36, Column as Column36, ManyToOne as ManyToOne23, OneToMany as OneToMany15, JoinColumn as JoinColumn23 } from "typeorm";
7210
7925
  var Cart = class {
7211
7926
  id;
7212
7927
  guestToken;
@@ -7219,25 +7934,25 @@ var Cart = class {
7219
7934
  items;
7220
7935
  };
7221
7936
  __decorateClass([
7222
- PrimaryGeneratedColumn35()
7937
+ PrimaryGeneratedColumn36()
7223
7938
  ], Cart.prototype, "id", 2);
7224
7939
  __decorateClass([
7225
- Column35("varchar", { nullable: true })
7940
+ Column36("varchar", { nullable: true })
7226
7941
  ], Cart.prototype, "guestToken", 2);
7227
7942
  __decorateClass([
7228
- Column35("int", { nullable: true })
7943
+ Column36("int", { nullable: true })
7229
7944
  ], Cart.prototype, "contactId", 2);
7230
7945
  __decorateClass([
7231
- Column35("varchar", { default: "INR" })
7946
+ Column36("varchar", { default: "INR" })
7232
7947
  ], Cart.prototype, "currency", 2);
7233
7948
  __decorateClass([
7234
- Column35({ type: "timestamp", nullable: true })
7949
+ Column36({ type: "timestamp", nullable: true })
7235
7950
  ], Cart.prototype, "expiresAt", 2);
7236
7951
  __decorateClass([
7237
- Column35({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7952
+ Column36({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7238
7953
  ], Cart.prototype, "createdAt", 2);
7239
7954
  __decorateClass([
7240
- Column35({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7955
+ Column36({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7241
7956
  ], Cart.prototype, "updatedAt", 2);
7242
7957
  __decorateClass([
7243
7958
  ManyToOne23(() => Contact, { onDelete: "CASCADE" }),
@@ -7247,11 +7962,11 @@ __decorateClass([
7247
7962
  OneToMany15("CartItem", "cart")
7248
7963
  ], Cart.prototype, "items", 2);
7249
7964
  Cart = __decorateClass([
7250
- Entity35("carts")
7965
+ Entity36("carts")
7251
7966
  ], Cart);
7252
7967
 
7253
7968
  // src/entities/cart-item.entity.ts
7254
- import { Entity as Entity36, PrimaryGeneratedColumn as PrimaryGeneratedColumn36, Column as Column36, ManyToOne as ManyToOne24, JoinColumn as JoinColumn24 } from "typeorm";
7969
+ import { Entity as Entity37, PrimaryGeneratedColumn as PrimaryGeneratedColumn37, Column as Column37, ManyToOne as ManyToOne24, JoinColumn as JoinColumn24 } from "typeorm";
7255
7970
  var CartItem = class {
7256
7971
  id;
7257
7972
  cartId;
@@ -7264,25 +7979,25 @@ var CartItem = class {
7264
7979
  product;
7265
7980
  };
7266
7981
  __decorateClass([
7267
- PrimaryGeneratedColumn36()
7982
+ PrimaryGeneratedColumn37()
7268
7983
  ], CartItem.prototype, "id", 2);
7269
7984
  __decorateClass([
7270
- Column36("int")
7985
+ Column37("int")
7271
7986
  ], CartItem.prototype, "cartId", 2);
7272
7987
  __decorateClass([
7273
- Column36("int")
7988
+ Column37("int")
7274
7989
  ], CartItem.prototype, "productId", 2);
7275
7990
  __decorateClass([
7276
- Column36("int", { default: 1 })
7991
+ Column37("int", { default: 1 })
7277
7992
  ], CartItem.prototype, "quantity", 2);
7278
7993
  __decorateClass([
7279
- Column36("jsonb", { nullable: true })
7994
+ Column37("jsonb", { nullable: true })
7280
7995
  ], CartItem.prototype, "metadata", 2);
7281
7996
  __decorateClass([
7282
- Column36({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7997
+ Column37({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7283
7998
  ], CartItem.prototype, "createdAt", 2);
7284
7999
  __decorateClass([
7285
- Column36({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
8000
+ Column37({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7286
8001
  ], CartItem.prototype, "updatedAt", 2);
7287
8002
  __decorateClass([
7288
8003
  ManyToOne24(() => Cart, (c) => c.items, { onDelete: "CASCADE" }),
@@ -7293,11 +8008,11 @@ __decorateClass([
7293
8008
  JoinColumn24({ name: "productId" })
7294
8009
  ], CartItem.prototype, "product", 2);
7295
8010
  CartItem = __decorateClass([
7296
- Entity36("cart_items")
8011
+ Entity37("cart_items")
7297
8012
  ], CartItem);
7298
8013
 
7299
8014
  // src/entities/wishlist.entity.ts
7300
- import { Entity as Entity37, PrimaryGeneratedColumn as PrimaryGeneratedColumn37, Column as Column37, ManyToOne as ManyToOne25, OneToMany as OneToMany16, JoinColumn as JoinColumn25 } from "typeorm";
8015
+ import { Entity as Entity38, PrimaryGeneratedColumn as PrimaryGeneratedColumn38, Column as Column38, ManyToOne as ManyToOne25, OneToMany as OneToMany16, JoinColumn as JoinColumn25 } from "typeorm";
7301
8016
  var Wishlist = class {
7302
8017
  id;
7303
8018
  guestId;
@@ -7309,22 +8024,22 @@ var Wishlist = class {
7309
8024
  items;
7310
8025
  };
7311
8026
  __decorateClass([
7312
- PrimaryGeneratedColumn37()
8027
+ PrimaryGeneratedColumn38()
7313
8028
  ], Wishlist.prototype, "id", 2);
7314
8029
  __decorateClass([
7315
- Column37("varchar", { nullable: true })
8030
+ Column38("varchar", { nullable: true })
7316
8031
  ], Wishlist.prototype, "guestId", 2);
7317
8032
  __decorateClass([
7318
- Column37("int", { nullable: true })
8033
+ Column38("int", { nullable: true })
7319
8034
  ], Wishlist.prototype, "contactId", 2);
7320
8035
  __decorateClass([
7321
- Column37("varchar", { default: "default" })
8036
+ Column38("varchar", { default: "default" })
7322
8037
  ], Wishlist.prototype, "name", 2);
7323
8038
  __decorateClass([
7324
- Column37({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
8039
+ Column38({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7325
8040
  ], Wishlist.prototype, "createdAt", 2);
7326
8041
  __decorateClass([
7327
- Column37({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
8042
+ Column38({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7328
8043
  ], Wishlist.prototype, "updatedAt", 2);
7329
8044
  __decorateClass([
7330
8045
  ManyToOne25(() => Contact, { onDelete: "CASCADE" }),
@@ -7334,11 +8049,11 @@ __decorateClass([
7334
8049
  OneToMany16("WishlistItem", "wishlist")
7335
8050
  ], Wishlist.prototype, "items", 2);
7336
8051
  Wishlist = __decorateClass([
7337
- Entity37("wishlists")
8052
+ Entity38("wishlists")
7338
8053
  ], Wishlist);
7339
8054
 
7340
8055
  // src/entities/wishlist-item.entity.ts
7341
- import { Entity as Entity38, PrimaryGeneratedColumn as PrimaryGeneratedColumn38, Column as Column38, ManyToOne as ManyToOne26, JoinColumn as JoinColumn26 } from "typeorm";
8056
+ import { Entity as Entity39, PrimaryGeneratedColumn as PrimaryGeneratedColumn39, Column as Column39, ManyToOne as ManyToOne26, JoinColumn as JoinColumn26 } from "typeorm";
7342
8057
  var WishlistItem = class {
7343
8058
  id;
7344
8059
  wishlistId;
@@ -7350,22 +8065,22 @@ var WishlistItem = class {
7350
8065
  product;
7351
8066
  };
7352
8067
  __decorateClass([
7353
- PrimaryGeneratedColumn38()
8068
+ PrimaryGeneratedColumn39()
7354
8069
  ], WishlistItem.prototype, "id", 2);
7355
8070
  __decorateClass([
7356
- Column38("int")
8071
+ Column39("int")
7357
8072
  ], WishlistItem.prototype, "wishlistId", 2);
7358
8073
  __decorateClass([
7359
- Column38("int")
8074
+ Column39("int")
7360
8075
  ], WishlistItem.prototype, "productId", 2);
7361
8076
  __decorateClass([
7362
- Column38("jsonb", { nullable: true })
8077
+ Column39("jsonb", { nullable: true })
7363
8078
  ], WishlistItem.prototype, "metadata", 2);
7364
8079
  __decorateClass([
7365
- Column38({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
8080
+ Column39({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7366
8081
  ], WishlistItem.prototype, "createdAt", 2);
7367
8082
  __decorateClass([
7368
- Column38({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
8083
+ Column39({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
7369
8084
  ], WishlistItem.prototype, "updatedAt", 2);
7370
8085
  __decorateClass([
7371
8086
  ManyToOne26(() => Wishlist, (w) => w.items, { onDelete: "CASCADE" }),
@@ -7376,9 +8091,45 @@ __decorateClass([
7376
8091
  JoinColumn26({ name: "productId" })
7377
8092
  ], WishlistItem.prototype, "product", 2);
7378
8093
  WishlistItem = __decorateClass([
7379
- Entity38("wishlist_items")
8094
+ Entity39("wishlist_items")
7380
8095
  ], WishlistItem);
7381
8096
 
8097
+ // src/entities/llm-agent-knowledge-document.entity.ts
8098
+ import { Entity as Entity40, PrimaryGeneratedColumn as PrimaryGeneratedColumn40, Column as Column40, ManyToOne as ManyToOne27, JoinColumn as JoinColumn27, Index as Index2, Unique as Unique2 } from "typeorm";
8099
+ var LlmAgentKnowledgeDocument = class {
8100
+ id;
8101
+ agentId;
8102
+ documentId;
8103
+ createdAt;
8104
+ agent;
8105
+ document;
8106
+ };
8107
+ __decorateClass([
8108
+ PrimaryGeneratedColumn40()
8109
+ ], LlmAgentKnowledgeDocument.prototype, "id", 2);
8110
+ __decorateClass([
8111
+ Column40("int")
8112
+ ], LlmAgentKnowledgeDocument.prototype, "agentId", 2);
8113
+ __decorateClass([
8114
+ Column40("int")
8115
+ ], LlmAgentKnowledgeDocument.prototype, "documentId", 2);
8116
+ __decorateClass([
8117
+ Column40({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
8118
+ ], LlmAgentKnowledgeDocument.prototype, "createdAt", 2);
8119
+ __decorateClass([
8120
+ ManyToOne27(() => LlmAgent, { onDelete: "CASCADE" }),
8121
+ JoinColumn27({ name: "agentId" })
8122
+ ], LlmAgentKnowledgeDocument.prototype, "agent", 2);
8123
+ __decorateClass([
8124
+ ManyToOne27(() => KnowledgeBaseDocument, { onDelete: "CASCADE" }),
8125
+ JoinColumn27({ name: "documentId" })
8126
+ ], LlmAgentKnowledgeDocument.prototype, "document", 2);
8127
+ LlmAgentKnowledgeDocument = __decorateClass([
8128
+ Entity40("llm_agent_knowledge_documents"),
8129
+ Unique2("UQ_llm_agent_knowledge_agent_document", ["agentId", "documentId"]),
8130
+ Index2("IDX_llm_agent_knowledge_agent", ["agentId"])
8131
+ ], LlmAgentKnowledgeDocument);
8132
+
7382
8133
  // src/entities/index.ts
7383
8134
  var CMS_ENTITY_MAP = {
7384
8135
  users: User,
@@ -7418,7 +8169,9 @@ var CMS_ENTITY_MAP = {
7418
8169
  carts: Cart,
7419
8170
  cart_items: CartItem,
7420
8171
  wishlists: Wishlist,
7421
- wishlist_items: WishlistItem
8172
+ wishlist_items: WishlistItem,
8173
+ llm_agents: LlmAgent,
8174
+ llm_agent_knowledge_documents: LlmAgentKnowledgeDocument
7422
8175
  };
7423
8176
 
7424
8177
  // src/auth/permission-entities.ts
@@ -7757,6 +8510,13 @@ function getNextAuthOptions(config) {
7757
8510
 
7758
8511
  // src/api/crud.ts
7759
8512
  import { Brackets, ILike as ILike2, MoreThan as MoreThan2 } from "typeorm";
8513
+ var CRUD_LOG = "[cms-crud]";
8514
+ function logCrudClientError(op, detail) {
8515
+ console.warn(CRUD_LOG, op, detail);
8516
+ }
8517
+ function logCrudServerError(op, detail) {
8518
+ console.error(CRUD_LOG, op, detail);
8519
+ }
7760
8520
  var DATE_COLUMN_TYPES = /* @__PURE__ */ new Set([
7761
8521
  "date",
7762
8522
  "datetime",
@@ -7868,6 +8628,13 @@ function createCrudHandler(dataSource, entityMap, options) {
7868
8628
  if (authError) return authError;
7869
8629
  const entity = entityMap[resource];
7870
8630
  if (!resource || !entity) {
8631
+ logCrudClientError("GET list", {
8632
+ reason: "invalid_resource",
8633
+ resource,
8634
+ hasEntity: Boolean(entity),
8635
+ entityMapHasLlmAgents: Boolean(entityMap.llm_agents),
8636
+ entityMapKeyCount: Object.keys(entityMap).length
8637
+ });
7871
8638
  return json({ error: "Invalid resource" }, { status: 400 });
7872
8639
  }
7873
8640
  const { searchParams } = new URL(req.url);
@@ -8075,12 +8842,22 @@ function createCrudHandler(dataSource, entityMap, options) {
8075
8842
  }
8076
8843
  }
8077
8844
  where = mergeDeletedFalseWhere(repo, where);
8078
- const [data, total] = await repo.findAndCount({
8079
- skip,
8080
- take: limit,
8081
- order: { [sortField]: sortOrder },
8082
- where
8083
- });
8845
+ let data;
8846
+ let total;
8847
+ try {
8848
+ const r = await repo.findAndCount({
8849
+ skip,
8850
+ take: limit,
8851
+ order: { [sortField]: sortOrder },
8852
+ where
8853
+ });
8854
+ data = r[0];
8855
+ total = r[1];
8856
+ } catch (err) {
8857
+ const message = err instanceof Error ? err.message : String(err);
8858
+ logCrudServerError("GET list query failed", { resource, sortField, sortOrder, message });
8859
+ throw err;
8860
+ }
8084
8861
  return json({ total, page, limit, totalPages: Math.ceil(total / limit), data });
8085
8862
  },
8086
8863
  async POST(req, resource) {
@@ -8088,12 +8865,25 @@ function createCrudHandler(dataSource, entityMap, options) {
8088
8865
  if (authError) return authError;
8089
8866
  const entity = entityMap[resource];
8090
8867
  if (!resource || !entity) {
8868
+ logCrudClientError("POST create", {
8869
+ reason: "invalid_resource",
8870
+ resource,
8871
+ hasEntity: Boolean(entity),
8872
+ entityMapHasLlmAgents: Boolean(entityMap.llm_agents)
8873
+ });
8091
8874
  return json({ error: "Invalid resource" }, { status: 400 });
8092
8875
  }
8093
- const body = await req.json();
8094
- if (!body || typeof body !== "object" || Object.keys(body).length === 0) {
8876
+ const rawPostBody = await req.json();
8877
+ if (!rawPostBody || typeof rawPostBody !== "object" || Object.keys(rawPostBody).length === 0) {
8878
+ logCrudClientError("POST create", {
8879
+ reason: "invalid_request_payload",
8880
+ resource,
8881
+ rawType: rawPostBody == null ? "nullish" : typeof rawPostBody,
8882
+ keyCount: rawPostBody && typeof rawPostBody === "object" ? Object.keys(rawPostBody).length : 0
8883
+ });
8095
8884
  return json({ error: "Invalid request payload" }, { status: 400 });
8096
8885
  }
8886
+ const body = rawPostBody;
8097
8887
  if (resource === "media") {
8098
8888
  const b = body;
8099
8889
  const kind = b.kind === "folder" ? "folder" : "file";
@@ -8127,8 +8917,24 @@ function createCrudHandler(dataSource, entityMap, options) {
8127
8917
  }
8128
8918
  }
8129
8919
  const repo = dataSource.getRepository(entity);
8130
- sanitizeBodyForEntity(repo, body);
8131
- const created = await repo.save(repo.create(body));
8920
+ const persistBody = resource === "media" ? body : pickColumnUpdates(repo, body);
8921
+ if (resource !== "media" && Object.keys(persistBody).length === 0) {
8922
+ logCrudClientError("POST create", {
8923
+ reason: "no_scalar_columns_after_pick",
8924
+ resource,
8925
+ incomingKeys: Object.keys(body)
8926
+ });
8927
+ return json({ error: "Invalid request payload" }, { status: 400 });
8928
+ }
8929
+ sanitizeBodyForEntity(repo, persistBody);
8930
+ let created;
8931
+ try {
8932
+ created = await repo.save(repo.create(persistBody));
8933
+ } catch (err) {
8934
+ const message = err instanceof Error ? err.message : String(err);
8935
+ logCrudServerError("POST create save failed", { resource, message, persistKeys: Object.keys(persistBody) });
8936
+ throw err;
8937
+ }
8132
8938
  if (resource === "contacts") {
8133
8939
  await syncContactRowToErp(created);
8134
8940
  }
@@ -8143,6 +8949,7 @@ function createCrudHandler(dataSource, entityMap, options) {
8143
8949
  if (authError) return authError;
8144
8950
  const entity = entityMap[resource];
8145
8951
  if (!resource || !entity) {
8952
+ logCrudClientError("GET_METADATA", { reason: "invalid_resource", resource });
8146
8953
  return json({ error: "Invalid resource" }, { status: 400 });
8147
8954
  }
8148
8955
  const repo = dataSource.getRepository(entity);
@@ -8174,11 +8981,18 @@ function createCrudHandler(dataSource, entityMap, options) {
8174
8981
  if (authError) return authError;
8175
8982
  const entity = entityMap[resource];
8176
8983
  if (!resource || !entity) {
8984
+ logCrudClientError("BULK_POST", { reason: "invalid_resource", resource });
8177
8985
  return json({ error: "Invalid resource" }, { status: 400 });
8178
8986
  }
8179
8987
  const body = await req.json();
8180
8988
  const { records, upsertKey = "id" } = body;
8181
8989
  if (!Array.isArray(records) || records.length === 0) {
8990
+ logCrudClientError("BULK_POST", {
8991
+ reason: "records_required",
8992
+ resource,
8993
+ recordsIsArray: Array.isArray(records),
8994
+ recordCount: Array.isArray(records) ? records.length : 0
8995
+ });
8182
8996
  return json({ error: "Records array is required" }, { status: 400 });
8183
8997
  }
8184
8998
  const repo = dataSource.getRepository(entity);
@@ -8197,6 +9011,7 @@ function createCrudHandler(dataSource, entityMap, options) {
8197
9011
  });
8198
9012
  } catch (error) {
8199
9013
  const message = error instanceof Error ? error.message : "Bulk import failed";
9014
+ logCrudClientError("BULK_POST upsert failed", { resource, upsertKey, message });
8200
9015
  return json({ error: message }, { status: 400 });
8201
9016
  }
8202
9017
  },
@@ -8205,6 +9020,7 @@ function createCrudHandler(dataSource, entityMap, options) {
8205
9020
  if (authError) return authError;
8206
9021
  const entity = entityMap[resource];
8207
9022
  if (!resource || !entity) {
9023
+ logCrudClientError("GET_EXPORT", { reason: "invalid_resource", resource });
8208
9024
  return json({ error: "Invalid resource" }, { status: 400 });
8209
9025
  }
8210
9026
  const { searchParams } = new URL(req.url);
@@ -8259,7 +9075,10 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
8259
9075
  const authError = await authz(req, resource, "read");
8260
9076
  if (authError) return authError;
8261
9077
  const entity = entityMap[resource];
8262
- if (!entity) return json({ error: "Invalid resource" }, { status: 400 });
9078
+ if (!entity) {
9079
+ logCrudClientError("GET by id", { reason: "invalid_resource", resource, id });
9080
+ return json({ error: "Invalid resource" }, { status: 400 });
9081
+ }
8263
9082
  const repo = dataSource.getRepository(entity);
8264
9083
  if (resource === "orders") {
8265
9084
  const order = await repo.findOne({
@@ -8318,7 +9137,10 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
8318
9137
  const authError = await authz(req, resource, "update");
8319
9138
  if (authError) return authError;
8320
9139
  const entity = entityMap[resource];
8321
- if (!entity) return json({ error: "Invalid resource" }, { status: 400 });
9140
+ if (!entity) {
9141
+ logCrudClientError("PUT by id", { reason: "invalid_resource", resource, id });
9142
+ return json({ error: "Invalid resource" }, { status: 400 });
9143
+ }
8322
9144
  const rawBody = await req.json();
8323
9145
  const repo = dataSource.getRepository(entity);
8324
9146
  const numericId = Number(id);
@@ -8431,7 +9253,10 @@ function createCrudByIdHandler(dataSource, entityMap, options) {
8431
9253
  const authError = await authz(req, resource, "delete");
8432
9254
  if (authError) return authError;
8433
9255
  const entity = entityMap[resource];
8434
- if (!entity) return json({ error: "Invalid resource" }, { status: 400 });
9256
+ if (!entity) {
9257
+ logCrudClientError("DELETE by id", { reason: "invalid_resource", resource, id });
9258
+ return json({ error: "Invalid resource" }, { status: 400 });
9259
+ }
8435
9260
  const repo = dataSource.getRepository(entity);
8436
9261
  const numericId = Number(id);
8437
9262
  if (entityHasSoftDelete(repo)) {
@@ -8593,6 +9418,560 @@ function createUserAuthApiRouter(config) {
8593
9418
  };
8594
9419
  }
8595
9420
 
9421
+ // src/api/llm-agent-knowledge-handlers.ts
9422
+ import { In as In2 } from "typeorm";
9423
+ var INGEST_CHUNK_CHARS = 900;
9424
+ var MAX_CHUNKS_PER_UPLOAD = 400;
9425
+ var EMBED_CONCURRENCY = 5;
9426
+ var MAX_PDF_BYTES = 25 * 1024 * 1024;
9427
+ var TEXT_FILE_TYPES = /* @__PURE__ */ new Set(["text/plain", "text/markdown", "application/json"]);
9428
+ var KB_LOG = "[llm-agent-knowledge]";
9429
+ function logKbPipeline(step, meta) {
9430
+ console.info(`${KB_LOG} pipeline`, { step, ...meta });
9431
+ }
9432
+ function llmEmbedDebug() {
9433
+ const v = process.env.LLM_EMBED_DEBUG?.toLowerCase();
9434
+ return v === "1" || v === "true" || v === "yes";
9435
+ }
9436
+ function isPdfUpload(mime, fileName) {
9437
+ if (mime === "application/pdf") return true;
9438
+ const n = fileName.toLowerCase();
9439
+ return n.endsWith(".pdf");
9440
+ }
9441
+ async function extractTextFromPdf(buffer) {
9442
+ const pdfParse = await import("pdf-parse");
9443
+ const data = await pdfParse(buffer);
9444
+ return (data?.text ?? "").trim();
9445
+ }
9446
+ async function loadChunksMissingEmbeddings(dataSource, documentId, slug) {
9447
+ const rows = await dataSource.query(
9448
+ `SELECT id, content FROM knowledge_base_chunks WHERE "documentId" = $1 AND embedding IS NULL ORDER BY "chunkIndex" ASC`,
9449
+ [documentId]
9450
+ );
9451
+ const list = rows ?? [];
9452
+ logKbPipeline("07_query_chunks_missing_embedding", {
9453
+ slug,
9454
+ documentId,
9455
+ missingEmbeddingCount: list.length
9456
+ });
9457
+ return list;
9458
+ }
9459
+ async function writeEmbeddingsConcurrent(dataSource, embed, chunks, concurrency, slug) {
9460
+ let next = 0;
9461
+ let written = 0;
9462
+ let failed = 0;
9463
+ let skippedEmpty = 0;
9464
+ logKbPipeline("09_embedding_workers_start", {
9465
+ slug,
9466
+ chunkCount: chunks.length,
9467
+ concurrency: Math.max(1, Math.min(concurrency, chunks.length))
9468
+ });
9469
+ async function worker() {
9470
+ for (; ; ) {
9471
+ const i = next++;
9472
+ if (i >= chunks.length) return;
9473
+ const c = chunks[i];
9474
+ try {
9475
+ const emb = await embed(c.content);
9476
+ if (emb?.length) {
9477
+ const vectorStr = "[" + emb.join(",") + "]";
9478
+ await dataSource.query(
9479
+ `UPDATE knowledge_base_chunks SET embedding = $1::vector WHERE id = $2`,
9480
+ [vectorStr, c.id]
9481
+ );
9482
+ written++;
9483
+ } else {
9484
+ skippedEmpty++;
9485
+ if (llmEmbedDebug()) {
9486
+ console.warn(`${KB_LOG} embed() returned empty vector`, { chunkId: c.id });
9487
+ }
9488
+ }
9489
+ } catch (err) {
9490
+ failed++;
9491
+ console.error(`${KB_LOG} embedding DB update failed`, {
9492
+ chunkId: c.id,
9493
+ err: err instanceof Error ? err.message : String(err)
9494
+ });
9495
+ }
9496
+ }
9497
+ }
9498
+ const n = Math.max(1, Math.min(concurrency, chunks.length));
9499
+ await Promise.all(Array.from({ length: n }, () => worker()));
9500
+ const summary = {
9501
+ chunkCount: chunks.length,
9502
+ written,
9503
+ failed,
9504
+ skippedEmpty
9505
+ };
9506
+ if (skippedEmpty > 0 && written === 0) {
9507
+ summary.hint = "embed() returned empty vectors \u2014 see [LLM embed] / [LLM embed HF] logs (OpenAI gateway vs @huggingface/inference + legacy HTTP).";
9508
+ }
9509
+ logKbPipeline("10_embedding_workers_finished", { slug, ...summary });
9510
+ if (failed > 0 || skippedEmpty > 0 && written === 0) {
9511
+ console.error(`${KB_LOG} embedding pass finished with issues`, summary);
9512
+ }
9513
+ return { written, failed };
9514
+ }
9515
+ function splitIntoChunks(text, maxLen) {
9516
+ const t = text.trim();
9517
+ if (!t) return [];
9518
+ const chunks = [];
9519
+ for (let i = 0; i < t.length; i += maxLen) {
9520
+ chunks.push(t.slice(i, i + maxLen));
9521
+ }
9522
+ return chunks;
9523
+ }
9524
+ async function findAgentBySlug(dataSource, llmAgents, slug) {
9525
+ const repo = dataSource.getRepository(llmAgents);
9526
+ return repo.findOne({
9527
+ where: { slug, deleted: false }
9528
+ });
9529
+ }
9530
+ function createLlmAgentKnowledgeHandlers(config) {
9531
+ const { dataSource, entityMap, getCms, json, requireAuth, requireEntityPermission } = config;
9532
+ const kbDoc = entityMap.knowledge_base_documents;
9533
+ const kbChunk = entityMap.knowledge_base_chunks;
9534
+ const llmAgents = entityMap.llm_agents;
9535
+ const junction = entityMap.llm_agent_knowledge_documents;
9536
+ if (!kbDoc || !kbChunk || !llmAgents || !junction) {
9537
+ return null;
9538
+ }
9539
+ async function gate(req, action) {
9540
+ const a = await requireAuth(req);
9541
+ if (a) return a;
9542
+ if (requireEntityPermission) {
9543
+ const pe = await requireEntityPermission(req, "llm_agents", action);
9544
+ if (pe) return pe;
9545
+ }
9546
+ return null;
9547
+ }
9548
+ async function runEmbeddingPass(slug, savedChunks) {
9549
+ let embeddingsWritten = 0;
9550
+ let embeddingsFailed = 0;
9551
+ try {
9552
+ logKbPipeline("08_resolve_llm_plugin", { slug, chunkCount: savedChunks.length });
9553
+ const cms = await getCms();
9554
+ const llm = cms.getPlugin("llm");
9555
+ if (llm?.embed && savedChunks.length > 0) {
9556
+ logKbPipeline("08b_embed_fn_available", {
9557
+ slug,
9558
+ chunkCount: savedChunks.length,
9559
+ firstChunkId: savedChunks[0]?.id,
9560
+ lastChunkId: savedChunks[savedChunks.length - 1]?.id
9561
+ });
9562
+ const embedBound = (text) => llm.embed(text);
9563
+ const { written, failed } = await writeEmbeddingsConcurrent(
9564
+ dataSource,
9565
+ embedBound,
9566
+ savedChunks,
9567
+ EMBED_CONCURRENCY,
9568
+ slug
9569
+ );
9570
+ embeddingsWritten = written;
9571
+ embeddingsFailed = failed;
9572
+ } else {
9573
+ logKbPipeline("08c_embed_skipped", {
9574
+ slug,
9575
+ hasLlmPlugin: !!llm,
9576
+ hasEmbed: typeof llm?.embed === "function",
9577
+ chunkCount: savedChunks.length,
9578
+ reason: savedChunks.length === 0 ? "no_chunks" : !llm ? "no_llm_plugin" : "no_embed_method"
9579
+ });
9580
+ console.error(`${KB_LOG} embeddings skipped`, {
9581
+ slug,
9582
+ hasLlmPlugin: !!llm,
9583
+ hasEmbed: typeof llm?.embed === "function",
9584
+ chunkCount: savedChunks.length,
9585
+ hint: !llm || typeof llm.embed !== "function" ? "LLM plugin missing or no embed(); check LLM_GATEWAY_URL + LLM_API_KEY so llm plugin initializes." : void 0
9586
+ });
9587
+ }
9588
+ } catch (embErr) {
9589
+ const detail = embErr instanceof Error ? embErr.message : String(embErr);
9590
+ logKbPipeline("08d_embed_pass_exception", { slug, detail });
9591
+ console.error(`${KB_LOG} embedding step threw before/during batch`, { slug, detail, embErr });
9592
+ return {
9593
+ embeddingsWritten: 0,
9594
+ embeddingsFailed: savedChunks.length,
9595
+ embedError: detail
9596
+ };
9597
+ }
9598
+ return { embeddingsWritten, embeddingsFailed };
9599
+ }
9600
+ return {
9601
+ async list(req, slug) {
9602
+ const denied = await gate(req, "read");
9603
+ if (denied) return denied;
9604
+ try {
9605
+ const agent = await findAgentBySlug(dataSource, llmAgents, slug);
9606
+ if (!agent) return json({ error: "Agent not found" }, { status: 404 });
9607
+ const linkRepo = dataSource.getRepository(junction);
9608
+ const links = await linkRepo.find({ where: { agentId: agent.id } });
9609
+ const docIds = [...new Set(links.map((l) => l.documentId))];
9610
+ if (docIds.length === 0) return json({ documents: [] });
9611
+ const docRepo = dataSource.getRepository(kbDoc);
9612
+ const docs = await docRepo.find({ where: { id: In2(docIds) } });
9613
+ const byId = new Map(docs.map((d) => [d.id, d]));
9614
+ const documents = docIds.map((id) => {
9615
+ const d = byId.get(id);
9616
+ return d ? { id: d.id, name: d.name } : null;
9617
+ }).filter(Boolean);
9618
+ return json({ documents });
9619
+ } catch (err) {
9620
+ const msg = err instanceof Error ? err.message : "Failed to list knowledge";
9621
+ return json({ error: msg }, { status: 500 });
9622
+ }
9623
+ },
9624
+ async post(req, slug) {
9625
+ const denied = await gate(req, "update");
9626
+ if (denied) return denied;
9627
+ try {
9628
+ const ct0 = req.headers.get("content-type") || "";
9629
+ logKbPipeline("01_request", { slug, contentType: ct0.slice(0, 80) });
9630
+ const agent = await findAgentBySlug(dataSource, llmAgents, slug);
9631
+ if (!agent) return json({ error: "Agent not found" }, { status: 404 });
9632
+ logKbPipeline("02_agent_loaded", { slug, agentId: agent.id });
9633
+ let name = "";
9634
+ let text = "";
9635
+ let sourceUrl = null;
9636
+ let existingDocumentId = null;
9637
+ const ct = req.headers.get("content-type") || "";
9638
+ if (ct.includes("application/json")) {
9639
+ const body = await req.json();
9640
+ existingDocumentId = typeof body?.documentId === "number" && Number.isFinite(body.documentId) ? body.documentId : null;
9641
+ name = (body?.name ?? "").trim();
9642
+ text = (body?.text ?? "").trim();
9643
+ sourceUrl = typeof body?.sourceUrl === "string" && body.sourceUrl.trim() ? body.sourceUrl.trim() : null;
9644
+ logKbPipeline("03_body_parsed", {
9645
+ slug,
9646
+ mode: "json",
9647
+ existingDocumentId,
9648
+ nameLen: name.length,
9649
+ textChars: text.length,
9650
+ hasSourceUrl: !!sourceUrl
9651
+ });
9652
+ } else if (ct.includes("multipart/form-data")) {
9653
+ const form = await req.formData();
9654
+ name = form.get("name")?.trim() ?? "";
9655
+ text = form.get("text")?.trim() ?? "";
9656
+ const file = form.get("file");
9657
+ if (file && typeof file !== "string" && "arrayBuffer" in file) {
9658
+ const f = file;
9659
+ const mime = (f.type || "").split(";")[0].trim().toLowerCase();
9660
+ const buf = Buffer.from(await f.arrayBuffer());
9661
+ logKbPipeline("03_body_parsed", {
9662
+ slug,
9663
+ mode: "multipart",
9664
+ fileName: f.name || "(no name)",
9665
+ mime,
9666
+ fileBytes: buf.length
9667
+ });
9668
+ if (TEXT_FILE_TYPES.has(mime)) {
9669
+ const decoded = buf.toString("utf8");
9670
+ if (!text) text = decoded;
9671
+ logKbPipeline("04_file_decoded_text", { slug, mime, textChars: text.length });
9672
+ } else if (isPdfUpload(mime, f.name || "")) {
9673
+ if (buf.length > MAX_PDF_BYTES) {
9674
+ return json(
9675
+ { error: `PDF too large (max ${Math.floor(MAX_PDF_BYTES / (1024 * 1024))}MB)` },
9676
+ { status: 413 }
9677
+ );
9678
+ }
9679
+ try {
9680
+ logKbPipeline("04_pdf_extract_start", { slug, fileBytes: buf.length });
9681
+ const extracted = await extractTextFromPdf(buf);
9682
+ if (!text) text = extracted;
9683
+ logKbPipeline("04_pdf_extract_done", { slug, textChars: text.length });
9684
+ } catch {
9685
+ return json(
9686
+ { error: "Could not read PDF text (file may be encrypted, corrupt, or image-only)" },
9687
+ { status: 422 }
9688
+ );
9689
+ }
9690
+ } else {
9691
+ return json(
9692
+ {
9693
+ error: "Unsupported file type; use text/plain, text/markdown, application/json, or application/pdf"
9694
+ },
9695
+ { status: 415 }
9696
+ );
9697
+ }
9698
+ if (!name && f.name) name = f.name.replace(/\.[^/.]+$/, "") || f.name;
9699
+ } else {
9700
+ logKbPipeline("03_body_parsed", { slug, mode: "multipart", hasFile: false, textChars: text.length });
9701
+ }
9702
+ } else {
9703
+ return json({ error: "Use application/json or multipart/form-data" }, { status: 400 });
9704
+ }
9705
+ const linkRepo = dataSource.getRepository(junction);
9706
+ if (existingDocumentId != null) {
9707
+ logKbPipeline("05_branch", { slug, branch: "link_existing_document", documentId: existingDocumentId });
9708
+ const docRepo2 = dataSource.getRepository(kbDoc);
9709
+ const existing = await docRepo2.findOne({ where: { id: existingDocumentId } });
9710
+ if (!existing) return json({ error: "documentId not found" }, { status: 404 });
9711
+ const dup2 = await linkRepo.findOne({
9712
+ where: { agentId: agent.id, documentId: existingDocumentId }
9713
+ });
9714
+ if (!dup2) {
9715
+ await linkRepo.save(linkRepo.create({ agentId: agent.id, documentId: existingDocumentId }));
9716
+ logKbPipeline("06_junction_link_created", {
9717
+ slug,
9718
+ agentId: agent.id,
9719
+ documentId: existingDocumentId
9720
+ });
9721
+ } else {
9722
+ logKbPipeline("06_junction_link_exists", {
9723
+ slug,
9724
+ agentId: agent.id,
9725
+ documentId: existingDocumentId
9726
+ });
9727
+ }
9728
+ const chunkRepo2 = dataSource.getRepository(kbChunk);
9729
+ const docRow = existing;
9730
+ const chunkCount = await chunkRepo2.count({ where: { documentId: existingDocumentId } });
9731
+ logKbPipeline("06b_chunks_existing_count", {
9732
+ slug,
9733
+ documentId: existingDocumentId,
9734
+ chunkCount
9735
+ });
9736
+ let chunksToEmbed = [];
9737
+ let chunksCreated = 0;
9738
+ if (chunkCount === 0) {
9739
+ const text2 = (docRow.content ?? "").trim();
9740
+ if (!text2) {
9741
+ logKbPipeline("07_ingest_aborted_empty_document", { slug, documentId: existingDocumentId });
9742
+ return json({
9743
+ documentId: existingDocumentId,
9744
+ linked: true,
9745
+ created: false,
9746
+ chunkCount: 0,
9747
+ embeddingsWritten: 0,
9748
+ embeddingsFailed: 0,
9749
+ warning: "Document has no text content; add content then attach again to build chunks and embeddings."
9750
+ });
9751
+ }
9752
+ const parts2 = splitIntoChunks(text2, INGEST_CHUNK_CHARS);
9753
+ if (parts2.length > MAX_CHUNKS_PER_UPLOAD) {
9754
+ return json(
9755
+ {
9756
+ error: `Document is too large for one ingest (${parts2.length} chunks; max ${MAX_CHUNKS_PER_UPLOAD}). Split into smaller files.`
9757
+ },
9758
+ { status: 413 }
9759
+ );
9760
+ }
9761
+ logKbPipeline("07_chunk_split", {
9762
+ slug,
9763
+ documentId: existingDocumentId,
9764
+ partCount: parts2.length,
9765
+ maxChunkChars: INGEST_CHUNK_CHARS,
9766
+ totalChars: text2.length
9767
+ });
9768
+ const now2 = /* @__PURE__ */ new Date();
9769
+ const chunkRows2 = parts2.map(
9770
+ (content, i) => chunkRepo2.create({
9771
+ documentId: existingDocumentId,
9772
+ content,
9773
+ chunkIndex: i,
9774
+ createdAt: now2
9775
+ })
9776
+ );
9777
+ const savedList2 = await chunkRepo2.save(chunkRows2);
9778
+ chunksCreated = savedList2.length;
9779
+ chunksToEmbed = savedList2.map((row, i) => ({
9780
+ id: row.id,
9781
+ content: parts2[i]
9782
+ }));
9783
+ logKbPipeline("07b_chunks_persisted", {
9784
+ slug,
9785
+ documentId: existingDocumentId,
9786
+ rowsInserted: chunksCreated
9787
+ });
9788
+ } else {
9789
+ chunksToEmbed = await loadChunksMissingEmbeddings(dataSource, existingDocumentId, slug);
9790
+ if (chunksToEmbed.length === 0) {
9791
+ logKbPipeline("08_skip_embed_all_chunks_have_vectors", {
9792
+ slug,
9793
+ documentId: existingDocumentId,
9794
+ existingChunkCount: chunkCount
9795
+ });
9796
+ }
9797
+ }
9798
+ const embedResult2 = chunksToEmbed.length > 0 ? await runEmbeddingPass(slug, chunksToEmbed) : { embeddingsWritten: 0, embeddingsFailed: 0 };
9799
+ if (embedResult2.embedError) {
9800
+ logKbPipeline("11_response", {
9801
+ slug,
9802
+ branch: "link",
9803
+ documentId: existingDocumentId,
9804
+ ok: false,
9805
+ embeddingError: true
9806
+ });
9807
+ return json(
9808
+ {
9809
+ documentId: existingDocumentId,
9810
+ linked: true,
9811
+ created: false,
9812
+ chunkCount: chunkCount + chunksCreated,
9813
+ chunksCreated,
9814
+ embeddingAttempted: true,
9815
+ embeddingsWritten: 0,
9816
+ embeddingsFailed: chunksToEmbed.length,
9817
+ warning: "Document linked; embedding step failed. Fix LLM/embed config and attach again (or unlink and re-attach) to retry NULL embeddings.",
9818
+ detail: embedResult2.embedError
9819
+ },
9820
+ { status: 201 }
9821
+ );
9822
+ }
9823
+ logKbPipeline("11_response", {
9824
+ slug,
9825
+ branch: "link",
9826
+ documentId: existingDocumentId,
9827
+ ok: true,
9828
+ chunkCount: chunkCount + chunksCreated,
9829
+ chunksCreated,
9830
+ chunksQueuedForEmbedding: chunksToEmbed.length,
9831
+ embeddingsWritten: embedResult2.embeddingsWritten,
9832
+ embeddingsFailed: embedResult2.embeddingsFailed
9833
+ });
9834
+ return json({
9835
+ documentId: existingDocumentId,
9836
+ linked: true,
9837
+ created: false,
9838
+ chunkCount: chunkCount + chunksCreated,
9839
+ chunksCreated: chunksCreated || void 0,
9840
+ chunksQueuedForEmbedding: chunksToEmbed.length,
9841
+ embeddingAttempted: chunksToEmbed.length > 0,
9842
+ embeddingsWritten: embedResult2.embeddingsWritten,
9843
+ embeddingsFailed: embedResult2.embeddingsFailed
9844
+ });
9845
+ }
9846
+ logKbPipeline("05_branch", { slug, branch: "new_upload_ingest" });
9847
+ if (!text) return json({ error: "text or file with text content is required" }, { status: 400 });
9848
+ if (!name) name = "Untitled";
9849
+ const parts = splitIntoChunks(text, INGEST_CHUNK_CHARS);
9850
+ if (parts.length === 0) {
9851
+ return json({ error: "text or file with text content is required" }, { status: 400 });
9852
+ }
9853
+ if (parts.length > MAX_CHUNKS_PER_UPLOAD) {
9854
+ return json(
9855
+ {
9856
+ error: `Document is too large for one upload (${parts.length} chunks; max ${MAX_CHUNKS_PER_UPLOAD}). Split into smaller files.`
9857
+ },
9858
+ { status: 413 }
9859
+ );
9860
+ }
9861
+ logKbPipeline("07_chunk_split", {
9862
+ slug,
9863
+ partCount: parts.length,
9864
+ maxChunkChars: INGEST_CHUNK_CHARS,
9865
+ totalChars: text.length,
9866
+ documentName: name
9867
+ });
9868
+ const docRepo = dataSource.getRepository(kbDoc);
9869
+ const chunkRepo = dataSource.getRepository(kbChunk);
9870
+ const now = /* @__PURE__ */ new Date();
9871
+ const doc = await docRepo.save(
9872
+ docRepo.create({ name, content: text, sourceUrl, createdAt: now, updatedAt: now })
9873
+ );
9874
+ const docId = doc.id;
9875
+ logKbPipeline("06_knowledge_document_saved", {
9876
+ slug,
9877
+ documentId: docId,
9878
+ name,
9879
+ contentChars: text.length,
9880
+ hasSourceUrl: !!sourceUrl
9881
+ });
9882
+ const chunkRows = parts.map(
9883
+ (content, i) => chunkRepo.create({ documentId: docId, content, chunkIndex: i, createdAt: now })
9884
+ );
9885
+ const savedList = await chunkRepo.save(chunkRows);
9886
+ const savedChunks = savedList.map(
9887
+ (row, i) => ({
9888
+ id: row.id,
9889
+ content: parts[i]
9890
+ })
9891
+ );
9892
+ logKbPipeline("07b_chunks_persisted", {
9893
+ slug,
9894
+ documentId: docId,
9895
+ rowsInserted: savedChunks.length,
9896
+ firstChunkId: savedChunks[0]?.id,
9897
+ lastChunkId: savedChunks[savedChunks.length - 1]?.id
9898
+ });
9899
+ const dup = await linkRepo.findOne({ where: { agentId: agent.id, documentId: docId } });
9900
+ if (!dup) {
9901
+ await linkRepo.save(linkRepo.create({ agentId: agent.id, documentId: docId }));
9902
+ logKbPipeline("06c_junction_link_created", { slug, agentId: agent.id, documentId: docId });
9903
+ } else {
9904
+ logKbPipeline("06c_junction_link_exists", { slug, agentId: agent.id, documentId: docId });
9905
+ }
9906
+ const embedResult = await runEmbeddingPass(slug, savedChunks);
9907
+ if (embedResult.embedError) {
9908
+ logKbPipeline("11_response", {
9909
+ slug,
9910
+ branch: "ingest",
9911
+ documentId: docId,
9912
+ ok: false,
9913
+ embeddingError: true
9914
+ });
9915
+ return json(
9916
+ {
9917
+ documentId: docId,
9918
+ chunkCount: savedChunks.length,
9919
+ embeddingAttempted: true,
9920
+ created: true,
9921
+ linked: true,
9922
+ embeddingsWritten: 0,
9923
+ embeddingsFailed: savedChunks.length,
9924
+ warning: "Document saved and linked; embedding step failed.",
9925
+ detail: embedResult.embedError
9926
+ },
9927
+ { status: 201 }
9928
+ );
9929
+ }
9930
+ logKbPipeline("11_response", {
9931
+ slug,
9932
+ branch: "ingest",
9933
+ documentId: docId,
9934
+ ok: true,
9935
+ chunkCount: savedChunks.length,
9936
+ embeddingsWritten: embedResult.embeddingsWritten,
9937
+ embeddingsFailed: embedResult.embeddingsFailed
9938
+ });
9939
+ return json({
9940
+ documentId: docId,
9941
+ chunkCount: savedChunks.length,
9942
+ embeddingAttempted: savedChunks.length > 0,
9943
+ created: true,
9944
+ linked: true,
9945
+ embeddingsWritten: embedResult.embeddingsWritten,
9946
+ embeddingsFailed: embedResult.embeddingsFailed
9947
+ });
9948
+ } catch (err) {
9949
+ const msg = err instanceof Error ? err.message : "Failed to ingest knowledge";
9950
+ const name = err instanceof Error ? err.name : "";
9951
+ logKbPipeline("99_pipeline_error", { slug, errorName: name, message: msg });
9952
+ return json({ error: msg, errorName: name || void 0 }, { status: 500 });
9953
+ }
9954
+ },
9955
+ async unlink(req, slug, documentIdStr) {
9956
+ const denied = await gate(req, "update");
9957
+ if (denied) return denied;
9958
+ const documentId = parseInt(documentIdStr, 10);
9959
+ if (!Number.isFinite(documentId)) return json({ error: "Invalid document id" }, { status: 400 });
9960
+ try {
9961
+ const agent = await findAgentBySlug(dataSource, llmAgents, slug);
9962
+ if (!agent) return json({ error: "Agent not found" }, { status: 404 });
9963
+ logKbPipeline("unlink_junction", { slug, agentId: agent.id, documentId });
9964
+ const linkRepo = dataSource.getRepository(junction);
9965
+ await linkRepo.delete({ agentId: agent.id, documentId });
9966
+ return json({ ok: true });
9967
+ } catch (err) {
9968
+ const msg = err instanceof Error ? err.message : "Failed to unlink";
9969
+ return json({ error: msg }, { status: 500 });
9970
+ }
9971
+ }
9972
+ };
9973
+ }
9974
+
8596
9975
  // src/api/message-template-admin-handlers.ts
8597
9976
  init_sms_defaults();
8598
9977
  function createSmsMessageTemplateHandlers(config) {
@@ -8842,6 +10221,48 @@ function createAdminRolesHandlers(config) {
8842
10221
  }
8843
10222
 
8844
10223
  // src/api/cms-api-handler.ts
10224
+ var KNOWLEDGE_SUFFIX = "knowledge";
10225
+ var CMS_API_LOG = "[cms-api]";
10226
+ function withLlmKnowledgeEntityFallbacks(base) {
10227
+ const keys = [
10228
+ "llm_agents",
10229
+ "llm_agent_knowledge_documents",
10230
+ "knowledge_base_documents",
10231
+ "knowledge_base_chunks"
10232
+ ];
10233
+ const patch = {};
10234
+ for (const key of keys) {
10235
+ if (!(key in base) || base[key] == null) {
10236
+ const fallback = CMS_ENTITY_MAP[key];
10237
+ if (fallback) patch[key] = fallback;
10238
+ }
10239
+ }
10240
+ const merged = Object.keys(patch).length > 0 ? { ...base, ...patch } : base;
10241
+ if (!merged.llm_agents) {
10242
+ const agent = CMS_ENTITY_MAP.llm_agents ?? LlmAgent;
10243
+ return { ...merged, llm_agents: agent };
10244
+ }
10245
+ return merged;
10246
+ }
10247
+ function matchLlmAgentKnowledgeRoute(path) {
10248
+ const p = path[0] === "api" ? path.slice(1) : path;
10249
+ if (p[0] !== "llm_agents" || p.length < 2) return null;
10250
+ const seg1 = p[1];
10251
+ if (!seg1) return null;
10252
+ if (p[2] === KNOWLEDGE_SUFFIX) {
10253
+ return {
10254
+ slug: seg1,
10255
+ documentId: p.length >= 4 ? p[3] : void 0
10256
+ };
10257
+ }
10258
+ if (seg1.endsWith(KNOWLEDGE_SUFFIX) && seg1.length > KNOWLEDGE_SUFFIX.length) {
10259
+ const slug = seg1.slice(0, -KNOWLEDGE_SUFFIX.length);
10260
+ if (!slug) return null;
10261
+ if (p.length === 2) return { slug, documentId: void 0 };
10262
+ if (p.length === 3) return { slug, documentId: p[2] };
10263
+ }
10264
+ return null;
10265
+ }
8845
10266
  var DEFAULT_EXCLUDE = /* @__PURE__ */ new Set([
8846
10267
  "users",
8847
10268
  "password_reset_tokens",
@@ -8854,14 +10275,15 @@ var DEFAULT_EXCLUDE = /* @__PURE__ */ new Set([
8854
10275
  "cart_items",
8855
10276
  "wishlists",
8856
10277
  "wishlist_items",
8857
- "message_templates"
10278
+ "message_templates",
10279
+ "llm_agent_knowledge_documents"
8858
10280
  ]);
8859
10281
  function createCmsApiHandler(config) {
8860
10282
  const {
8861
10283
  dataSource,
8862
- entityMap,
10284
+ entityMap: rawEntityMap,
8863
10285
  pathToModel = (s) => s,
8864
- crudResources = Object.keys(entityMap).filter((k) => !DEFAULT_EXCLUDE.has(k)),
10286
+ crudResources: crudResourcesOverride,
8865
10287
  getCms,
8866
10288
  userAuth: userAuthConfig,
8867
10289
  dashboard,
@@ -8878,9 +10300,13 @@ function createCmsApiHandler(config) {
8878
10300
  userProfile,
8879
10301
  settings: settingsConfig,
8880
10302
  chat: chatConfig,
10303
+ llmAgentKnowledge: llmAgentKnowledgeConfig,
8881
10304
  requireEntityPermission: userRequireEntityPermission,
8882
10305
  getSessionUser
8883
10306
  } = config;
10307
+ const entityMap = withLlmKnowledgeEntityFallbacks(rawEntityMap);
10308
+ const baseCrudResources = crudResourcesOverride ?? Object.keys(entityMap).filter((k) => !DEFAULT_EXCLUDE.has(k));
10309
+ const crudResources = entityMap.llm_agents && !baseCrudResources.includes("llm_agents") ? [...baseCrudResources, "llm_agents"] : baseCrudResources;
8884
10310
  const requireEntityPermissionEffective = userRequireEntityPermission ?? (async (_req, entity, action) => config.json({ error: "Forbidden", reason: "entity_rbac_required", entity, action }, { status: 403 }));
8885
10311
  const analytics = analyticsConfig ?? (getCms ? {
8886
10312
  json: config.json,
@@ -8985,12 +10411,25 @@ function createCmsApiHandler(config) {
8985
10411
  requireEntityPermission: requireEntityPermissionEffective
8986
10412
  });
8987
10413
  const chatHandlers = chatConfig ? createChatHandlers(chatConfig) : null;
10414
+ const llmAgentKnowledgeMerged = llmAgentKnowledgeConfig ?? (chatConfig ? {
10415
+ dataSource: chatConfig.dataSource,
10416
+ entityMap: withLlmKnowledgeEntityFallbacks(chatConfig.entityMap ?? rawEntityMap),
10417
+ getCms: chatConfig.getCms,
10418
+ json: chatConfig.json,
10419
+ requireAuth: chatConfig.requireAuth
10420
+ } : void 0);
10421
+ const llmAgentKnowledgeHandlers = llmAgentKnowledgeMerged ? createLlmAgentKnowledgeHandlers({
10422
+ ...llmAgentKnowledgeMerged,
10423
+ requireEntityPermission: requireEntityPermissionEffective
10424
+ }) : null;
8988
10425
  function resolveResource(segment) {
8989
10426
  const model = pathToModel(segment);
8990
10427
  return crudResources.includes(model) ? model : segment;
8991
10428
  }
8992
10429
  return {
8993
- async handle(method, path, req) {
10430
+ async handle(method, pathInput, req) {
10431
+ const m = typeof method === "string" ? method.toUpperCase() : "GET";
10432
+ const path = pathInput.length > 0 && pathInput[0] === "api" ? pathInput.slice(1) : pathInput;
8994
10433
  async function analyticsGate() {
8995
10434
  const a = await config.requireAuth(req);
8996
10435
  if (a) return a;
@@ -8998,86 +10437,86 @@ function createCmsApiHandler(config) {
8998
10437
  }
8999
10438
  if (path[0] === "admin" && path[1] === "roles") {
9000
10439
  if (!adminRoles) return config.json({ error: "Not found" }, { status: 404 });
9001
- if (path.length === 2 && method === "GET") return adminRoles.list();
9002
- if (path.length === 2 && method === "POST") return adminRoles.createGroup(req);
9003
- if (path.length === 3 && method === "PATCH") return adminRoles.patchGroup(req, path[2]);
9004
- if (path.length === 3 && method === "DELETE") return adminRoles.deleteGroup(path[2]);
9005
- if (path.length === 4 && path[3] === "permissions" && method === "PUT") return adminRoles.putPermissions(req, path[2]);
10440
+ if (path.length === 2 && m === "GET") return adminRoles.list();
10441
+ if (path.length === 2 && m === "POST") return adminRoles.createGroup(req);
10442
+ if (path.length === 3 && m === "PATCH") return adminRoles.patchGroup(req, path[2]);
10443
+ if (path.length === 3 && m === "DELETE") return adminRoles.deleteGroup(path[2]);
10444
+ if (path.length === 4 && path[3] === "permissions" && m === "PUT") return adminRoles.putPermissions(req, path[2]);
9006
10445
  return config.json({ error: "Not found" }, { status: 404 });
9007
10446
  }
9008
- if (path[0] === "dashboard" && path[1] === "stats" && path.length === 2 && method === "GET" && dashboardGet) {
10447
+ if (path[0] === "dashboard" && path[1] === "stats" && path.length === 2 && m === "GET" && dashboardGet) {
9009
10448
  return dashboardGet(req);
9010
10449
  }
9011
- if (path[0] === "dashboard" && path[1] === "ecommerce" && path.length === 2 && method === "GET" && ecommerceAnalyticsGet) {
10450
+ if (path[0] === "dashboard" && path[1] === "ecommerce" && path.length === 2 && m === "GET" && ecommerceAnalyticsGet) {
9012
10451
  const g = await analyticsGate();
9013
10452
  if (g) return g;
9014
10453
  return ecommerceAnalyticsGet(req);
9015
10454
  }
9016
10455
  if (path[0] === "analytics" && analyticsHandlers) {
9017
- if (path.length === 1 && method === "GET") {
10456
+ if (path.length === 1 && m === "GET") {
9018
10457
  const g = await analyticsGate();
9019
10458
  if (g) return g;
9020
10459
  return analyticsHandlers.GET(req);
9021
10460
  }
9022
- if (path.length === 2 && path[1] === "property-id" && method === "GET") {
10461
+ if (path.length === 2 && path[1] === "property-id" && m === "GET") {
9023
10462
  const g = await analyticsGate();
9024
10463
  if (g) return g;
9025
10464
  return analyticsHandlers.propertyId();
9026
10465
  }
9027
- if (path.length === 2 && path[1] === "permissions" && method === "GET") {
10466
+ if (path.length === 2 && path[1] === "permissions" && m === "GET") {
9028
10467
  const g = await analyticsGate();
9029
10468
  if (g) return g;
9030
10469
  return analyticsHandlers.permissions();
9031
10470
  }
9032
10471
  }
9033
- if (path[0] === "upload" && path.length === 1 && method === "POST" && uploadPost) return uploadPost(req);
9034
- if (path[0] === "media" && path[1] === "extract" && path.length === 3 && method === "POST" && zipExtractPost) {
10472
+ if (path[0] === "upload" && path.length === 1 && m === "POST" && uploadPost) return uploadPost(req);
10473
+ if (path[0] === "media" && path[1] === "extract" && path.length === 3 && m === "POST" && zipExtractPost) {
9035
10474
  return zipExtractPost(req, path[2]);
9036
10475
  }
9037
- if (path[0] === "blogs" && path[1] === "slug" && path.length === 3 && method === "GET" && blogBySlugGet) {
10476
+ if (path[0] === "blogs" && path[1] === "slug" && path.length === 3 && m === "GET" && blogBySlugGet) {
9038
10477
  return blogBySlugGet(req, path[2]);
9039
10478
  }
9040
- if (path[0] === "forms" && path[1] === "slug" && path.length === 3 && method === "GET" && formBySlugGet) {
10479
+ if (path[0] === "forms" && path[1] === "slug" && path.length === 3 && m === "GET" && formBySlugGet) {
9041
10480
  return formBySlugGet(req, path[2]);
9042
10481
  }
9043
10482
  if (path[0] === "form-submissions") {
9044
10483
  if (path.length === 1) {
9045
- if (method === "GET" && formSubmissionList) return formSubmissionList(req);
9046
- if (method === "POST" && formSubmissionPost) return formSubmissionPost(req);
10484
+ if (m === "GET" && formSubmissionList) return formSubmissionList(req);
10485
+ if (m === "POST" && formSubmissionPost) return formSubmissionPost(req);
9047
10486
  }
9048
- if (path.length === 2 && method === "GET" && formSubmissionGetById) return formSubmissionGetById(req, path[1]);
10487
+ if (path.length === 2 && m === "GET" && formSubmissionGetById) return formSubmissionGetById(req, path[1]);
9049
10488
  }
9050
10489
  if (path[0] === "forms" && formSaveHandlers) {
9051
- if (path.length === 1 && method === "POST") return formSaveHandlers.POST(req);
10490
+ if (path.length === 1 && m === "POST") return formSaveHandlers.POST(req);
9052
10491
  if (path.length === 2) {
9053
- if (method === "GET") return formSaveHandlers.GET(req, path[1]);
9054
- if (method === "PUT" || method === "PATCH") return formSaveHandlers.PUT(req, path[1]);
10492
+ if (m === "GET") return formSaveHandlers.GET(req, path[1]);
10493
+ if (m === "PUT" || m === "PATCH") return formSaveHandlers.PUT(req, path[1]);
9055
10494
  }
9056
10495
  }
9057
10496
  if (path[0] === "users" && usersHandlers) {
9058
10497
  if (path.length === 1) {
9059
- if (method === "GET") return usersHandlers.list(req);
9060
- if (method === "POST") return usersHandlers.create(req);
10498
+ if (m === "GET") return usersHandlers.list(req);
10499
+ if (m === "POST") return usersHandlers.create(req);
9061
10500
  }
9062
10501
  if (path.length === 2) {
9063
- if (path[1] === "avatar" && method === "POST" && avatarPost) return avatarPost(req);
9064
- if (path[1] === "profile" && method === "PUT" && profilePut) return profilePut(req);
10502
+ if (path[1] === "avatar" && m === "POST" && avatarPost) return avatarPost(req);
10503
+ if (path[1] === "profile" && m === "PUT" && profilePut) return profilePut(req);
9065
10504
  const id = path[1];
9066
- if (method === "GET") return usersHandlers.getById(req, id);
9067
- if (method === "PUT" || method === "PATCH") return usersHandlers.update(req, id);
9068
- if (method === "DELETE") return usersHandlers.delete(req, id);
10505
+ if (m === "GET") return usersHandlers.getById(req, id);
10506
+ if (m === "PUT" || m === "PATCH") return usersHandlers.update(req, id);
10507
+ if (m === "DELETE") return usersHandlers.delete(req, id);
9069
10508
  }
9070
- if (path.length === 3 && path[2] === "regenerate-invite" && method === "POST") {
10509
+ if (path.length === 3 && path[2] === "regenerate-invite" && m === "POST") {
9071
10510
  return usersHandlers.regenerateInvite(req, path[1]);
9072
10511
  }
9073
10512
  }
9074
- if (path[0] === "users" && path.length === 2 && userAuthRouter && method === "POST") {
10513
+ if (path[0] === "users" && path.length === 2 && userAuthRouter && m === "POST") {
9075
10514
  return userAuthRouter.POST(req, path[1]);
9076
10515
  }
9077
10516
  if (path[0] === "settings" && path.length === 2 && settingsHandlers) {
9078
10517
  const group = path[1];
9079
10518
  const isPublic = settingsConfig?.publicGetGroups?.includes(group);
9080
- if (method === "GET") {
10519
+ if (m === "GET") {
9081
10520
  if (!isPublic) {
9082
10521
  const a = await config.requireAuth(req);
9083
10522
  if (a) return a;
@@ -9086,22 +10525,70 @@ function createCmsApiHandler(config) {
9086
10525
  }
9087
10526
  return settingsHandlers.GET(req, group);
9088
10527
  }
9089
- if (method === "PUT") {
10528
+ if (m === "PUT") {
9090
10529
  const pe = await requireEntityPermissionEffective(req, "settings", "update");
9091
10530
  if (pe) return pe;
9092
10531
  return settingsHandlers.PUT(req, group);
9093
10532
  }
9094
10533
  }
9095
10534
  if (path[0] === "message-templates" && path[1] === "sms" && path.length === 2) {
9096
- if (method === "GET") return smsMessageTemplateHandlers.GET(req);
9097
- if (method === "PUT") return smsMessageTemplateHandlers.PUT(req);
10535
+ if (m === "GET") return smsMessageTemplateHandlers.GET(req);
10536
+ if (m === "PUT") return smsMessageTemplateHandlers.PUT(req);
10537
+ }
10538
+ if (path[0] === "llm_agents") {
10539
+ if (!entityMap.llm_agents) {
10540
+ console.error(CMS_API_LOG, "llm_agents route: entity missing after merge", {
10541
+ method: m,
10542
+ pathJoined: path.join("/"),
10543
+ entityMapKeyCount: Object.keys(entityMap).length
10544
+ });
10545
+ return config.json(
10546
+ { error: "LlmAgent entity is not registered", hint: "Ensure migrations ran and entities include LlmAgent." },
10547
+ { status: 503 }
10548
+ );
10549
+ }
10550
+ if (path.length === 1) {
10551
+ if (m === "GET") return crud.GET(req, "llm_agents");
10552
+ if (m === "POST") return crud.POST(req, "llm_agents");
10553
+ }
10554
+ if (path.length === 2 && !path[1]?.includes("knowledge")) {
10555
+ const id = path[1];
10556
+ if (m === "GET") return crudById.GET(req, "llm_agents", id);
10557
+ if (m === "PUT" || m === "PATCH") return crudById.PUT(req, "llm_agents", id);
10558
+ if (m === "DELETE") return crudById.DELETE(req, "llm_agents", id);
10559
+ }
10560
+ }
10561
+ {
10562
+ const kbMatch = matchLlmAgentKnowledgeRoute(path);
10563
+ if (kbMatch) {
10564
+ if (!llmAgentKnowledgeHandlers) {
10565
+ return config.json(
10566
+ {
10567
+ error: "LLM agent knowledge is not available",
10568
+ hint: "With chat enabled, routes usually work automatically. Otherwise pass llmAgentKnowledge. If this persists, ensure entityMap includes knowledge_base_documents, knowledge_base_chunks, llm_agent_knowledge_documents, and run migrations."
10569
+ },
10570
+ { status: 503 }
10571
+ );
10572
+ }
10573
+ const { slug, documentId } = kbMatch;
10574
+ if (m === "DELETE" && documentId != null && documentId !== "") {
10575
+ return llmAgentKnowledgeHandlers.unlink(req, slug, documentId);
10576
+ }
10577
+ if (m === "GET" && (documentId == null || documentId === "")) {
10578
+ return llmAgentKnowledgeHandlers.list(req, slug);
10579
+ }
10580
+ if (m === "POST" && (documentId == null || documentId === "")) {
10581
+ return llmAgentKnowledgeHandlers.post(req, slug);
10582
+ }
10583
+ }
9098
10584
  }
9099
10585
  if (path[0] === "chat" && chatHandlers) {
9100
- if (path.length === 2 && path[1] === "identify" && method === "POST") return chatHandlers.identify(req);
9101
- if (path.length === 4 && path[1] === "conversations" && path[3] === "messages" && method === "GET") return chatHandlers.getMessages(req, path[2]);
9102
- if (path.length === 2 && path[1] === "messages" && method === "POST") return chatHandlers.postMessage(req);
10586
+ if (path.length === 2 && path[1] === "config" && m === "GET") return chatHandlers.publicConfig(req);
10587
+ if (path.length === 2 && path[1] === "identify" && m === "POST") return chatHandlers.identify(req);
10588
+ if (path.length === 4 && path[1] === "conversations" && path[3] === "messages" && m === "GET") return chatHandlers.getMessages(req, path[2]);
10589
+ if (path.length === 2 && path[1] === "messages" && m === "POST") return chatHandlers.postMessage(req);
9103
10590
  }
9104
- if (path[0] === "orders" && path.length === 3 && path[2] === "invoice" && method === "GET" && getCms) {
10591
+ if (path[0] === "orders" && path.length === 3 && path[2] === "invoice" && m === "GET" && getCms) {
9105
10592
  const a = await config.requireAuth(req);
9106
10593
  if (a) return a;
9107
10594
  const pe = await requireEntityPermissionEffective(req, "orders", "read");
@@ -9115,17 +10602,17 @@ function createCmsApiHandler(config) {
9115
10602
  if (path[0] === "orders" && path.length === 3 && path[2] === "repost-erp" && getCms) {
9116
10603
  const a = await config.requireAuth(req);
9117
10604
  if (a) return a;
9118
- const pe = await requireEntityPermissionEffective(req, "orders", method === "GET" ? "read" : "update");
10605
+ const pe = await requireEntityPermissionEffective(req, "orders", m === "GET" ? "read" : "update");
9119
10606
  if (pe) return pe;
9120
10607
  const oid = Number(path[1]);
9121
10608
  if (!Number.isFinite(oid)) return config.json({ error: "Invalid id" }, { status: 400 });
9122
10609
  const cms = await getCms();
9123
10610
  const { isErpIntegrationEnabled: isErpIntegrationEnabled3 } = await Promise.resolve().then(() => (init_erp_config_enabled(), erp_config_enabled_exports));
9124
10611
  const enabled = await isErpIntegrationEnabled3(cms, dataSource, entityMap);
9125
- if (method === "GET") {
10612
+ if (m === "GET") {
9126
10613
  return config.json({ enabled });
9127
10614
  }
9128
- if (method === "POST") {
10615
+ if (m === "POST") {
9129
10616
  if (!enabled) return config.json({ error: "ERP integration is disabled" }, { status: 409 });
9130
10617
  const { queueErpPaidOrderForOrderId: queueErpPaidOrderForOrderId2 } = await Promise.resolve().then(() => (init_paid_order_erp(), paid_order_erp_exports));
9131
10618
  await queueErpPaidOrderForOrderId2(cms, dataSource, entityMap, oid);
@@ -9135,28 +10622,39 @@ function createCmsApiHandler(config) {
9135
10622
  }
9136
10623
  if (path.length === 0) return config.json({ error: "Not found" }, { status: 404 });
9137
10624
  const resource = resolveResource(path[0]);
9138
- if (!crudResources.includes(resource)) return config.json({ error: "Invalid resource" }, { status: 400 });
10625
+ if (!crudResources.includes(resource)) {
10626
+ console.warn(CMS_API_LOG, "generic CRUD gate: Invalid resource (not in crudResources)", {
10627
+ method: m,
10628
+ pathJoined: path.join("/"),
10629
+ pathSegments: path,
10630
+ resource,
10631
+ hasLlmAgentsEntity: Boolean(entityMap.llm_agents),
10632
+ crudResourcesHasResource: crudResources.includes(resource),
10633
+ crudResourcesLength: crudResources.length
10634
+ });
10635
+ return config.json({ error: "Invalid resource" }, { status: 400 });
10636
+ }
9139
10637
  if (path.length === 2) {
9140
- if (path[1] === "metadata" && method === "GET") {
10638
+ if (path[1] === "metadata" && m === "GET") {
9141
10639
  return crud.GET_METADATA(req, resource);
9142
10640
  }
9143
- if (path[1] === "bulk" && method === "POST") {
10641
+ if (path[1] === "bulk" && m === "POST") {
9144
10642
  return crud.BULK_POST(req, resource);
9145
10643
  }
9146
- if (path[1] === "export" && method === "GET") {
10644
+ if (path[1] === "export" && m === "GET") {
9147
10645
  return crud.GET_EXPORT(req, resource);
9148
10646
  }
9149
10647
  }
9150
10648
  if (path.length === 1) {
9151
- if (method === "GET") return crud.GET(req, resource);
9152
- if (method === "POST") return crud.POST(req, resource);
10649
+ if (m === "GET") return crud.GET(req, resource);
10650
+ if (m === "POST") return crud.POST(req, resource);
9153
10651
  return config.json({ error: "Method not allowed" }, { status: 405 });
9154
10652
  }
9155
10653
  if (path.length === 2) {
9156
10654
  const id = path[1];
9157
- if (method === "GET") return crudById.GET(req, resource, id);
9158
- if (method === "PUT" || method === "PATCH") return crudById.PUT(req, resource, id);
9159
- if (method === "DELETE") return crudById.DELETE(req, resource, id);
10655
+ if (m === "GET") return crudById.GET(req, resource, id);
10656
+ if (m === "PUT" || m === "PATCH") return crudById.PUT(req, resource, id);
10657
+ if (m === "DELETE") return crudById.DELETE(req, resource, id);
9160
10658
  return config.json({ error: "Method not allowed" }, { status: 405 });
9161
10659
  }
9162
10660
  return config.json({ error: "Not found" }, { status: 404 });
@@ -9165,7 +10663,7 @@ function createCmsApiHandler(config) {
9165
10663
  }
9166
10664
 
9167
10665
  // src/api/storefront-handlers.ts
9168
- import { In as In2, IsNull as IsNull4 } from "typeorm";
10666
+ import { In as In3, IsNull as IsNull4 } from "typeorm";
9169
10667
 
9170
10668
  // src/lib/is-valid-signup-email.ts
9171
10669
  var MAX_EMAIL = 254;
@@ -10437,7 +11935,7 @@ function createStorefrontApiHandler(config) {
10437
11935
  const previewByOrder = {};
10438
11936
  if (orderIds.length) {
10439
11937
  const oItems = await orderItemRepo().find({
10440
- where: { orderId: In2(orderIds) },
11938
+ where: { orderId: In3(orderIds) },
10441
11939
  relations: ["product"],
10442
11940
  order: { id: "ASC" }
10443
11941
  });
@@ -10601,6 +12099,7 @@ export {
10601
12099
  FormSubmission,
10602
12100
  KnowledgeBaseChunk,
10603
12101
  KnowledgeBaseDocument,
12102
+ LlmAgent,
10604
12103
  LlmService,
10605
12104
  Media,
10606
12105
  MessageTemplate,
@@ -10650,6 +12149,7 @@ export {
10650
12149
  createForgotPasswordHandler,
10651
12150
  createFormBySlugHandler,
10652
12151
  createInviteAcceptHandler,
12152
+ createLlmAgentKnowledgeHandlers,
10653
12153
  createMediaZipExtractHandler,
10654
12154
  createOtpChallenge,
10655
12155
  createSetPasswordHandler,
@@ -10683,13 +12183,17 @@ export {
10683
12183
  isZipMedia,
10684
12184
  joinRecipientsForSend,
10685
12185
  linkUnclaimedContactToUser,
12186
+ llmAgentToChatAgentOptions,
10686
12187
  llmPlugin,
10687
12188
  loadPublicThemeSettings,
10688
12189
  localStoragePlugin,
10689
12190
  mergeEmailLayoutCompanyDetails,
12191
+ mergeGuardrailsIntoSystemPrompt,
10690
12192
  mergeSeoBySlug,
10691
12193
  normalizePhoneE164,
10692
12194
  parseEmailRecipientsFromConfig,
12195
+ parseHfInferenceEmbeddingBody,
12196
+ parseLlmAgentValidationRules,
10693
12197
  paymentPlugin,
10694
12198
  permissionRowsToRecord,
10695
12199
  queueEmail,
@@ -10721,6 +12225,8 @@ export {
10721
12225
  smsPlugin,
10722
12226
  truncateText,
10723
12227
  validateSlug,
12228
+ validateUserMessageAgainstAgentRules,
12229
+ validateUserMessageAgainstStructuredRules,
10724
12230
  verifyAndConsumeOtpChallenge,
10725
12231
  verifyOtpCodeHash
10726
12232
  };