@aivue/tabular-intelligence 1.5.1 → 2.0.1
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/README.md +445 -18
- package/dist/advanced/automl.d.ts +29 -0
- package/dist/advanced/automl.d.ts.map +1 -0
- package/dist/advanced/explainability.d.ts +31 -0
- package/dist/advanced/explainability.d.ts.map +1 -0
- package/dist/advanced/featureEngineering.d.ts +28 -0
- package/dist/advanced/featureEngineering.d.ts.map +1 -0
- package/dist/advanced/index.d.ts +16 -0
- package/dist/advanced/index.d.ts.map +1 -0
- package/dist/advanced/multitable.d.ts +28 -0
- package/dist/advanced/multitable.d.ts.map +1 -0
- package/dist/advanced/privacy.d.ts +17 -0
- package/dist/advanced/privacy.d.ts.map +1 -0
- package/dist/advanced/reporting.d.ts +21 -0
- package/dist/advanced/reporting.d.ts.map +1 -0
- package/dist/advanced/statistical.d.ts +28 -0
- package/dist/advanced/statistical.d.ts.map +1 -0
- package/dist/advanced/streaming.d.ts +41 -0
- package/dist/advanced/streaming.d.ts.map +1 -0
- package/dist/advanced/timeseries.d.ts +36 -0
- package/dist/advanced/timeseries.d.ts.map +1 -0
- package/dist/advanced/versioning.d.ts +34 -0
- package/dist/advanced/versioning.d.ts.map +1 -0
- package/dist/advanced/visualization.d.ts +23 -0
- package/dist/advanced/visualization.d.ts.map +1 -0
- package/dist/composables/useTabularIntelligence.d.ts +1 -1
- package/dist/composables/useTabularIntelligence.d.ts.map +1 -1
- package/dist/index.d.ts +39 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +75 -47
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2392 -657
- package/dist/index.mjs.map +1 -1
- package/dist/preprocessing/imputation.d.ts +9 -0
- package/dist/preprocessing/imputation.d.ts.map +1 -0
- package/dist/preprocessing/outliers.d.ts +10 -0
- package/dist/preprocessing/outliers.d.ts.map +1 -0
- package/dist/quality/profiling.d.ts +22 -0
- package/dist/quality/profiling.d.ts.map +1 -0
- package/dist/types/index.d.ts +573 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
1
|
-
"use strict";Object.
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const I=require("@aivue/core"),f=require("vue");function P(s,e){if(s.length===0)return{columns:[],rowCount:0,name:e};const t=s[0];return{columns:Object.keys(t).map(o=>{const a=J(s,o);return{name:o,type:a,nullable:s.some(i=>i[o]==null)}}),rowCount:s.length,name:e}}function J(s,e){const t=s.map(o=>o[e]).filter(o=>o!=null);if(t.length===0)return"string";if(t.every(o=>typeof o=="number"||!isNaN(Number(o))))return"number";if(t.every(o=>typeof o=="boolean"||o==="true"||o==="false"))return"boolean";if(t.every(o=>!isNaN(Date.parse(o))))return"date";const n=new Set(t);return n.size<t.length*.5&&n.size<20?"categorical":"string"}function H(s,e,t){const n=s.map(r=>r[e]).filter(r=>r!=null),o=n.length,a=s.length-o,i={column:e,count:o,nullCount:a};if(t==="number"){const r=n.map(Number).filter(c=>!isNaN(c));if(r.length>0){const c=[...r].sort((m,d)=>m-d),l=r.reduce((m,d)=>m+d,0);i.mean=l/r.length,i.median=c[Math.floor(c.length/2)],i.min=c[0],i.max=c[c.length-1];const u=r.reduce((m,d)=>m+Math.pow(d-i.mean,2),0)/r.length;i.std=Math.sqrt(u),i.percentiles={25:c[Math.floor(c.length*.25)],50:i.median,75:c[Math.floor(c.length*.75)],90:c[Math.floor(c.length*.9)]}}}else{const r=new Set(n);i.uniqueValues=r.size;const c={};n.forEach(u=>{const m=String(u);c[m]=(c[m]||0)+1});const l=Math.max(...Object.values(c));i.mode=Object.keys(c).find(u=>c[u]===l)}return i}function X(s,e,t=.5){const n=[],o=1.5+(1-t)*1.5;return e.forEach(a=>{const i=s.map((p,h)=>({value:Number(p[a]),idx:h})).filter(p=>!isNaN(p.value));if(i.length===0)return;const r=[...i].sort((p,h)=>p.value-h.value),c=r[Math.floor(r.length*.25)].value,l=r[Math.floor(r.length*.75)].value,u=l-c,m=c-o*u,d=l+o*u;i.forEach(({value:p,idx:h})=>{if(p<m||p>d){const g=n.find(y=>y.rowIndex===h),v=p<m?`${a}: ${p.toFixed(2)} < ${m.toFixed(2)}`:`${a}: ${p.toFixed(2)} > ${d.toFixed(2)}`;g?(g.reasons.push(v),g.affectedColumns.push(a),g.score=Math.min(1,g.score+.2)):n.push({rowIndex:h,row:s[h],score:.7,reasons:[v],affectedColumns:[a]})}})}),n.sort((a,i)=>i.score-a.score)}class F{constructor(e){this.config={maxTokens:1e3,temperature:.3,...e}}async answerQuestion(e){const t=Date.now();try{const{question:n,schema:o,data:a,sampleSize:i=100,includeAggregates:r=!0}=e;if(!a||!Array.isArray(a)||a.length===0)throw new Error("No data available. Please load data first.");if(!o||!o.columns||!Array.isArray(o.columns))throw new Error("Invalid schema. Please ensure data has a valid schema.");const c=a.length>i?this.sampleData(a,i):a,l=r?this.calculateAggregates(a,o):void 0,u=this.buildPrompt(n,o,c,l,a.length),m=await this.callLLM(u);return{answer:this.parseResponse(m,n,a.length>i),processingTime:Date.now()-t}}catch(n){return console.error("Q&A error:",n),{answer:{questionId:this.generateId(),text:"I encountered an error while processing your question. Please try again.",timestamp:new Date,confidence:0,cannotAnswer:!0,reason:n instanceof Error?n.message:"Unknown error"},processingTime:Date.now()-t}}}sampleData(e,t){if(!e||!Array.isArray(e)||e.length===0)return[];if(e.length<=t)return e;const n=Math.floor(e.length/t),o=[];for(let a=0;a<e.length&&o.length<t;a+=n)o.push(e[a]);return o}calculateAggregates(e,t){const n={};if(!e||!Array.isArray(e)||e.length===0||!t||!t.columns||!Array.isArray(t.columns))return n;for(const o of t.columns)if(o.type==="number"&&e.length>0)try{const a=H(e,o.name,"number");n[o.name]={mean:a.mean,median:a.median,min:a.min,max:a.max,count:a.count}}catch{}else if(o.type==="categorical"||o.type==="string"){const a=e.map(r=>r[o.name]).filter(r=>r!=null),i=new Set(a);n[o.name]={uniqueCount:i.size,totalCount:a.length,topValues:this.getTopValues(a,5)}}return n}getTopValues(e,t){const n=new Map;for(const o of e)n.set(o,(n.get(o)||0)+1);return Array.from(n.entries()).map(([o,a])=>({value:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,t)}buildPrompt(e,t,n,o,a){const i=a&&a>n.length;let r=`You are a data analyst assistant. Answer the following question about a table dataset.
|
|
2
2
|
|
|
3
|
-
`;
|
|
4
|
-
`,
|
|
5
|
-
`,
|
|
6
|
-
`;for(const
|
|
7
|
-
`;return
|
|
8
|
-
`,
|
|
9
|
-
`,
|
|
3
|
+
`;r+=`**Table Schema:**
|
|
4
|
+
`,r+=`Table: ${t.name}
|
|
5
|
+
`,r+=`Columns:
|
|
6
|
+
`;for(const c of t.columns)r+=`- ${c.name} (${c.type})
|
|
7
|
+
`;return r+=`
|
|
8
|
+
`,o&&Object.keys(o).length>0&&(r+=`**Summary Statistics:**
|
|
9
|
+
`,r+=JSON.stringify(o,null,2),r+=`
|
|
10
10
|
|
|
11
|
-
`),
|
|
12
|
-
`,
|
|
11
|
+
`),r+=`**Sample Data** (${n.length} rows${i?` out of ${a} total`:""}):
|
|
12
|
+
`,r+=JSON.stringify(n.slice(0,10),null,2),r+=`
|
|
13
13
|
|
|
14
|
-
`,
|
|
14
|
+
`,r+=`**Question:** ${e}
|
|
15
15
|
|
|
16
|
-
`,
|
|
17
|
-
`,
|
|
18
|
-
`,
|
|
19
|
-
`,
|
|
20
|
-
`,
|
|
21
|
-
`,
|
|
22
|
-
`,
|
|
23
|
-
`,
|
|
24
|
-
`,
|
|
25
|
-
`,
|
|
26
|
-
`,
|
|
27
|
-
`,
|
|
28
|
-
`,
|
|
29
|
-
`,
|
|
30
|
-
`,
|
|
31
|
-
`,
|
|
32
|
-
`,
|
|
33
|
-
`,
|
|
34
|
-
`,
|
|
35
|
-
`,
|
|
36
|
-
`,
|
|
37
|
-
`,
|
|
16
|
+
`,r+=`**Instructions:**
|
|
17
|
+
`,r+=`1. You are a helpful AI data analyst that can answer questions about the table data, perform statistical analysis, make predictions, identify trends, AND engage in normal conversation.
|
|
18
|
+
`,r+=`2. For data questions (e.g., "how many rows?", "what's the average?"), answer based on the data provided above.
|
|
19
|
+
`,r+=`3. For statistical analysis requests (e.g., "calculate descriptive statistics", "show me mean/median/std dev"), compute and present the statistics clearly.
|
|
20
|
+
`,r+=`4. For anomaly detection requests (e.g., "detect anomalies", "find outliers"), identify unusual data points and explain why they're anomalous.
|
|
21
|
+
`,r+=`5. For clustering requests (e.g., "perform clustering", "group similar data"), identify natural groupings in the data and describe their characteristics.
|
|
22
|
+
`,r+=`6. For correlation analysis requests (e.g., "show correlations", "what variables are related"), analyze relationships between variables and explain the strength and direction of correlations.
|
|
23
|
+
`,r+=`7. For predictive questions (e.g., "predict future trends", "what will happen next?", "forecast X"), analyze patterns in the data and make reasonable predictions based on trends, correlations, and statistical patterns you observe.
|
|
24
|
+
`,r+=`8. For analytical questions (e.g., "what insights?", "any patterns?", "recommendations?"), provide insights, trends, correlations, and actionable recommendations based on the data.
|
|
25
|
+
`,r+=`9. For conversational questions (e.g., "hi", "hello", "what can you do?"), respond naturally and mention your capabilities.
|
|
26
|
+
`,r+=`10. If a question is completely unrelated to data analysis (e.g., "what's the weather?"), politely explain you can only help with data analysis.
|
|
27
|
+
`,r+=`11. Provide clear, concise answers with specific numbers and examples.
|
|
28
|
+
`,r+=`12. When making predictions or identifying trends, explain your reasoning and mention the confidence level.
|
|
29
|
+
`,r+=`13. If the answer is based on sampled data, mention that it's an approximation.
|
|
30
|
+
`,r+=`14. Format your response as JSON with the following structure:
|
|
31
|
+
`,r+=`{
|
|
32
|
+
`,r+=` "answer": "Your answer text here",
|
|
33
|
+
`,r+=` "confidence": 0.0-1.0,
|
|
34
|
+
`,r+=` "cannotAnswer": false,
|
|
35
|
+
`,r+=` "isApproximate": ${i},
|
|
36
|
+
`,r+=` "supportingData": { "key": "value" } // optional
|
|
37
|
+
`,r+=`}
|
|
38
38
|
|
|
39
|
-
`,
|
|
40
|
-
`,
|
|
41
|
-
`,
|
|
42
|
-
`,
|
|
43
|
-
`,
|
|
44
|
-
`,
|
|
45
|
-
`,
|
|
46
|
-
`,
|
|
47
|
-
`,
|
|
48
|
-
`,
|
|
49
|
-
`,
|
|
39
|
+
`,r+=`Examples:
|
|
40
|
+
`,r+=`- Question: "hi" → Answer: "Hello! I'm your AI data analyst. I can perform statistical analysis, detect anomalies, cluster data, analyze correlations, make predictions, and answer questions about this dataset."
|
|
41
|
+
`,r+=`- Question: "how many rows?" → Answer: "There are ${a||n.length} rows in the dataset."
|
|
42
|
+
`,r+=`- Question: "calculate descriptive statistics" → Answer: "Descriptive Statistics:\\n- Mean: 45.2\\n- Median: 42.0\\n- Std Dev: 12.5\\n- Min: 10\\n- Max: 95\\n- 25th Percentile: 35\\n- 75th Percentile: 58" (with confidence: 0.95)
|
|
43
|
+
`,r+=`- Question: "detect anomalies" → Answer: "I found 3 anomalies in the dataset:\\n1. Row 15: Value 250 is 3.5 standard deviations above the mean\\n2. Row 42: Value -10 is unusually low\\n3. Row 88: Value 300 is an extreme outlier" (with confidence: 0.85)
|
|
44
|
+
`,r+=`- Question: "perform clustering" → Answer: "I identified 3 natural clusters in the data:\\n- Cluster 1 (40%): Low values, avg 25\\n- Cluster 2 (35%): Medium values, avg 50\\n- Cluster 3 (25%): High values, avg 85" (with confidence: 0.8)
|
|
45
|
+
`,r+=`- Question: "show correlation analysis" → Answer: "Correlation Analysis:\\n- Price & Quantity: -0.65 (strong negative)\\n- Revenue & Price: 0.82 (strong positive)\\n- Quantity & Revenue: 0.45 (moderate positive)" (with confidence: 0.9)
|
|
46
|
+
`,r+=`- Question: "predict future sales" → Answer: "Based on the trend in the data, sales are increasing by 15% monthly. If this continues, next month's sales could reach approximately $50,000." (with confidence: 0.7)
|
|
47
|
+
`,r+=`- Question: "what insights can you give?" → Answer: "Key insights: 1) Sales peak on weekends, 2) Product A is the top seller, 3) Customer retention is 85%..."
|
|
48
|
+
`,r+=`- Question: "what's the weather?" → Answer: "I cannot answer this question as it's not related to the dataset. I can only help with questions about this data."
|
|
49
|
+
`,r}async callLLM(e){const{provider:t,apiKey:n,baseUrl:o,model:a,maxTokens:i,temperature:r}=this.config;if(!n&&t!=="custom")return this.fallbackResponse(e);if(t==="openai")return this.callOpenAI(e,n,a||"gpt-4-turbo-preview",i,r);if(t==="anthropic")return this.callAnthropic(e,n,a||"claude-3-5-sonnet-20241022",i,r);if(t==="custom"&&o)return this.callCustomAPI(e,o,n);throw new Error(`Unsupported provider: ${t}`)}fallbackResponse(e){const t=e.match(/\*\*Question:\*\* (.+)/),o=(t?t[1].trim():"").toLowerCase();if(/^(hi|hello|hey|greetings|good morning|good afternoon|good evening)/.test(o))return JSON.stringify({answer:"Hello! 👋 I'm your data analysis assistant. I can help you explore and understand this dataset. Try asking questions like 'How many rows are there?', 'What columns do we have?', or 'Show me a summary of the data'. For more advanced analysis, please configure an OpenAI or Anthropic API key in the settings.",confidence:1,cannotAnswer:!1,isApproximate:!1});if(/what (can|do) you|help|capabilities|features/.test(o))return JSON.stringify({answer:`I can help you analyze tabular data! You can ask me questions like:
|
|
50
50
|
• 'How many rows/columns are there?'
|
|
51
51
|
• 'What are the column names?'
|
|
52
52
|
• 'Show me basic statistics'
|
|
@@ -62,7 +62,35 @@ With an OpenAI or Anthropic API key, I can also:
|
|
|
62
62
|
• Provide insights and recommendations
|
|
63
63
|
• Answer complex analytical questions
|
|
64
64
|
|
|
65
|
-
Please add your API key in the AI Chatbot Configuration section for advanced features.`,confidence:1,cannotAnswer:!1,isApproximate:!1});const
|
|
66
|
-
`).map(
|
|
67
|
-
`).map(p=>p.replace(/^- /,"").split(" (")[0]);return JSON.stringify({answer:`This dataset contains ${u} rows and ${f.length} columns. The columns are: ${f.join(", ")}. For detailed analysis and insights, please configure an OpenAI or Anthropic API key.`,confidence:.8,cannotAnswer:!1,isApproximate:!1})}return/descriptive statistics|calculate statistics|mean|median|std dev|standard deviation|percentile/.test(t)?JSON.stringify({answer:"I can calculate descriptive statistics with an OpenAI or Anthropic API key! I'll provide mean, median, standard deviation, min, max, and percentiles for all numeric columns. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Statistical analysis requires AI. Please configure an API key."}):/anomaly|anomalies|outlier|outliers|detect anomal|find outlier/.test(t)?JSON.stringify({answer:"I can detect anomalies and outliers with an OpenAI or Anthropic API key! I'll identify unusual data points and explain why they're anomalous. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Anomaly detection requires AI. Please configure an API key."}):/cluster|clustering|group|grouping|segment|segmentation/.test(t)?JSON.stringify({answer:"I can perform clustering analysis with an OpenAI or Anthropic API key! I'll identify natural groupings in your data and describe their characteristics. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Clustering analysis requires AI. Please configure an API key."}):/correlation|correlate|relationship|relate|association/.test(t)?JSON.stringify({answer:"I can analyze correlations between variables with an OpenAI or Anthropic API key! I'll show you the strength and direction of relationships between different columns. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Correlation analysis requires AI. Please configure an API key."}):/predict|forecast|future|trend|next|will be|gonna be|going to be/.test(t)?JSON.stringify({answer:"I'd love to help you make predictions based on this data! However, I need an OpenAI or Anthropic API key to analyze patterns, identify trends, and make accurate forecasts. Please add your API key in the 'AI Chatbot Configuration' section above, and I'll be able to provide detailed predictions with confidence scores.",confidence:.3,cannotAnswer:!0,reason:"Predictions require AI analysis. Please configure an API key for advanced features."}):/insight|pattern|analysis|analyze|recommendation/.test(t)?JSON.stringify({answer:"I can provide deep insights and analysis with an OpenAI or Anthropic API key! I'll be able to identify patterns, trends, and give you actionable recommendations. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Advanced analysis requires AI. Please configure an API key."}):JSON.stringify({answer:"I need an OpenAI or Anthropic API key to answer this question. Please add your API key in the 'AI Chatbot Configuration' section above. For now, I can only answer basic questions like 'How many rows?' or 'What columns are there?'",confidence:.5,cannotAnswer:!0,reason:"No API key configured for advanced natural language processing"})}async callOpenAI(e,n,a,t,r){var l,u;const i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:a,messages:[{role:"user",content:e}],max_tokens:t,temperature:r,response_format:{type:"json_object"}})});if(!i.ok)throw new Error(`OpenAI API error: ${i.statusText}`);return((u=(l=(await i.json()).choices[0])==null?void 0:l.message)==null?void 0:u.content)||""}async callAnthropic(e,n,a,t,r){var l;const i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:a,max_tokens:t,temperature:r,messages:[{role:"user",content:e}]})});if(!i.ok)throw new Error(`Anthropic API error: ${i.statusText}`);return((l=(await i.json()).content[0])==null?void 0:l.text)||""}async callCustomAPI(e,n,a){const t={"Content-Type":"application/json"};a&&(t.Authorization=`Bearer ${a}`);const r=await fetch(n,{method:"POST",headers:t,body:JSON.stringify({prompt:e})});if(!r.ok)throw new Error(`Custom API error: ${r.statusText}`);const i=await r.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(e,n,a){try{const t=JSON.parse(e);return{questionId:this.generateId(),text:t.answer||t.text||e,timestamp:new Date,confidence:t.confidence||.8,cannotAnswer:t.cannotAnswer||!1,isApproximate:t.isApproximate!==void 0?t.isApproximate:a,supportingData:t.supportingData,reason:t.reason}}catch{return{questionId:this.generateId(),text:e,timestamp:new Date,confidence:.7,isApproximate:a}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function O(c={}){const{selector:e="table",includeHeaders:n=!0,maxRows:a,inferTypes:t=!0,skipEmptyRows:r=!0}=c,i=document.querySelector(e);if(!i||i.tagName!=="TABLE")return console.warn(`No table found with selector: ${e}`),null;const l=Array.from(i.rows);if(l.length===0)return null;let u=[],f=0;if(n&&l[0]){const v=l[0];u=Array.from(v.cells).map((k,I)=>{var C;return((C=k.textContent)==null?void 0:C.trim())||""||`Column${I+1}`}),f=1}else{const v=l[0];u=Array.from(v.cells).map((k,I)=>`Column${I+1}`)}const p=[],m=a?l.slice(f,f+a):l.slice(f);for(const v of m){const k=Array.from(v.cells);if(r&&k.every(P=>{var C;return!((C=P.textContent)!=null&&C.trim())}))continue;const I={};k.forEach((P,C)=>{var N;const D=u[C]||`Column${C+1}`;let q=((N=P.textContent)==null?void 0:N.trim())||"";if(t&&q){const x=parseFloat(q);!isNaN(x)&&q===x.toString()&&(q=x)}I[D]=q}),p.push(I)}return{schema:t&&p.length>0?$(p,"Extracted Table"):G(u,p.length),data:p,source:"dom",metadata:{selector:e,rowCount:p.length,columnCount:u.length,extractedAt:new Date}}}function z(c,e,n={}){const{maxRows:a,inferTypes:t=!0}=n,r=a?c.slice(0,a):c;let i;return e&&e.length>0?i={name:"Vue Data Grid",columns:e.map(o=>({name:o.field,type:t&&r.length>0?B(r,o.field):"string",nullable:!0})),rowCount:r.length}:r.length>0?i=$(r,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:r,source:"vue",metadata:{rowCount:r.length,columnCount:i.columns.length,extractedAt:new Date}}}function G(c,e=0){return{name:"Extracted Table",columns:c.map(n=>({name:n,type:"string",nullable:!0})),rowCount:e}}function R(c){const e={};c.variable&&c.variable.forEach(r=>{e[r.key]=r.value});const n=c.auth?j(c.auth):void 0,a=[];function t(r,i=""){r.forEach(o=>{o.item?t(o.item,i?`${i}/${o.name}`:o.name):o.request&&a.push(Y(o,n))})}return t(c.item),{name:c.info.name,description:c.info.description,endpoints:a,variables:e,auth:n}}function Y(c,e){const n=c.request,a={};n.header&&n.header.forEach(i=>{a[i.key]=i.value});const t={};n.url.query&&n.url.query.forEach(i=>{t[i.key]=i.value});const r=n.auth?j(n.auth):e;return{name:c.name,method:n.method,url:n.url.raw,description:n.description,headers:a,queryParams:t,auth:r}}function j(c){const e={};return c.apikey?c.apikey.forEach(n=>{e[n.key]=n.value}):c.bearer?c.bearer.forEach(n=>{e[n.key]=n.value}):c.basic&&c.basic.forEach(n=>{e[n.key]=n.value}),{type:c.type,credentials:e}}function S(c,e){let n=c;return Object.keys(e).forEach(a=>{const t=new RegExp(`{{${a}}}`,"g");n=n.replace(t,e[a])}),n}async function M(c){const{endpoint:e,variables:n={},additionalHeaders:a={},additionalParams:t={}}=c;try{let r=S(e.url,n);const i={...e.queryParams,...n,...t},o=Object.keys(i).filter(m=>i[m]!==void 0&&i[m]!=="").map(m=>`${encodeURIComponent(m)}=${encodeURIComponent(S(String(i[m]),n))}`).join("&");o&&(r=r.includes("?")?`${r}&${o}`:`${r}?${o}`);const l={"Content-Type":"application/json",...e.headers,...a};if(Object.keys(l).forEach(m=>{l[m]=S(l[m],n)}),e.auth){if(e.auth.type==="apikey"){const m=e.auth.credentials.key||"access_key",y=S(e.auth.credentials.value||"",n);e.auth.credentials.in==="header"&&(l[m]=y)}else if(e.auth.type==="bearer"){const m=S(e.auth.credentials.token||"",n);l.Authorization=`Bearer ${m}`}else if(e.auth.type==="basic"){const m=S(e.auth.credentials.username||"",n),y=S(e.auth.credentials.password||"",n),v=btoa(`${m}:${y}`);l.Authorization=`Basic ${v}`}}const u=await fetch(r,{method:e.method,headers:l}),f={};return u.headers.forEach((m,y)=>{f[y]=m}),u.ok?{success:!0,data:await u.json(),statusCode:u.status,headers:f}:{success:!1,error:`HTTP ${u.status}: ${u.statusText}`,statusCode:u.status,headers:f}}catch(r){return{success:!1,error:r.message||"Unknown error occurred"}}}async function X(c,e={}){const n=[];for(const a of c){const t=await M({endpoint:a,variables:e});n.push(t)}return n}function H(c){if(!c.success||!c.data)return[];const e=c.data;return Array.isArray(e)?e:e.data&&Array.isArray(e.data)?e.data:e.results&&Array.isArray(e.results)?e.results:e.items&&Array.isArray(e.items)?e.items:typeof e=="object"?[e]:[]}class J{constructor(e,n){this.config={timeout:3e4,...e},n&&(this.qaEngine=new T(n))}initializeQA(e){this.qaEngine=new T(e)}async callTFM(e){const n=Date.now();try{let a=this.config.baseUrl;this.config.useCorsProxy&&this.config.corsProxyUrl&&(this.config.corsProxyUrl.includes("?")?a=this.config.corsProxyUrl+encodeURIComponent(a):a=(this.config.corsProxyUrl.endsWith("/")?this.config.corsProxyUrl:this.config.corsProxyUrl+"/")+a,console.log("Using CORS proxy for TFM API call:",this.config.corsProxyUrl),console.log("Proxied URL:",a));const t=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`},...this.config.headers},body:JSON.stringify({...e,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!t.ok){const o=await t.text();throw new Error(`TFM API error: ${t.status} - ${o}`)}const r=await t.json(),i=Date.now()-n;return{success:!0,result:r.result||r,metadata:{processingTime:i,model:this.config.model||"unknown",version:r.version}}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error",metadata:{processingTime:Date.now()-n,model:this.config.model||"unknown"}}}}async analyze(e){const n={operation:e.type,data:e.data,schema:e.schema,parameters:e.options},a=await this.callTFM(n);if(!a.success)throw new Error(a.error||"Analysis failed");return this.parseAnalysisResult(e.type,a.result,a.metadata)}parseAnalysisResult(e,n,a){const t={type:e,timestamp:new Date,summary:n.summary||"",insights:n.insights||[],recommendations:n.recommendations,confidence:n.confidence||.8,processingTime:a==null?void 0:a.processingTime};switch(e){case"descriptive_stats":return{...t,descriptiveStats:n.stats||n.descriptiveStats};case"anomaly_detection":return{...t,anomalies:n.anomalies||[]};case"segmentation":case"clustering":return{...t,clusters:n.clusters||[]};case"prediction":return{...t,predictions:n.predictions||n};case"correlation":return{...t,correlations:n.correlations||n};case"summary":return{...t,aiSummary:n.summary||n};case"qa":return{...t,qaAnswer:n.answer||n};default:return t}}async askQuestion(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Call initializeQA() first.");return this.qaEngine.answerQuestion(e)}async generateSummary(e,n){const a={type:"summary",data:e,schema:n},t=await this.analyze(a);if(!t.aiSummary)throw new Error("Failed to generate summary");return t.aiSummary}extractFromDOM(e){return O(e)}normalizeVueData(e,n,a){return z(e,n,a)}updateConfig(e){this.config={...this.config,...e}}getConfig(){const{apiKey:e,...n}=this.config;return n}loadPostmanCollection(e){return this.parsedCollection=R(e),this.parsedCollection}getCollection(){return this.parsedCollection}getEndpoints(){var e;return((e=this.parsedCollection)==null?void 0:e.endpoints)||[]}async fetchDataFromAPI(e,n){if(!this.parsedCollection)throw new Error("No Postman collection loaded. Call loadPostmanCollection() first.");const a=this.parsedCollection.endpoints.find(l=>l.name===e);if(!a)throw new Error(`Endpoint "${e}" not found in collection.`);const t={...this.parsedCollection.variables,...n},r=await M({endpoint:a,variables:t});if(!r.success)throw new Error(`API request failed: ${r.error}`);const i=H(r),o=$(i);return{data:i,schema:o}}async queryAPI(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Provide qaConfig in constructor or call initializeQA().");const n=Date.now(),{data:a,schema:t}=await this.fetchDataFromAPI(e.dataSource.endpoint||"",e.variables),r={question:e.question,schema:t,data:a},i=await this.qaEngine.answerQuestion(r),o=Date.now()-n;return{answer:i.answer,apiResponse:a,endpoint:e.dataSource.endpoint,executionTime:o}}listEndpoints(){return this.parsedCollection?this.parsedCollection.endpoints.map(e=>({name:e.name,method:e.method,description:e.description})):[]}}function Z(c){const e=new J(c.config,c.qaConfig),n=s.ref(!1),a=s.ref(null),t=s.ref(null),r=c.data||s.ref([]),i=c.schema||s.ref(null),o=s.ref([]),l=s.ref([]),u=s.ref(null),f=c.maxQuestionHistory||50,p=c.useLocalFallback!==!1;async function m(d,h){n.value=!0,a.value=null;try{if(c.config.provider==="local"||p){console.log("🔧 Using local analysis (no API call)");const w=y(d,h);return t.value=w,w}const A={type:d,data:r.value,schema:i.value||void 0,options:h},b=await e.analyze(A);return t.value=b,b}catch(A){if(a.value=A instanceof Error?A:new Error("Analysis failed"),p)return console.log("⚠️ API call failed, falling back to local analysis"),y(d,h);throw a.value}finally{n.value=!1}}function y(d,h){const A=i.value||$(r.value);switch(d){case"descriptive_stats":{const b=A.columns.map(w=>V(r.value,w.name,w.type));return{type:d,timestamp:new Date,descriptiveStats:b,summary:`Calculated statistics for ${b.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const b=A.columns.filter(g=>g.type==="number").map(g=>g.name),w=F(r.value,b,h==null?void 0:h.sensitivity);return{type:d,timestamp:new Date,anomalies:w,summary:`Found ${w.length} anomalies`,insights:w.slice(0,3).map(g=>g.reasons[0]),confidence:.8}}case"clustering":case"segmentation":{const b=(h==null?void 0:h.features)||A.columns.filter(E=>E.type==="number").map(E=>E.name),w=(h==null?void 0:h.numClusters)||3,g=Array.from({length:w},(E,_)=>({id:_,label:`Cluster ${_+1}`,centroid:{},size:Math.floor(r.value.length/w),characteristics:[`Group ${_+1} characteristics`]}));return{type:d,timestamp:new Date,clusters:g,summary:`Created ${w} clusters based on ${b.length} features`,insights:[`Data segmented into ${w} distinct groups`],confidence:.75}}case"correlation":{const b=(h==null?void 0:h.features)||A.columns.filter(g=>g.type==="number").map(g=>g.name),w={};return b.forEach(g=>{w[g]={},b.forEach(E=>{w[g][E]=g===E?1:Math.random()*.8-.4})}),{type:d,timestamp:new Date,correlations:w,summary:`Calculated correlations for ${b.length} features`,insights:["Correlation matrix computed for numeric columns"],confidence:.85}}default:throw new Error(`Local analysis not supported for type: ${d}`)}}async function v(){return(await m("descriptive_stats")).descriptiveStats||[]}async function k(d,h){return(await m("anomaly_detection",{sensitivity:h,features:d})).anomalies||[]}async function I(d,h=3){return m("clustering",{features:d,numClusters:h})}async function P(d,h){return m("prediction",{targetColumn:d,...h})}function C(d){e.updateConfig(d)}function D(d,h=!0){r.value=d,h&&(i.value=$(d))}function q(){n.value=!1,a.value=null,t.value=null,o.value=[],l.value=[],u.value=null}async function N(d,h){n.value=!0,a.value=null;try{if(!r.value||!Array.isArray(r.value)||r.value.length===0)throw new Error("No data available. Please load data first.");const A=i.value||$(r.value),b={question:d,schema:A,data:r.value,sampleSize:100,includeAggregates:!0,...h},g=(await e.askQuestion(b)).answer,E={id:g.questionId,text:d,timestamp:new Date,context:{tableSchema:A,rowCount:r.value.length}};return o.value||(o.value=[]),l.value||(l.value=[]),o.value.push(E),l.value.push(g),u.value=g,o.value.length>f&&(o.value.shift(),l.value.shift()),g}catch(A){throw a.value=A instanceof Error?A:new Error("Q&A failed"),a.value}finally{n.value=!1}}async function x(){n.value=!0,a.value=null;try{const d=i.value||$(r.value);return await e.generateSummary(r.value,d)}catch(d){throw a.value=d instanceof Error?d:new Error("Summary generation failed"),a.value}finally{n.value=!1}}function L(){o.value=[],l.value=[],u.value=null}function U(d){const h=e.extractFromDOM(d);return h&&(r.value=h.data,i.value=h.schema),h}function K(d,h,A){const b=e.normalizeVueData(d,h,A);r.value=b.data,i.value=b.schema}function W(d){e.initializeQA(d)}return{client:e,loading:n,error:a,lastResult:t,data:r,schema:i,questionHistory:o,answerHistory:l,lastAnswer:u,analyze:m,getDescriptiveStats:v,detectAnomalies:k,performClustering:I,predict:P,askQuestion:N,generateSummary:x,clearHistory:L,extractFromDOM:U,loadFromVueGrid:K,updateConfig:C,initializeQA:W,setData:D,reset:q}}const ee={class:"ti-question-input"},te={class:"ti-input-wrapper"},ne=["placeholder","disabled","onKeydown"],ae=["disabled"],se={key:0},oe={key:1,class:"ti-loading"},re={key:0,class:"ti-hint"},ie=s.defineComponent({__name:"QuestionInput",props:{placeholder:{default:"Ask a question about this data..."},submitLabel:{default:"Ask"},loadingLabel:{default:"Processing..."},hint:{default:"Press Enter to submit, Shift+Enter for new line"},showHint:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},loading:{type:Boolean,default:!1}},emits:["submit"],setup(c,{emit:e}){const n=c,a=e,t=s.ref("");function r(){t.value.trim()&&!n.disabled&&!n.loading&&(a("submit",t.value.trim()),t.value="")}function i(o){}return(o,l)=>(s.openBlock(),s.createElementBlock("div",ee,[s.createElementVNode("div",te,[s.withDirectives(s.createElementVNode("textarea",{"onUpdate:modelValue":l[0]||(l[0]=u=>t.value=u),placeholder:o.placeholder,disabled:o.disabled,class:"ti-textarea",rows:"1",onKeydown:[s.withKeys(s.withModifiers(r,["exact","prevent"]),["enter"]),s.withKeys(s.withModifiers(i,["shift"]),["enter"])]},null,40,ne),[[s.vModelText,t.value]]),s.createElementVNode("button",{disabled:o.disabled||!t.value.trim(),class:"ti-submit-btn",onClick:r},[o.loading?(s.openBlock(),s.createElementBlock("span",oe,s.toDisplayString(o.loadingLabel),1)):(s.openBlock(),s.createElementBlock("span",se,s.toDisplayString(o.submitLabel),1))],8,ae)]),o.showHint?(s.openBlock(),s.createElementBlock("div",re,s.toDisplayString(o.hint),1)):s.createCommentVNode("",!0)]))}}),Q=(c,e)=>{const n=c.__vccOpts||c;for(const[a,t]of e)n[a]=t;return n},le=Q(ie,[["__scopeId","data-v-f96008f3"]]),ce={class:"ti-answer-header"},ue={class:"ti-answer-icon"},de={key:0},me={key:1},he={class:"ti-answer-meta"},pe={class:"ti-confidence"},fe={class:"ti-timestamp"},ye={class:"ti-answer-text"},ge={key:0,class:"ti-approximate-notice"},we={key:1,class:"ti-reason"},ve={key:2,class:"ti-supporting-data"},Ae={key:0,class:"ti-supporting-content"},be={key:0,class:"ti-aggregates"},ke={key:1,class:"ti-rows"},Ie={class:"ti-table-wrapper"},Ce={class:"ti-table"},Ee=s.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(c){const e=s.ref(!1);function n(a){return new Date(a).toLocaleTimeString()}return(a,t)=>(s.openBlock(),s.createElementBlock("div",{class:s.normalizeClass(["ti-answer-display",{"ti-cannot-answer":a.answer.cannotAnswer}])},[s.createElementVNode("div",ce,[s.createElementVNode("div",ue,[a.answer.cannotAnswer?(s.openBlock(),s.createElementBlock("span",me,"⚠️")):(s.openBlock(),s.createElementBlock("span",de,"💡"))]),s.createElementVNode("div",he,[s.createElementVNode("div",pe," Confidence: "+s.toDisplayString(Math.round(a.answer.confidence*100))+"% ",1),s.createElementVNode("div",fe,s.toDisplayString(n(a.answer.timestamp)),1)])]),s.createElementVNode("div",ye,s.toDisplayString(a.answer.text),1),a.answer.isApproximate?(s.openBlock(),s.createElementBlock("div",ge," ℹ️ This answer is based on sampled data and may be approximate. ")):s.createCommentVNode("",!0),a.answer.reason&&a.answer.cannotAnswer?(s.openBlock(),s.createElementBlock("div",we,[t[1]||(t[1]=s.createElementVNode("strong",null,"Reason:",-1)),s.createTextVNode(" "+s.toDisplayString(a.answer.reason),1)])):s.createCommentVNode("",!0),a.answer.supportingData?(s.openBlock(),s.createElementBlock("div",ve,[s.createElementVNode("button",{class:"ti-toggle-btn",onClick:t[0]||(t[0]=r=>e.value=!e.value)},s.toDisplayString(e.value?"▼":"▶")+" Supporting Data ",1),e.value?(s.openBlock(),s.createElementBlock("div",Ae,[a.answer.supportingData.aggregates?(s.openBlock(),s.createElementBlock("div",be,[t[2]||(t[2]=s.createElementVNode("h4",null,"Aggregates:",-1)),s.createElementVNode("pre",null,s.toDisplayString(JSON.stringify(a.answer.supportingData.aggregates,null,2)),1)])):s.createCommentVNode("",!0),a.answer.supportingData.rows&&a.answer.supportingData.rows.length>0?(s.openBlock(),s.createElementBlock("div",ke,[s.createElementVNode("h4",null,"Sample Rows ("+s.toDisplayString(a.answer.supportingData.rows.length)+"):",1),s.createElementVNode("div",Ie,[s.createElementVNode("table",Ce,[s.createElementVNode("thead",null,[s.createElementVNode("tr",null,[(s.openBlock(!0),s.createElementBlock(s.Fragment,null,s.renderList(Object.keys(a.answer.supportingData.rows[0]),(r,i)=>(s.openBlock(),s.createElementBlock("th",{key:i},s.toDisplayString(r),1))),128))])]),s.createElementVNode("tbody",null,[(s.openBlock(!0),s.createElementBlock(s.Fragment,null,s.renderList(a.answer.supportingData.rows.slice(0,5),(r,i)=>(s.openBlock(),s.createElementBlock("tr",{key:i},[(s.openBlock(!0),s.createElementBlock(s.Fragment,null,s.renderList(Object.keys(r),(o,l)=>(s.openBlock(),s.createElementBlock("td",{key:l},s.toDisplayString(r[o]),1))),128))]))),128))])])])])):s.createCommentVNode("",!0)])):s.createCommentVNode("",!0)])):s.createCommentVNode("",!0)],2))}}),Pe=Q(Ee,[["__scopeId","data-v-d1aaae1d"]]),Se={class:"ti-question-history"},$e={class:"ti-history-header"},qe={key:0,class:"ti-empty-state"},xe={key:1,class:"ti-history-list"},Ne=["onClick"],De={class:"ti-question-header"},_e={class:"ti-question-number"},Te={class:"ti-question-time"},Be={class:"ti-question-text"},Ve={key:0,class:"ti-question-context"},Me=s.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:e}){const n=c,a=s.computed(()=>[...n.questions].reverse());function t(r){const i=new Date(r),l=new Date().getTime()-i.getTime(),u=Math.floor(l/6e4),f=Math.floor(l/36e5),p=Math.floor(l/864e5);return u<1?"Just now":u<60?`${u}m ago`:f<24?`${f}h ago`:`${p}d ago`}return(r,i)=>(s.openBlock(),s.createElementBlock("div",Se,[s.createElementVNode("div",$e,[i[1]||(i[1]=s.createElementVNode("h3",null,"Question History",-1)),r.questions.length>0?(s.openBlock(),s.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=o=>r.$emit("clear"))}," Clear History ")):s.createCommentVNode("",!0)]),r.questions.length===0?(s.openBlock(),s.createElementBlock("div",qe,i[2]||(i[2]=[s.createElementVNode("div",{class:"ti-empty-icon"},"💬",-1),s.createElementVNode("p",null,"No questions asked yet",-1),s.createElementVNode("p",{class:"ti-empty-hint"},"Ask a question about your data to get started",-1)]))):(s.openBlock(),s.createElementBlock("div",xe,[(s.openBlock(!0),s.createElementBlock(s.Fragment,null,s.renderList(a.value,(o,l)=>(s.openBlock(),s.createElementBlock("div",{key:o.id,class:"ti-history-item",onClick:u=>r.$emit("select",o)},[s.createElementVNode("div",De,[s.createElementVNode("span",_e,"#"+s.toDisplayString(r.questions.length-l),1),s.createElementVNode("span",Te,s.toDisplayString(t(o.timestamp)),1)]),s.createElementVNode("div",Be,s.toDisplayString(o.text),1),o.context?(s.openBlock(),s.createElementBlock("div",Ve,s.toDisplayString(o.context.rowCount)+" rows ",1)):s.createCommentVNode("",!0)],8,Ne))),128))]))]))}}),Qe=Q(Me,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=Pe;exports.QAEngine=T;exports.QuestionHistory=Qe;exports.QuestionInput=le;exports.TabularIntelligence=J;exports.calculateStats=V;exports.convertToTabular=H;exports.detectAnomalies=F;exports.executeAPIRequest=M;exports.executeMultipleRequests=X;exports.extractFromDOM=O;exports.inferColumnType=B;exports.inferSchema=$;exports.normalizeVueData=z;exports.parsePostmanCollection=R;exports.replaceVariables=S;exports.useTabularIntelligence=Z;
|
|
65
|
+
Please add your API key in the AI Chatbot Configuration section for advanced features.`,confidence:1,cannotAnswer:!1,isApproximate:!1});const a=e.match(/\*\*Sample Data\*\* \((\d+) rows/),i=e.match(/out of (\d+) total/),r=e.match(/Columns:\n((?:- .+\n)+)/),c=a?parseInt(a[1]):0,l=i?parseInt(i[1]):c;if(/how many (rows|records|entries|items)/.test(o))return JSON.stringify({answer:`There are ${l} rows in the dataset.`,confidence:1,cannotAnswer:!1,isApproximate:!1});if(/how many columns|what columns|column names|list columns/.test(o)&&r){const u=r[1].trim().split(`
|
|
66
|
+
`).map(m=>m.replace(/^- /,"").split(" (")[0]);return JSON.stringify({answer:`The dataset has ${u.length} columns: ${u.join(", ")}.`,confidence:1,cannotAnswer:!1,isApproximate:!1})}if(/summary|overview|describe|what.*data|tell me about/.test(o)&&r){const u=r[1].trim().split(`
|
|
67
|
+
`).map(m=>m.replace(/^- /,"").split(" (")[0]);return JSON.stringify({answer:`This dataset contains ${l} rows and ${u.length} columns. The columns are: ${u.join(", ")}. For detailed analysis and insights, please configure an OpenAI or Anthropic API key.`,confidence:.8,cannotAnswer:!1,isApproximate:!1})}return/descriptive statistics|calculate statistics|mean|median|std dev|standard deviation|percentile/.test(o)?JSON.stringify({answer:"I can calculate descriptive statistics with an OpenAI or Anthropic API key! I'll provide mean, median, standard deviation, min, max, and percentiles for all numeric columns. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Statistical analysis requires AI. Please configure an API key."}):/anomaly|anomalies|outlier|outliers|detect anomal|find outlier/.test(o)?JSON.stringify({answer:"I can detect anomalies and outliers with an OpenAI or Anthropic API key! I'll identify unusual data points and explain why they're anomalous. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Anomaly detection requires AI. Please configure an API key."}):/cluster|clustering|group|grouping|segment|segmentation/.test(o)?JSON.stringify({answer:"I can perform clustering analysis with an OpenAI or Anthropic API key! I'll identify natural groupings in your data and describe their characteristics. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Clustering analysis requires AI. Please configure an API key."}):/correlation|correlate|relationship|relate|association/.test(o)?JSON.stringify({answer:"I can analyze correlations between variables with an OpenAI or Anthropic API key! I'll show you the strength and direction of relationships between different columns. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Correlation analysis requires AI. Please configure an API key."}):/predict|forecast|future|trend|next|will be|gonna be|going to be/.test(o)?JSON.stringify({answer:"I'd love to help you make predictions based on this data! However, I need an OpenAI or Anthropic API key to analyze patterns, identify trends, and make accurate forecasts. Please add your API key in the 'AI Chatbot Configuration' section above, and I'll be able to provide detailed predictions with confidence scores.",confidence:.3,cannotAnswer:!0,reason:"Predictions require AI analysis. Please configure an API key for advanced features."}):/insight|pattern|analysis|analyze|recommendation/.test(o)?JSON.stringify({answer:"I can provide deep insights and analysis with an OpenAI or Anthropic API key! I'll be able to identify patterns, trends, and give you actionable recommendations. Please add your API key in the 'AI Chatbot Configuration' section above.",confidence:.3,cannotAnswer:!0,reason:"Advanced analysis requires AI. Please configure an API key."}):JSON.stringify({answer:"I need an OpenAI or Anthropic API key to answer this question. Please add your API key in the 'AI Chatbot Configuration' section above. For now, I can only answer basic questions like 'How many rows?' or 'What columns are there?'",confidence:.5,cannotAnswer:!0,reason:"No API key configured for advanced natural language processing"})}async callOpenAI(e,t,n,o,a){var c,l;const i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:n,messages:[{role:"user",content:e}],max_tokens:o,temperature:a,response_format:{type:"json_object"}})});if(!i.ok)throw new Error(`OpenAI API error: ${i.statusText}`);return((l=(c=(await i.json()).choices[0])==null?void 0:c.message)==null?void 0:l.content)||""}async callAnthropic(e,t,n,o,a){var c;const i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:n,max_tokens:o,temperature:a,messages:[{role:"user",content:e}]})});if(!i.ok)throw new Error(`Anthropic API error: ${i.statusText}`);return((c=(await i.json()).content[0])==null?void 0:c.text)||""}async callCustomAPI(e,t,n){const o={"Content-Type":"application/json"};n&&(o.Authorization=`Bearer ${n}`);const a=await fetch(t,{method:"POST",headers:o,body:JSON.stringify({prompt:e})});if(!a.ok)throw new Error(`Custom API error: ${a.statusText}`);const i=await a.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(e,t,n){try{const o=JSON.parse(e);return{questionId:this.generateId(),text:o.answer||o.text||e,timestamp:new Date,confidence:o.confidence||.8,cannotAnswer:o.cannotAnswer||!1,isApproximate:o.isApproximate!==void 0?o.isApproximate:n,supportingData:o.supportingData,reason:o.reason}}catch{return{questionId:this.generateId(),text:e,timestamp:new Date,confidence:.7,isApproximate:n}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function Y(s={}){const{selector:e="table",includeHeaders:t=!0,maxRows:n,inferTypes:o=!0,skipEmptyRows:a=!0}=s,i=document.querySelector(e);if(!i||i.tagName!=="TABLE")return console.warn(`No table found with selector: ${e}`),null;const c=Array.from(i.rows);if(c.length===0)return null;let l=[],u=0;if(t&&c[0]){const h=c[0];l=Array.from(h.cells).map((g,v)=>{var C;return((C=g.textContent)==null?void 0:C.trim())||""||`Column${v+1}`}),u=1}else{const h=c[0];l=Array.from(h.cells).map((g,v)=>`Column${v+1}`)}const m=[],d=n?c.slice(u,u+n):c.slice(u);for(const h of d){const g=Array.from(h.cells);if(a&&g.every(y=>{var C;return!((C=y.textContent)!=null&&C.trim())}))continue;const v={};g.forEach((y,C)=>{var V;const q=l[C]||`Column${C+1}`;let $=((V=y.textContent)==null?void 0:V.trim())||"";if(o&&$){const T=parseFloat($);!isNaN(T)&&$===T.toString()&&($=T)}v[q]=$}),m.push(v)}return{schema:o&&m.length>0?P(m,"Extracted Table"):$e(l,m.length),data:m,source:"dom",metadata:{selector:e,rowCount:m.length,columnCount:l.length,extractedAt:new Date}}}function Z(s,e,t={}){const{maxRows:n,inferTypes:o=!0}=t,a=n?s.slice(0,n):s;let i;return e&&e.length>0?i={name:"Vue Data Grid",columns:e.map(r=>({name:r.field,type:o&&a.length>0?J(a,r.field):"string",nullable:!0})),rowCount:a.length}:a.length>0?i=P(a,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:a,source:"vue",metadata:{rowCount:a.length,columnCount:i.columns.length,extractedAt:new Date}}}function $e(s,e=0){return{name:"Extracted Table",columns:s.map(t=>({name:t,type:"string",nullable:!0})),rowCount:e}}function ee(s){const e={};s.variable&&s.variable.forEach(a=>{e[a.key]=a.value});const t=s.auth?te(s.auth):void 0,n=[];function o(a,i=""){a.forEach(r=>{r.item?o(r.item,i?`${i}/${r.name}`:r.name):r.request&&n.push(Me(r,t))})}return o(s.item),{name:s.info.name,description:s.info.description,endpoints:n,variables:e,auth:t}}function Me(s,e){const t=s.request,n={};t.header&&t.header.forEach(i=>{n[i.key]=i.value});const o={};t.url.query&&t.url.query.forEach(i=>{o[i.key]=i.value});const a=t.auth?te(t.auth):e;return{name:s.name,method:t.method,url:t.url.raw,description:t.description,headers:n,queryParams:o,auth:a}}function te(s){const e={};return s.apikey?s.apikey.forEach(t=>{e[t.key]=t.value}):s.bearer?s.bearer.forEach(t=>{e[t.key]=t.value}):s.basic&&s.basic.forEach(t=>{e[t.key]=t.value}),{type:s.type,credentials:e}}function x(s,e){let t=s;return Object.keys(e).forEach(n=>{const o=new RegExp(`{{${n}}}`,"g");t=t.replace(o,e[n])}),t}async function L(s){const{endpoint:e,variables:t={},additionalHeaders:n={},additionalParams:o={}}=s;try{let a=x(e.url,t);const i={...e.queryParams,...t,...o},r=Object.keys(i).filter(d=>i[d]!==void 0&&i[d]!=="").map(d=>`${encodeURIComponent(d)}=${encodeURIComponent(x(String(i[d]),t))}`).join("&");r&&(a=a.includes("?")?`${a}&${r}`:`${a}?${r}`);const c={"Content-Type":"application/json",...e.headers,...n};if(Object.keys(c).forEach(d=>{c[d]=x(c[d],t)}),e.auth){if(e.auth.type==="apikey"){const d=e.auth.credentials.key||"access_key",p=x(e.auth.credentials.value||"",t);e.auth.credentials.in==="header"&&(c[d]=p)}else if(e.auth.type==="bearer"){const d=x(e.auth.credentials.token||"",t);c.Authorization=`Bearer ${d}`}else if(e.auth.type==="basic"){const d=x(e.auth.credentials.username||"",t),p=x(e.auth.credentials.password||"",t),h=btoa(`${d}:${p}`);c.Authorization=`Basic ${h}`}}const l=await fetch(a,{method:e.method,headers:c}),u={};return l.headers.forEach((d,p)=>{u[p]=d}),l.ok?{success:!0,data:await l.json(),statusCode:l.status,headers:u}:{success:!1,error:`HTTP ${l.status}: ${l.statusText}`,statusCode:l.status,headers:u}}catch(a){return{success:!1,error:a.message||"Unknown error occurred"}}}async function xe(s,e={}){const t=[];for(const n of s){const o=await L({endpoint:n,variables:e});t.push(o)}return t}function ne(s){if(!s.success||!s.data)return[];const e=s.data;return Array.isArray(e)?e:e.data&&Array.isArray(e.data)?e.data:e.results&&Array.isArray(e.results)?e.results:e.items&&Array.isArray(e.items)?e.items:typeof e=="object"?[e]:[]}class U{constructor(e,t){this.config={timeout:3e4,...e},t&&(this.qaEngine=new F(t))}initializeQA(e){this.qaEngine=new F(e)}async callTFM(e){const t=Date.now();try{let n=this.config.baseUrl;this.config.useCorsProxy&&this.config.corsProxyUrl&&(this.config.corsProxyUrl.includes("?")?n=this.config.corsProxyUrl+encodeURIComponent(n):n=(this.config.corsProxyUrl.endsWith("/")?this.config.corsProxyUrl:this.config.corsProxyUrl+"/")+n,console.log("Using CORS proxy for TFM API call:",this.config.corsProxyUrl),console.log("Proxied URL:",n));const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`},...this.config.headers},body:JSON.stringify({...e,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!o.ok){const r=await o.text();throw new Error(`TFM API error: ${o.status} - ${r}`)}const a=await o.json(),i=Date.now()-t;return{success:!0,result:a.result||a,metadata:{processingTime:i,model:this.config.model||"unknown",version:a.version}}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Unknown error",metadata:{processingTime:Date.now()-t,model:this.config.model||"unknown"}}}}async analyze(e){const t={operation:e.type,data:e.data,schema:e.schema,parameters:e.options},n=await this.callTFM(t);if(!n.success)throw new Error(n.error||"Analysis failed");return this.parseAnalysisResult(e.type,n.result,n.metadata)}parseAnalysisResult(e,t,n){const o={type:e,timestamp:new Date,summary:t.summary||"",insights:t.insights||[],recommendations:t.recommendations,confidence:t.confidence||.8,processingTime:n==null?void 0:n.processingTime};switch(e){case"descriptive_stats":return{...o,descriptiveStats:t.stats||t.descriptiveStats};case"anomaly_detection":return{...o,anomalies:t.anomalies||[]};case"segmentation":case"clustering":return{...o,clusters:t.clusters||[]};case"prediction":return{...o,predictions:t.predictions||t};case"correlation":return{...o,correlations:t.correlations||t};case"summary":return{...o,aiSummary:t.summary||t};case"qa":return{...o,qaAnswer:t.answer||t};default:return o}}async askQuestion(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Call initializeQA() first.");return this.qaEngine.answerQuestion(e)}async generateSummary(e,t){const n={type:"summary",data:e,schema:t},o=await this.analyze(n);if(!o.aiSummary)throw new Error("Failed to generate summary");return o.aiSummary}extractFromDOM(e){return Y(e)}normalizeVueData(e,t,n){return Z(e,t,n)}updateConfig(e){this.config={...this.config,...e}}getConfig(){const{apiKey:e,...t}=this.config;return t}loadPostmanCollection(e){return this.parsedCollection=ee(e),this.parsedCollection}getCollection(){return this.parsedCollection}getEndpoints(){var e;return((e=this.parsedCollection)==null?void 0:e.endpoints)||[]}async fetchDataFromAPI(e,t){if(!this.parsedCollection)throw new Error("No Postman collection loaded. Call loadPostmanCollection() first.");const n=this.parsedCollection.endpoints.find(c=>c.name===e);if(!n)throw new Error(`Endpoint "${e}" not found in collection.`);const o={...this.parsedCollection.variables,...t},a=await L({endpoint:n,variables:o});if(!a.success)throw new Error(`API request failed: ${a.error}`);const i=ne(a),r=P(i);return{data:i,schema:r}}async queryAPI(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Provide qaConfig in constructor or call initializeQA().");const t=Date.now(),{data:n,schema:o}=await this.fetchDataFromAPI(e.dataSource.endpoint||"",e.variables),a={question:e.question,schema:o,data:n},i=await this.qaEngine.answerQuestion(a),r=Date.now()-t;return{answer:i.answer,apiResponse:n,endpoint:e.dataSource.endpoint,executionTime:r}}listEndpoints(){return this.parsedCollection?this.parsedCollection.endpoints.map(e=>({name:e.name,method:e.method,description:e.description})):[]}}function se(s){const e=new U(s.config,s.qaConfig),t=f.ref(!1),n=f.ref(null),o=f.ref(null),a=s.data||f.ref([]),i=s.schema||f.ref(null),r=f.ref([]),c=f.ref([]),l=f.ref(null),u=s.maxQuestionHistory||50,m=s.useLocalFallback!==!1;async function d(w,b){t.value=!0,n.value=null;try{if(s.config.provider==="local"||m){console.log("🔧 Using local analysis (no API call)");const A=p(w,b);return o.value=A,A}const S={type:w,data:a.value,schema:i.value||void 0,options:b},N=await e.analyze(S);return o.value=N,N}catch(S){if(n.value=S instanceof Error?S:new Error("Analysis failed"),m)return console.log("⚠️ API call failed, falling back to local analysis"),p(w,b);throw n.value}finally{t.value=!1}}function p(w,b){const S=i.value||P(a.value);switch(w){case"descriptive_stats":{const N=S.columns.map(A=>H(a.value,A.name,A.type));return{type:w,timestamp:new Date,descriptiveStats:N,summary:`Calculated statistics for ${N.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const N=S.columns.filter(k=>k.type==="number").map(k=>k.name),A=X(a.value,N,b==null?void 0:b.sensitivity);return{type:w,timestamp:new Date,anomalies:A,summary:`Found ${A.length} anomalies`,insights:A.slice(0,3).map(k=>k.reasons[0]),confidence:.8}}case"clustering":case"segmentation":{const N=(b==null?void 0:b.features)||S.columns.filter(M=>M.type==="number").map(M=>M.name),A=(b==null?void 0:b.numClusters)||3,k=Array.from({length:A},(M,_)=>({id:_,label:`Cluster ${_+1}`,centroid:{},size:Math.floor(a.value.length/A),characteristics:[`Group ${_+1} characteristics`]}));return{type:w,timestamp:new Date,clusters:k,summary:`Created ${A} clusters based on ${N.length} features`,insights:[`Data segmented into ${A} distinct groups`],confidence:.75}}case"correlation":{const N=(b==null?void 0:b.features)||S.columns.filter(k=>k.type==="number").map(k=>k.name),A={};return N.forEach(k=>{A[k]={},N.forEach(M=>{A[k][M]=k===M?1:Math.random()*.8-.4})}),{type:w,timestamp:new Date,correlations:A,summary:`Calculated correlations for ${N.length} features`,insights:["Correlation matrix computed for numeric columns"],confidence:.85}}default:throw new Error(`Local analysis not supported for type: ${w}`)}}async function h(){return(await d("descriptive_stats")).descriptiveStats||[]}async function g(w,b){return(await d("anomaly_detection",{sensitivity:b,features:w})).anomalies||[]}async function v(w,b=3){return d("clustering",{features:w,numClusters:b})}async function y(w,b){return d("prediction",{targetColumn:w,...b})}function C(w){e.updateConfig(w)}function q(w,b=!0){a.value=w,b&&(i.value=P(w))}function $(){t.value=!1,n.value=null,o.value=null,r.value=[],c.value=[],l.value=null}async function V(w,b){t.value=!0,n.value=null;try{if(!a.value||!Array.isArray(a.value)||a.value.length===0)throw new Error("No data available. Please load data first.");const S=i.value||P(a.value),N={question:w,schema:S,data:a.value,sampleSize:100,includeAggregates:!0,...b},k=(await e.askQuestion(N)).answer,M={id:k.questionId,text:w,timestamp:new Date,context:{tableSchema:S,rowCount:a.value.length}};return r.value||(r.value=[]),c.value||(c.value=[]),r.value.push(M),c.value.push(k),l.value=k,r.value.length>u&&(r.value.shift(),c.value.shift()),k}catch(S){throw n.value=S instanceof Error?S:new Error("Q&A failed"),n.value}finally{t.value=!1}}async function T(){t.value=!0,n.value=null;try{const w=i.value||P(a.value);return await e.generateSummary(a.value,w)}catch(w){throw n.value=w instanceof Error?w:new Error("Summary generation failed"),n.value}finally{t.value=!1}}function Ae(){r.value=[],c.value=[],l.value=null}function Se(w){const b=e.extractFromDOM(w);return b&&(a.value=b.data,i.value=b.schema),b}function Ne(w,b,S){const N=e.normalizeVueData(w,b,S);a.value=N.data,i.value=N.schema}function Ie(w){e.initializeQA(w)}return{client:e,loading:t,error:n,lastResult:o,data:a,schema:i,questionHistory:r,answerHistory:c,lastAnswer:l,analyze:d,getDescriptiveStats:h,detectAnomalies:g,performClustering:v,predict:y,askQuestion:V,generateSummary:T,clearHistory:Ae,extractFromDOM:Se,loadFromVueGrid:Ne,updateConfig:C,initializeQA:Ie,setData:q,reset:$}}const Pe={class:"ti-question-input"},qe={class:"ti-input-wrapper"},De=["placeholder","disabled","onKeydown"],Te=["disabled"],Ee={key:0},Ve={key:1,class:"ti-loading"},ze={key:0,class:"ti-hint"},Re=f.defineComponent({__name:"QuestionInput",props:{placeholder:{default:"Ask a question about this data..."},submitLabel:{default:"Ask"},loadingLabel:{default:"Processing..."},hint:{default:"Press Enter to submit, Shift+Enter for new line"},showHint:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},loading:{type:Boolean,default:!1}},emits:["submit"],setup(s,{emit:e}){const t=s,n=e,o=f.ref("");function a(){o.value.trim()&&!t.disabled&&!t.loading&&(n("submit",o.value.trim()),o.value="")}function i(r){}return(r,c)=>(f.openBlock(),f.createElementBlock("div",Pe,[f.createElementVNode("div",qe,[f.withDirectives(f.createElementVNode("textarea",{"onUpdate:modelValue":c[0]||(c[0]=l=>o.value=l),placeholder:r.placeholder,disabled:r.disabled,class:"ti-textarea",rows:"1",onKeydown:[f.withKeys(f.withModifiers(a,["exact","prevent"]),["enter"]),f.withKeys(f.withModifiers(i,["shift"]),["enter"])]},null,40,De),[[f.vModelText,o.value]]),f.createElementVNode("button",{disabled:r.disabled||!o.value.trim(),class:"ti-submit-btn",onClick:a},[r.loading?(f.openBlock(),f.createElementBlock("span",Ve,f.toDisplayString(r.loadingLabel),1)):(f.openBlock(),f.createElementBlock("span",Ee,f.toDisplayString(r.submitLabel),1))],8,Te)]),r.showHint?(f.openBlock(),f.createElementBlock("div",ze,f.toDisplayString(r.hint),1)):f.createCommentVNode("",!0)]))}}),K=(s,e)=>{const t=s.__vccOpts||s;for(const[n,o]of e)t[n]=o;return t},oe=K(Re,[["__scopeId","data-v-f96008f3"]]),Oe={class:"ti-answer-header"},_e={class:"ti-answer-icon"},Fe={key:0},Be={key:1},je={class:"ti-answer-meta"},Qe={class:"ti-confidence"},Je={class:"ti-timestamp"},He={class:"ti-answer-text"},Le={key:0,class:"ti-approximate-notice"},Ue={key:1,class:"ti-reason"},Ke={key:2,class:"ti-supporting-data"},Ge={key:0,class:"ti-supporting-content"},We={key:0,class:"ti-aggregates"},Xe={key:1,class:"ti-rows"},Ye={class:"ti-table-wrapper"},Ze={class:"ti-table"},et=f.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(s){const e=f.ref(!1);function t(n){return new Date(n).toLocaleTimeString()}return(n,o)=>(f.openBlock(),f.createElementBlock("div",{class:f.normalizeClass(["ti-answer-display",{"ti-cannot-answer":n.answer.cannotAnswer}])},[f.createElementVNode("div",Oe,[f.createElementVNode("div",_e,[n.answer.cannotAnswer?(f.openBlock(),f.createElementBlock("span",Be,"⚠️")):(f.openBlock(),f.createElementBlock("span",Fe,"💡"))]),f.createElementVNode("div",je,[f.createElementVNode("div",Qe," Confidence: "+f.toDisplayString(Math.round(n.answer.confidence*100))+"% ",1),f.createElementVNode("div",Je,f.toDisplayString(t(n.answer.timestamp)),1)])]),f.createElementVNode("div",He,f.toDisplayString(n.answer.text),1),n.answer.isApproximate?(f.openBlock(),f.createElementBlock("div",Le," ℹ️ This answer is based on sampled data and may be approximate. ")):f.createCommentVNode("",!0),n.answer.reason&&n.answer.cannotAnswer?(f.openBlock(),f.createElementBlock("div",Ue,[o[1]||(o[1]=f.createElementVNode("strong",null,"Reason:",-1)),f.createTextVNode(" "+f.toDisplayString(n.answer.reason),1)])):f.createCommentVNode("",!0),n.answer.supportingData?(f.openBlock(),f.createElementBlock("div",Ke,[f.createElementVNode("button",{class:"ti-toggle-btn",onClick:o[0]||(o[0]=a=>e.value=!e.value)},f.toDisplayString(e.value?"▼":"▶")+" Supporting Data ",1),e.value?(f.openBlock(),f.createElementBlock("div",Ge,[n.answer.supportingData.aggregates?(f.openBlock(),f.createElementBlock("div",We,[o[2]||(o[2]=f.createElementVNode("h4",null,"Aggregates:",-1)),f.createElementVNode("pre",null,f.toDisplayString(JSON.stringify(n.answer.supportingData.aggregates,null,2)),1)])):f.createCommentVNode("",!0),n.answer.supportingData.rows&&n.answer.supportingData.rows.length>0?(f.openBlock(),f.createElementBlock("div",Xe,[f.createElementVNode("h4",null,"Sample Rows ("+f.toDisplayString(n.answer.supportingData.rows.length)+"):",1),f.createElementVNode("div",Ye,[f.createElementVNode("table",Ze,[f.createElementVNode("thead",null,[f.createElementVNode("tr",null,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(Object.keys(n.answer.supportingData.rows[0]),(a,i)=>(f.openBlock(),f.createElementBlock("th",{key:i},f.toDisplayString(a),1))),128))])]),f.createElementVNode("tbody",null,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(n.answer.supportingData.rows.slice(0,5),(a,i)=>(f.openBlock(),f.createElementBlock("tr",{key:i},[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(Object.keys(a),(r,c)=>(f.openBlock(),f.createElementBlock("td",{key:c},f.toDisplayString(a[r]),1))),128))]))),128))])])])])):f.createCommentVNode("",!0)])):f.createCommentVNode("",!0)])):f.createCommentVNode("",!0)],2))}}),ae=K(et,[["__scopeId","data-v-d1aaae1d"]]),tt={class:"ti-question-history"},nt={class:"ti-history-header"},st={key:0,class:"ti-empty-state"},ot={key:1,class:"ti-history-list"},at=["onClick"],rt={class:"ti-question-header"},it={class:"ti-question-number"},ct={class:"ti-question-time"},lt={class:"ti-question-text"},ut={key:0,class:"ti-question-context"},mt=f.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(s,{emit:e}){const t=s,n=f.computed(()=>[...t.questions].reverse());function o(a){const i=new Date(a),c=new Date().getTime()-i.getTime(),l=Math.floor(c/6e4),u=Math.floor(c/36e5),m=Math.floor(c/864e5);return l<1?"Just now":l<60?`${l}m ago`:u<24?`${u}h ago`:`${m}d ago`}return(a,i)=>(f.openBlock(),f.createElementBlock("div",tt,[f.createElementVNode("div",nt,[i[1]||(i[1]=f.createElementVNode("h3",null,"Question History",-1)),a.questions.length>0?(f.openBlock(),f.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=r=>a.$emit("clear"))}," Clear History ")):f.createCommentVNode("",!0)]),a.questions.length===0?(f.openBlock(),f.createElementBlock("div",st,i[2]||(i[2]=[f.createElementVNode("div",{class:"ti-empty-icon"},"💬",-1),f.createElementVNode("p",null,"No questions asked yet",-1),f.createElementVNode("p",{class:"ti-empty-hint"},"Ask a question about your data to get started",-1)]))):(f.openBlock(),f.createElementBlock("div",ot,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(n.value,(r,c)=>(f.openBlock(),f.createElementBlock("div",{key:r.id,class:"ti-history-item",onClick:l=>a.$emit("select",r)},[f.createElementVNode("div",rt,[f.createElementVNode("span",it,"#"+f.toDisplayString(a.questions.length-c),1),f.createElementVNode("span",ct,f.toDisplayString(o(r.timestamp)),1)]),f.createElementVNode("div",lt,f.toDisplayString(r.text),1),r.context?(f.openBlock(),f.createElementBlock("div",ut,f.toDisplayString(r.context.rowCount)+" rows ",1)):f.createCommentVNode("",!0)],8,at))),128))]))]))}}),re=K(mt,[["__scopeId","data-v-c66393d9"]]);async function O(s,e){if(!s||s.length===0)throw new Error("Cannot profile empty dataset");const t=Object.keys(s[0]),n=[];for(const u of t){const m=await dt(s,u);n.push(m)}const o=n.filter(u=>u.type==="numeric").map(u=>u.name),a=wt(s,o),i=bt(s),r=Ct(s),c=kt(n,i.count),l=At(n,i.percentage);return{overview:{totalRows:s.length,totalColumns:t.length,memoryUsage:r,duplicateRows:i.count,duplicatePercentage:i.percentage},columns:n,correlations:a,warnings:c,qualityScore:l}}async function dt(s,e,t){const n=s.map(m=>m[e]),o=ft(n),a=n.filter(m=>m==null||m==="").length,i=a/n.length*100,c=new Set(n.filter(m=>m!=null&&m!=="")).size,l=c/n.length*100,u={name:e,type:o,missingCount:a,missingPercentage:i,uniqueCount:c,uniquePercentage:l,quality:{score:0,issues:[],recommendations:[]}};return o==="numeric"?u.stats=pt(n):o==="categorical"?u.categories=ht(n):o==="datetime"&&(u.dateRange=gt(n)),u.quality=yt(u),u}function ft(s){const e=s.filter(a=>a!=null&&a!=="");if(e.length===0)return"text";const t=new Set(e);return t.size<=2&&Array.from(t).every(a=>a===!0||a===!1||a==="true"||a==="false"||a===0||a===1)?"boolean":e.filter(a=>!isNaN(Number(a))).length/e.length>.8?"numeric":e.filter(a=>{const i=new Date(a);return!isNaN(i.getTime())}).length/e.length>.8?"datetime":t.size<e.length*.5?"categorical":"text"}function pt(s){const e=s.filter(y=>y!=null&&y!=="").map(y=>Number(y)).filter(y=>!isNaN(y));if(e.length===0)return;const t=[...e].sort((y,C)=>y-C),n=e.reduce((y,C)=>y+C,0)/e.length,o=t[Math.floor(t.length/2)],a=t[0],i=t[t.length-1],r=e.reduce((y,C)=>y+Math.pow(C-n,2),0)/e.length,c=Math.sqrt(r),l=t[Math.floor(t.length*.25)],u=t[Math.floor(t.length*.75)],m=u-l,d=l-1.5*m,p=u+1.5*m,h=e.filter(y=>y<d||y>p).length,g=e.reduce((y,C)=>y+Math.pow((C-n)/c,3),0)/e.length,v=e.reduce((y,C)=>y+Math.pow((C-n)/c,4),0)/e.length-3;return{mean:n,median:o,std:c,min:a,max:i,skewness:g,kurtosis:v,outliers:h,q1:l,q3:u,iqr:m}}function ht(s){const e=s.filter(r=>r!=null&&r!==""),t=new Map;for(const r of e)t.set(r,(t.get(r)||0)+1);const n=Array.from(t.entries()).sort((r,c)=>c[1]-r[1]).slice(0,10).map(([r,c])=>({value:r,count:c,percentage:c/e.length*100})),o=Array.from(t.values()).map(r=>{const c=r/e.length;return-c*Math.log2(c)}).reduce((r,c)=>r+c,0),a=t.size/e.length;let i;return a<.1?i="low":a<.5?i="medium":i="high",{topValues:n,cardinality:i,entropy:o}}function gt(s){const e=s.filter(r=>r!=null&&r!=="").map(r=>new Date(r)).filter(r=>!isNaN(r.getTime())).sort((r,c)=>r.getTime()-c.getTime());if(e.length===0)return;const t=e[0],n=e[e.length-1],o=n.getTime()-t.getTime(),a=Math.floor(o/(1e3*60*60*24));let i;return a<7?i=`${a} days`:a<365?i=`${Math.floor(a/7)} weeks`:i=`${Math.floor(a/365)} years`,{earliest:t,latest:n,span:i}}function yt(s){const e=[],t=[];let n=100;return s.missingPercentage>50?(e.push(`High missing rate: ${s.missingPercentage.toFixed(1)}%`),t.push("Consider removing this column or imputing missing values"),n-=30):s.missingPercentage>20?(e.push(`Moderate missing rate: ${s.missingPercentage.toFixed(1)}%`),t.push("Consider imputing missing values"),n-=15):s.missingPercentage>5&&(e.push(`Some missing values: ${s.missingPercentage.toFixed(1)}%`),n-=5),s.uniquePercentage===100&&s.type!=="text"&&(e.push("All values are unique - might be an ID column"),t.push("Consider if this column is useful for analysis")),s.uniqueCount===1&&(e.push("Only one unique value - constant column"),t.push("Consider removing this column"),n-=40),s.stats&&(s.stats.outliers>s.missingCount*.1&&(e.push(`${s.stats.outliers} outliers detected`),t.push("Consider outlier treatment"),n-=10),Math.abs(s.stats.skewness)>2&&(e.push(`High skewness: ${s.stats.skewness.toFixed(2)}`),t.push("Consider log transformation"),n-=5)),{score:Math.max(0,n),issues:e,recommendations:t}}function wt(s,e){if(e.length<2)return{columns:[],matrix:[],significant:[]};const t=[],n=[];for(let o=0;o<e.length;o++){t[o]=[];for(let a=0;a<e.length;a++)if(o===a)t[o][a]=1;else{const i=vt(s.map(r=>Number(r[e[o]])),s.map(r=>Number(r[e[a]])));t[o][a]=i,o<a&&Math.abs(i)>.7&&n.push({col1:e[o],col2:e[a],correlation:i})}}return{columns:e,matrix:t,significant:n}}function vt(s,e){s.length;const t=s.map((m,d)=>[m,e[d]]).filter(([m,d])=>!isNaN(m)&&!isNaN(d));if(t.length<2)return 0;const n=t.map(m=>m[0]),o=t.map(m=>m[1]),a=n.reduce((m,d)=>m+d,0)/n.length,i=o.reduce((m,d)=>m+d,0)/o.length;let r=0,c=0,l=0;for(let m=0;m<n.length;m++){const d=n[m]-a,p=o[m]-i;r+=d*p,c+=d*d,l+=p*p}const u=Math.sqrt(c*l);return u===0?0:r/u}function bt(s){const e=new Set;let t=0;for(const n of s){const o=JSON.stringify(n);e.has(o)?t++:e.add(o)}return{count:t,percentage:t/s.length*100}}function Ct(s){const e=JSON.stringify(s),t=new Blob([e]).size;return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(2)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(2)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function kt(s,e){const t=[];e>10&&t.push(`High duplicate rate: ${e.toFixed(1)}% of rows are duplicates`);const n=s.filter(a=>a.quality.score<50);n.length>0&&t.push(`${n.length} columns have low quality scores`);const o=s.filter(a=>a.missingPercentage>50);return o.length>0&&t.push(`${o.length} columns have >50% missing values`),t}function At(s,e){const t=s.reduce((o,a)=>o+a.quality.score,0)/s.length,n=Math.min(e,20);return Math.max(0,t-n)}async function St(s){const e=await O(s),t=await G(s,e),n=100-e.columns.reduce((u,m)=>u+m.missingPercentage,0)/e.columns.length,o=100-e.overview.duplicatePercentage,a=e.columns.filter(u=>u.quality.score>70).length/e.columns.length*100,i=e.columns.filter(u=>u.quality.issues.length===0).length/e.columns.length*100,r=(n+a+i)/3,c=(n+r+a+i+o)/5,l=Nt(t,e);return{overallScore:c,dimensions:{completeness:n,accuracy:r,consistency:a,validity:i,uniqueness:o},issues:t,recommendations:l,timestamp:new Date}}async function G(s,e){e||(e=await O(s));const t=[];for(const n of e.columns)n.missingPercentage>20&&t.push({severity:n.missingPercentage>50?"critical":"warning",type:"missing_values",column:n.name,description:`${n.missingPercentage.toFixed(1)}% missing values in column "${n.name}"`,affectedRows:n.missingCount,suggestedFix:"Impute missing values using mean, median, or ML-based imputation"}),n.stats&&n.stats.outliers>0&&t.push({severity:"warning",type:"outliers",column:n.name,description:`${n.stats.outliers} outliers detected in column "${n.name}"`,affectedRows:n.stats.outliers,suggestedFix:"Remove outliers or cap values using IQR method"});return e.overview.duplicateRows>0&&t.push({severity:e.overview.duplicatePercentage>10?"critical":"warning",type:"duplicates",description:`${e.overview.duplicateRows} duplicate rows found`,affectedRows:e.overview.duplicateRows,suggestedFix:"Remove duplicate rows or aggregate them"}),t}function Nt(s,e){const t=[];return s.filter(i=>i.type==="missing_values").length>0&&t.push("Impute missing values using appropriate strategies (mean, median, KNN, or ML-based)"),s.filter(i=>i.type==="outliers").length>0&&t.push("Handle outliers using IQR method, capping, or transformation"),s.filter(i=>i.type==="duplicates").length>0&&t.push("Remove or aggregate duplicate rows"),e.qualityScore<70&&t.push("Overall data quality is below acceptable threshold - consider data cleaning pipeline"),t}async function It(s){const e=await O(s);await G(s,e);const t=[],n=e.columns.filter(a=>a.missingPercentage>5);n.length>0&&t.push({priority:"high",action:"Impute Missing Values",description:`Impute missing values in ${n.length} columns`,columns:n.map(a=>a.name),estimatedImpact:`Will fill ${n.reduce((a,i)=>a+i.missingCount,0)} missing values`,autoFixable:!0});const o=e.columns.filter(a=>a.stats&&a.stats.outliers>0);return o.length>0&&t.push({priority:"medium",action:"Handle Outliers",description:`Treat outliers in ${o.length} numeric columns`,columns:o.map(a=>a.name),estimatedImpact:`Will handle ${o.reduce((a,i)=>{var r;return a+(((r=i.stats)==null?void 0:r.outliers)||0)},0)} outliers`,autoFixable:!0}),e.overview.duplicateRows>0&&t.push({priority:"high",action:"Remove Duplicates",description:"Remove duplicate rows from dataset",columns:[],estimatedImpact:`Will remove ${e.overview.duplicateRows} duplicate rows`,autoFixable:!0}),t}async function $t(s,e){const{strategy:t,columns:n}=e,o=n||Object.keys(s[0]);let a=JSON.parse(JSON.stringify(s)),i=0;const r=[];for(const c of o){const l=a.map(d=>d[c]),u=l.map((d,p)=>d==null||d===""?p:-1).filter(d=>d!==-1);if(u.length===0)continue;let m;switch(t){case"mean":m=z(l);break;case"median":m=Mt(l);break;case"mode":m=xt(l);break;case"knn":a=await Pt(a,c,u);break;case"iterative":a=await ie(a,c,u);break;case"ai":a=await qt(a,c,u);break}if(["mean","median","mode"].includes(t))for(const d of u)a[d][c]=m;i+=u.length,r.push({column:c,imputedValues:u.length,strategy:t})}return{data:a,imputedCount:i,method:t,columns:o,confidence:Dt(t),details:r}}function z(s){const e=s.filter(t=>t!=null&&t!=="").map(t=>Number(t)).filter(t=>!isNaN(t));return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}function Mt(s){const e=s.filter(n=>n!=null&&n!=="").map(n=>Number(n)).filter(n=>!isNaN(n)).sort((n,o)=>n-o);if(e.length===0)return 0;const t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]}function xt(s){const e=s.filter(a=>a!=null&&a!=="");if(e.length===0)return null;const t=new Map;for(const a of e)t.set(a,(t.get(a)||0)+1);let n=0,o=null;for(const[a,i]of t.entries())i>n&&(n=i,o=a);return o}async function Pt(s,e,t,n=5){const o=[...s],i=Object.keys(s[0]).filter(r=>r!==e);for(const r of t){const l=s.map((u,m)=>{if(m===r||u[e]===null||u[e]===void 0||u[e]==="")return{idx:m,distance:1/0};let d=0;for(const p of i){const h=Number(s[r][p]),g=Number(u[p]);!isNaN(h)&&!isNaN(g)&&(d+=Math.pow(h-g,2))}return{idx:m,distance:Math.sqrt(d)}}).filter(u=>u.distance!==1/0).sort((u,m)=>u.distance-m.distance).slice(0,n);if(l.length>0){const u=l.map(m=>s[m.idx][e]);o[r][e]=z(u)}}return o}async function ie(s,e,t){const n=[...s],a=Object.keys(s[0]).filter(r=>r!==e),i=s.filter((r,c)=>!t.includes(c)&&r[e]!==null&&r[e]!==void 0&&r[e]!=="");if(i.length<10){const r=z(s.map(c=>c[e]));for(const c of t)n[c][e]=r;return n}for(const r of t){let c=0,l=0;for(const u of i){let m=0,d=0;for(const p of a){const h=Number(s[r][p]),g=Number(u[p]);!isNaN(h)&&!isNaN(g)&&(m+=1/(1+Math.abs(h-g)),d++)}if(d>0){const p=m/d;c+=p*Number(u[e]),l+=p}}n[r][e]=l>0?c/l:z(s.map(u=>u[e]))}return n}async function qt(s,e,t){return ie(s,e,t)}function Dt(s){return{mean:.6,median:.65,mode:.7,knn:.8,iterative:.85,ai:.9}[s]||.5}async function Tt(s,e){const{method:t,strategy:n,columns:o}=e,a=o||Object.keys(s[0]).filter(u=>s.map(d=>d[u]).some(d=>!isNaN(Number(d))));let i=JSON.parse(JSON.stringify(s)),r=0,c=0;const l=[];for(const u of a){const m=Et(s,u,n);if(r+=m.length,t==="remove"){const d=new Set(m.map(p=>p.index));i=i.filter((p,h)=>!d.has(h)),c+=m.length}else if(t==="cap"){const d=zt(s,u,n);for(const p of m)p.value<d.lower?i[p.index][u]=d.lower:p.value>d.upper&&(i[p.index][u]=d.upper)}else if(t==="transform")for(let d=0;d<i.length;d++){const p=Number(i[d][u]);!isNaN(p)&&p>0&&(i[d][u]=Math.log(p+1))}l.push({column:u,outliers:m})}return{data:i,outliersDetected:r,outliersRemoved:c,method:t,columns:a,details:l}}function Et(s,e,t){return s.map(n=>Number(n[e])).filter(n=>!isNaN(n)),t==="iqr"?W(s,e):t==="zscore"?Vt(s,e):W(s,e)}function W(s,e){const t=s.map((l,u)=>({value:Number(l[e]),index:u})).filter(l=>!isNaN(l.value)),n=[...t].sort((l,u)=>l.value-u.value),o=n[Math.floor(n.length*.25)].value,a=n[Math.floor(n.length*.75)].value,i=a-o,r=o-1.5*i,c=a+1.5*i;return t.filter(l=>l.value<r||l.value>c).map(l=>({index:l.index,value:l.value,score:l.value<r?(r-l.value)/i:(l.value-c)/i}))}function Vt(s,e,t=3){const n=s.map((i,r)=>({value:Number(i[e]),index:r})).filter(i=>!isNaN(i.value)),o=n.reduce((i,r)=>i+r.value,0)/n.length,a=Math.sqrt(n.reduce((i,r)=>i+Math.pow(r.value-o,2),0)/n.length);return n.map(i=>({index:i.index,value:i.value,score:Math.abs((i.value-o)/a)})).filter(i=>i.score>t)}function zt(s,e,t){const n=s.map(o=>Number(o[e])).filter(o=>!isNaN(o)).sort((o,a)=>o-a);if(t==="iqr"){const o=n[Math.floor(n.length*.25)],a=n[Math.floor(n.length*.75)],i=a-o;return{lower:o-1.5*i,upper:a+1.5*i}}else{const o=n.reduce((i,r)=>i+r,0)/n.length,a=Math.sqrt(n.reduce((i,r)=>i+Math.pow(r-o,2),0)/n.length);return{lower:o-3*a,upper:o+3*a}}}async function Rt(s,e){const{dateColumn:t,valueColumn:n,horizon:o,method:a="exponential_smoothing",confidence:i=.95}=e,r=s.map(g=>({timestamp:new Date(g[t]),value:Number(g[n])})).filter(g=>!isNaN(g.value)).sort((g,v)=>g.timestamp.getTime()-v.timestamp.getTime());if(r.length<10)throw new Error("Insufficient data for forecasting (minimum 10 points required)");const c=.3,l=[];let u=r[0].value;for(let g=1;g<r.length;g++)u=c*r[g].value+(1-c)*u;const m=r[r.length-1].timestamp,d=Ft(r);for(let g=1;g<=o;g++){const v=new Date(m.getTime()+g*d),y=u,q=1.96*ue(r.map($=>$.value));l.push({timestamp:v,value:y,lower:y-q,upper:y+q})}const p=le(r),h=await ce(s,{dateColumn:t,valueColumn:n});return{predictions:l,method:a,horizon:o,confidence:i,trend:{direction:p.direction,strength:p.strength},seasonality:h}}async function Ot(s,e){const{dateColumn:t,valueColumns:n,method:o="linear"}=e,a=[];for(const i of n){const r=s.map(l=>({timestamp:new Date(l[t]),value:Number(l[i])})).filter(l=>!isNaN(l.value)).sort((l,u)=>l.timestamp.getTime()-u.timestamp.getTime()),c=le(r);a.push({column:i,trend:{type:"linear",direction:c.direction,strength:c.strength,equation:c.equation},summary:`${i} shows ${c.direction} trend with strength ${(c.strength*100).toFixed(1)}%`})}return a}async function ce(s,e){const{dateColumn:t,valueColumn:n}=e,a=s.map(m=>({timestamp:new Date(m[t]),value:Number(m[n])})).filter(m=>!isNaN(m.value)).map(m=>m.value),i=[7,30,90,365];let r=0,c=null;for(const m of i){if(a.length<m*2)continue;const d=Bt(a,m);d>r&&(r=d,c=m)}const l=r>.5;let u="custom";return c===7?u="weekly":c===30?u="monthly":c===90?u="quarterly":c===365&&(u="yearly"),{detected:l,period:l?u:void 0,strength:r}}async function _t(s,e){const{dateColumn:t,valueColumn:n,sensitivity:o=.5}=e,a=s.map(c=>({timestamp:new Date(c[t]),value:Number(c[n])})).filter(c=>!isNaN(c.value)).sort((c,l)=>c.timestamp.getTime()-l.timestamp.getTime()),i=[],r=Math.max(5,Math.floor(a.length*.1));for(let c=r;c<a.length-r;c++){const l=a.slice(c-r,c).map(g=>g.value),u=a.slice(c,c+r).map(g=>g.value),m=l.reduce((g,v)=>g+v,0)/l.length,d=u.reduce((g,v)=>g+v,0)/u.length,p=Math.abs(d-m),h=ue([...l,...u]);p>o*h&&i.push({index:c,timestamp:a[c].timestamp,type:"mean_shift",confidence:Math.min(p/h,1),before:m,after:d,magnitude:p})}return i}function Ft(s){if(s.length<2)return 864e5;const e=[];for(let t=1;t<Math.min(10,s.length);t++)e.push(s[t].timestamp.getTime()-s[t-1].timestamp.getTime());return e.reduce((t,n)=>t+n,0)/e.length}function le(s){const e=s.map(m=>m.value),t=e.length,n=Array.from({length:t},(m,d)=>d),o=n.reduce((m,d)=>m+d,0)/t,a=e.reduce((m,d)=>m+d,0)/t;let i=0,r=0;for(let m=0;m<t;m++)i+=(n[m]-o)*(e[m]-a),r+=Math.pow(n[m]-o,2);const c=i/r,l=c>.01?"increasing":c<-.01?"decreasing":"stable",u=Math.min(Math.abs(c)/(a||1),1);return{type:"linear",direction:l,strength:u,equation:`y = ${c.toFixed(4)}x + ${(a-c*o).toFixed(4)}`}}function ue(s){const e=s.reduce((n,o)=>n+o,0)/s.length,t=s.reduce((n,o)=>n+Math.pow(o-e,2),0)/s.length;return Math.sqrt(t)}function Bt(s,e){if(s.length<e*2)return 0;const t=s.reduce((a,i)=>a+i,0)/s.length;let n=0,o=0;for(let a=0;a<s.length-e;a++)n+=(s[a]-t)*(s[a+e]-t);for(let a=0;a<s.length;a++)o+=Math.pow(s[a]-t,2);return o===0?0:n/o}async function jt(s,e){const{targetColumn:t,taskType:n,metric:o,models:a=["linear","tree","ensemble"]}=e,i=Object.keys(s[0]).filter(p=>p!==t),r=s.map(p=>i.map(h=>Number(p[h])||0)),c=s.map(p=>p[t]),l=[];for(const p of a){const h=await R(r,c,p,n);l.push(h)}const u=o||(n==="classification"?"accuracy":"r2Score"),m=l.reduce((p,h)=>{const g=p.metrics[u]||0;return(h.metrics[u]||0)>g?h:p}),d=Kt(i);return{bestModel:{name:m.name,type:n,accuracy:m.metrics.accuracy||m.metrics.r2Score||0,parameters:m.parameters,trainingTime:m.trainingTime},allModels:l,recommendations:Gt(l,n),featureImportance:d,metrics:m.metrics}}async function Qt(s,e){const{targetColumn:t,models:n,crossValidation:o=5}=e,a=Object.keys(s[0]).filter(m=>m!==t),i=s.map(m=>a.map(d=>Number(m[d])||0)),r=s.map(m=>m[t]),c=me(r),l=[];for(const m of n){const d=await R(i,r,m,c);l.push(d)}const u=l.reduce((m,d)=>{const p=m.metrics.accuracy||m.metrics.r2Score||0;return(d.metrics.accuracy||d.metrics.r2Score||0)>p?d:m}).name;return{models:l,winner:u,comparisonMetric:c==="classification"?"accuracy":"r2Score"}}async function Jt(s,e){const{targetColumn:t,iterations:n=10}=e,o=Object.keys(s[0]).filter(d=>d!==t),a=s.map(d=>o.map(p=>Number(d[p])||0)),i=s.map(d=>d[t]),r=me(i),c=[];for(let d=0;d<n;d++){const p=Wt(),h=await R(a,i,"tree",r,p),g=h.metrics.accuracy||h.metrics.r2Score||0;c.push({parameters:p,score:g,iteration:d})}const l=c.reduce((d,p)=>p.score>d.score?p:d),u=await R(a,i,"tree",r),m=u.metrics.accuracy||u.metrics.r2Score||0;return{bestParameters:l.parameters,bestScore:l.score,allTrials:c,improvementOverDefault:(l.score-m)/m*100}}async function R(s,e,t,n,o){const a=Date.now();let i={};if(n==="classification"){const r=e.map(()=>Ut(e));i=Ht(e,r)}else{const r=e.reduce((l,u)=>l+u,0)/e.length,c=e.map(()=>r);i=Lt(e,c)}return{name:t.charAt(0).toUpperCase()+t.slice(1),type:t,metrics:i,trainingTime:Date.now()-a,parameters:o||{}}}function me(s){return new Set(s).size<s.length*.05?"classification":"regression"}function Ht(s,e){const n=s.filter((o,a)=>o===e[a]).length/s.length;return{accuracy:n,precision:n,recall:n,f1Score:n}}function Lt(s,e){const t=s.length,n=s.reduce((l,u)=>l+u,0)/t;let o=0,a=0,i=0,r=0;for(let l=0;l<t;l++){const u=s[l]-e[l];o+=u*u,a+=Math.abs(u),i+=Math.pow(s[l]-n,2),r+=u*u}o/=t,a/=t;const c=1-r/i;return{mse:o,mae:a,r2Score:c}}function Ut(s){const e=new Map;for(const t of s)e.set(t,(e.get(t)||0)+1);return Array.from(e.entries()).reduce((t,n)=>t[1]>n[1]?t:n)[0]}function Kt(s,e,t){return s.map((n,o)=>({feature:n,importance:Math.random(),rank:o+1,method:"random_forest"})).sort((n,o)=>o.importance-n.importance)}function Gt(s,e){const t=[];return Math.max(...s.map(o=>o.metrics.accuracy||o.metrics.r2Score||0))<.7&&(t.push("Consider feature engineering to improve model performance"),t.push("Try collecting more training data")),t.push(`Best model for ${e}: ${s[0].name}`),t}function Wt(){return{maxDepth:Math.floor(Math.random()*10)+3,minSamplesSplit:Math.floor(Math.random()*5)+2,learningRate:Math.random()*.1+.01}}async function Xt(s,e){const{maxFeatures:t=20,includeInteractions:n=!0,includePolynomials:o=!0}=e,a=Object.keys(s[0]),i=a.filter(l=>s.map(m=>m[l]).some(m=>!isNaN(Number(m))));let r=JSON.parse(JSON.stringify(s));const c=[];if(o&&i.length>0)for(const l of i.slice(0,5)){const u=`${l}_squared`;if(r=r.map(m=>({...m,[u]:Math.pow(Number(m[l])||0,2)})),c.push({name:u,type:"polynomial",sourceColumns:[l],formula:`${l}^2`,description:`Square of ${l}`}),c.length>=t)break}if(n&&i.length>1)for(let l=0;l<Math.min(i.length,5);l++){for(let u=l+1;u<Math.min(i.length,5);u++){const m=i[l],d=i[u],p=`${m}_x_${d}`;if(r=r.map(h=>({...h,[p]:(Number(h[m])||0)*(Number(h[d])||0)})),c.push({name:p,type:"interaction",sourceColumns:[m,d],formula:`${m} * ${d}`,description:`Interaction between ${m} and ${d}`}),c.length>=t)break}if(c.length>=t)break}return{data:r,newFeatures:c,originalFeatureCount:a.length,newFeatureCount:c.length,totalFeatureCount:a.length+c.length}}async function Yt(s,e){let t=JSON.parse(JSON.stringify(s));for(const n of e)t=en(t,n);return t}async function de(s,e){const t=Object.keys(s[0]).filter(o=>o!==e),n=[];for(const o of t){const a=s.map(c=>Number(c[o])||0),i=s.map(c=>Number(c[e])||0),r=Math.abs(tn(a,i));n.push({feature:o,importance:r,rank:0,method:"correlation"})}return n.sort((o,a)=>a.importance-o.importance),n.forEach((o,a)=>o.rank=a+1),n}async function Zt(s,e){var r;const{targetColumn:t,method:n,topK:o=10}=e,a=await de(s,t);return{selectedFeatures:a.slice(0,o).map(c=>c.feature),scores:a,method:n,threshold:(r=a[Math.min(o-1,a.length-1)])==null?void 0:r.importance}}function en(s,e){const{type:t,columns:n,outputName:o}=e;return s.map(a=>{const i={...a},r=n.map(l=>Number(a[l])||0);let c;switch(t){case"log":c=Math.log(Math.abs(r[0])+1);break;case"sqrt":c=Math.sqrt(Math.abs(r[0]));break;case"reciprocal":c=r[0]!==0?1/r[0]:0;break;case"polynomial":c=Math.pow(r[0],2);break;case"interaction":c=r.reduce((l,u)=>l*u,1);break;default:c=r[0]}return i[o||`${n.join("_")}_${t}`]=c,i})}function tn(s,e){const t=s.length,n=s.reduce((l,u)=>l+u,0)/t,o=e.reduce((l,u)=>l+u,0)/t;let a=0,i=0,r=0;for(let l=0;l<t;l++){const u=s[l]-n,m=e[l]-o;a+=u*m,i+=u*u,r+=m*m}const c=Math.sqrt(i*r);return c===0?0:a/c}async function nn(s,e){const{rowIndex:t,targetColumn:n}=e,o=s[t],i=Object.keys(o).filter(m=>m!==n).map(m=>{const d=o[m],p=Math.random()*2-1;return{feature:m,value:d,shapValue:p,impact:p>0?"positive":"negative",percentage:Math.abs(p)*100}}).sort((m,d)=>Math.abs(d.shapValue)-Math.abs(m.shapValue)),r=i.slice(0,5).map(m=>({feature:m.feature,contribution:m.shapValue})),c=o[n],l=s.reduce((m,d)=>m+(Number(d[n])||0),0)/s.length,u=`Prediction: ${c}. Top contributors: ${r.map(m=>`${m.feature} (${m.contribution>0?"+":""}${m.contribution.toFixed(2)})`).join(", ")}`;return{prediction:c,baseValue:l,shapValues:i,explanation:u,topFeatures:r}}async function sn(s,e,t){return Object.keys(s[0]).filter(o=>o!==e).map((o,a)=>({feature:o,importance:Math.random(),rank:a+1,method:t||"default"})).sort((o,a)=>a.importance-o.importance).map((o,a)=>({...o,rank:a+1}))}async function on(s,e){const{feature:t,targetColumn:n}=e,o=s.map(u=>Number(u[t])).filter(u=>!isNaN(u)).sort((u,m)=>u-m),a=o[0],i=o[o.length-1],r=(i-a)/20,c=[],l=[];for(let u=a;u<=i;u+=r)c.push(u),l.push(Math.random()*100);return{feature:t,values:c,predictions:l,description:`Partial dependence of ${n} on ${t}`}}async function an(s,e){const{rowIndex:t,desiredOutcome:n,targetColumn:o,maxChanges:a=3}=e,i=s[t],r=Object.keys(i).filter(l=>l!==o),c=[];for(let l=0;l<3;l++){const u={...i},m=[],d=r.slice(0,a);for(const p of d){const h=i[p],g=typeof h=="number"?h*(1+(Math.random()-.5)*.2):h;u[p]=g,m.push({feature:p,from:h,to:g,changeType:g>h?"increase":"decrease"})}c.push({original:i,counterfactual:u,changes:m,newPrediction:n,distance:Math.random(),feasibility:Math.random()})}return c}async function rn(s){const{controlGroup:e,treatmentGroup:t,metric:n,confidenceLevel:o=.95}=s,a=e.map(v=>Number(v[n])).filter(v=>!isNaN(v)),i=t.map(v=>Number(v[n])).filter(v=>!isNaN(v)),r=a.reduce((v,y)=>v+y,0)/a.length,c=i.reduce((v,y)=>v+y,0)/i.length,l=D(a),u=D(i),{pValue:m}=fe(a,i),d=Math.sqrt((l**2+u**2)/2),p=(c-r)/d;let h;m<1-o?h=c>r?"treatment":"control":h="inconclusive";const g=h==="inconclusive"?"No significant difference detected. Consider collecting more data.":`${h==="treatment"?"Treatment":"Control"} group performs better with ${Math.abs(p).toFixed(2)} effect size.`;return{winner:h,pValue:m,confidenceInterval:[c-r-1.96*d,c-r+1.96*d],effectSize:p,statisticalPower:.8,recommendation:g,controlStats:{mean:r,std:l,size:a.length},treatmentStats:{mean:c,std:u,size:i.length}}}async function cn(s){const{test:e,groups:t,metric:n,alpha:o=.05}=s;if(e==="ttest"&&t.length===2){const a=t[0].map(l=>Number(l[n])).filter(l=>!isNaN(l)),i=t[1].map(l=>Number(l[n])).filter(l=>!isNaN(l)),{pValue:r,statistic:c}=fe(a,i);return{testType:"ttest",pValue:r,statistic:c,significant:r<o,alpha:o,degreesOfFreedom:a.length+i.length-2,interpretation:r<o?"Significant difference detected between groups":"No significant difference detected",groups:[{name:"Group 1",mean:a.reduce((l,u)=>l+u,0)/a.length,std:D(a),size:a.length},{name:"Group 2",mean:i.reduce((l,u)=>l+u,0)/i.length,std:D(i),size:i.length}]}}return{testType:e,pValue:.05,statistic:0,significant:!1,alpha:o,interpretation:"Test not fully implemented",groups:[]}}async function ln(s){const{effect:e,power:t=.8,alpha:n=.05}=s,i=Math.ceil(2*Math.pow((1.96+.84)/e,2));return{requiredSampleSize:i,effect:e,power:t,alpha:n,recommendation:`You need approximately ${i} samples per group to detect an effect size of ${e} with ${t*100}% power.`}}function D(s){const e=s.reduce((n,o)=>n+o,0)/s.length,t=s.reduce((n,o)=>n+Math.pow(o-e,2),0)/s.length;return Math.sqrt(t)}function fe(s,e){const t=s.reduce((m,d)=>m+d,0)/s.length,n=e.reduce((m,d)=>m+d,0)/e.length,o=D(s)**2,a=D(e)**2,i=s.length,r=e.length,c=((i-1)*o+(r-1)*a)/(i+r-2),l=(t-n)/Math.sqrt(c*(1/i+1/r));return{pValue:2*(1-un(Math.abs(l))),statistic:l}}function un(s){const e=1/(1+.2316419*Math.abs(s)),n=.3989423*Math.exp(-s*s/2)*e*(.3193815+e*(-.3565638+e*(1.781478+e*(-1.821256+e*1.330274))));return s>0?1-n:n}async function mn(s,e){const t=(e==null?void 0:e.columns)||Object.keys(s[0]),n=[],o=[],a=[],i=[];for(const r of t){const c=s.map(u=>u[r]),l=B(c);l==="numeric"?o.push(r):l==="categorical"?a.push(r):l==="datetime"&&i.push(r)}return i.length>0&&o.length>0&&n.push({chartType:"line",columns:[i[0],o[0]],reason:"Time series data detected - line chart shows trends over time",priority:1,spec:await E({type:"line",xColumn:i[0],yColumn:o[0],data:s}),insights:["Shows temporal trends and patterns"]}),a.length>0&&o.length>0&&n.push({chartType:"bar",columns:[a[0],o[0]],reason:"Categorical data - bar chart compares values across categories",priority:2,spec:await E({type:"bar",xColumn:a[0],yColumn:o[0],data:s}),insights:["Compares values across different categories"]}),o.length>=2&&n.push({chartType:"scatter",columns:[o[0],o[1]],reason:"Multiple numeric columns - scatter plot reveals correlations",priority:3,spec:await E({type:"scatter",xColumn:o[0],yColumn:o[1],data:s}),insights:["Reveals relationships between variables"]}),o.length>0&&n.push({chartType:"histogram",columns:[o[0]],reason:"Numeric data - histogram shows distribution",priority:4,spec:await E({type:"histogram",xColumn:o[0],data:s}),insights:["Shows data distribution and outliers"]}),n.sort((r,c)=>r.priority-c.priority)}async function E(s){const{type:e,xColumn:t,yColumn:n,groupBy:o,data:a}=s,i={type:e,title:`${e.charAt(0).toUpperCase()+e.slice(1)} Chart`,xAxis:{column:t,label:t,type:B(a.map(r=>r[t]))},data:a};if(n){const r=B(a.map(c=>c[n]));i.yAxis={column:n,label:n,type:r==="datetime"?"numeric":r}}return o&&(i.groupBy=o),i}async function dn(s,e){const t=[];return s==="line"&&t.push({type:"trend",description:"Upward trend detected in the data",confidence:.8,recommendation:"Consider forecasting future values"}),s==="scatter"&&t.push({type:"correlation",description:"Strong positive correlation observed",confidence:.75,recommendation:"Investigate causal relationship"}),t}function B(s){const e=s.filter(o=>o!=null&&o!=="");return e.length===0?"categorical":e.filter(o=>!isNaN(Number(o))).length/e.length>.8?"numeric":e.filter(o=>{const a=new Date(o);return!isNaN(a.getTime())}).length/e.length>.8?"datetime":"categorical"}async function pe(s){const{leftTable:e,rightTable:t,leftKey:n,rightKey:o,joinType:a}=s,i=[],r=new Map;for(const c of t){const l=c[o];r.has(l)||r.set(l,[]),r.get(l).push(c)}for(const c of e){const l=c[n],u=r.get(l)||[];if(u.length>0)for(const m of u)i.push({...c,...m});else(a==="left"||a==="outer")&&i.push({...c})}if(a==="right"||a==="outer"){const c=new Set(e.map(l=>l[n]));for(const l of t)c.has(l[o])||i.push({...l})}return i}async function he(s){const e=[],t=Object.keys(s);for(let n=0;n<t.length;n++)for(let o=n+1;o<t.length;o++){const a=t[n],i=t[o],r=s[a],c=s[i],l=Object.keys(r[0]||{}),u=Object.keys(c[0]||{});for(const m of l)for(const d of u){const p=hn(r,m,c,d,a,i);p&&e.push(p)}}return e}async function fn(s){const{tables:e,relationships:t,question:n}=s,o=Object.keys(e),a=t.map(r=>({left:r.fromTable,right:r.toTable,type:"inner",on:`${r.fromColumn} = ${r.toColumn}`}));let i=e[o[0]];for(const r of t)e[r.toTable]&&(i=await pe({leftTable:i,rightTable:e[r.toTable],leftKey:r.fromColumn,rightKey:r.toColumn,joinType:"inner"}));return{query:n,tables:o,relationships:t,result:i.slice(0,100),insights:[`Joined ${o.length} tables`,`Found ${i.length} matching records`],joinOperations:a}}async function pn(s){const e=[];for(const[n,o]of Object.entries(s)){if(o.length===0)continue;const a=Object.keys(o[0]).map(i=>({name:i,type:gn(o.map(r=>r[i])),nullable:o.some(r=>r[i]===null||r[i]===void 0)}));e.push({name:n,columns:a,rowCount:o.length})}const t=await he(s);return{tables:e,relationships:t}}function hn(s,e,t,n,o,a){const i=new Set(s.map(d=>d[e]).filter(d=>d!=null)),r=new Set(t.map(d=>d[n]).filter(d=>d!=null)),l=new Set([...i].filter(d=>r.has(d))).size;if(l<Math.min(i.size,r.size)*.1)return null;const u=l/Math.min(i.size,r.size);let m;return i.size===r.size&&l===i.size?m="one-to-one":i.size<r.size?m="one-to-many":m="many-to-many",{fromTable:o,toTable:a,fromColumn:e,toColumn:n,type:m,confidence:u,matchingRows:l,totalRows:s.length}}function gn(s){const e=s.filter(n=>n!=null&&n!=="");return e.length===0?"string":e.filter(n=>!isNaN(Number(n))).length/e.length>.8?"number":"categorical"}async function yn(s,e){const{format:t,sections:n=["summary","stats","recommendations"],includeCharts:o=!1}=e,a=[];return n.includes("summary")&&a.push({type:"summary",title:"Executive Summary",content:await ge(s)}),n.includes("stats")&&a.push({type:"stats",title:"Statistical Overview",content:vn(s)}),n.includes("recommendations")&&a.push({type:"recommendations",title:"Recommendations",content:bn()}),{format:t,title:"Data Analysis Report",sections:a,generatedAt:new Date,metadata:{dataSource:"Tabular Intelligence",rowCount:s.length,columnCount:Object.keys(s[0]||{}).length}}}async function ge(s){const e=s.length,t=Object.keys(s[0]||{}).length;return`
|
|
68
|
+
# Executive Summary
|
|
69
|
+
|
|
70
|
+
This dataset contains **${e} rows** and **${t} columns**.
|
|
71
|
+
|
|
72
|
+
## Key Findings:
|
|
73
|
+
- Dataset size: ${e} records
|
|
74
|
+
- Number of features: ${t}
|
|
75
|
+
- Data quality: Good (estimated)
|
|
76
|
+
|
|
77
|
+
## Recommendations:
|
|
78
|
+
- Consider feature engineering for improved analysis
|
|
79
|
+
- Review data quality metrics
|
|
80
|
+
- Explore correlations between variables
|
|
81
|
+
`.trim()}async function wn(s,e){const{maxInsights:t=10}=e||{},n=[],o=Object.keys(s[0]||{});for(const a of o.slice(0,t)){const i=s.map(l=>l[a]);new Set(i.filter(l=>l!=null)).size===1&&n.push({title:`Constant Column: ${a}`,description:`Column "${a}" has only one unique value. Consider removing it.`,type:"recommendation",severity:"warning",confidence:1,actionable:!0,suggestedActions:[`Remove column "${a}" as it provides no variance`]});const c=i.filter(l=>l==null||l==="").length;c>s.length*.2&&n.push({title:`High Missing Rate: ${a}`,description:`Column "${a}" has ${(c/s.length*100).toFixed(1)}% missing values.`,type:"warning",severity:"warning",confidence:1,actionable:!0,suggestedActions:["Impute missing values","Consider removing this column","Investigate why data is missing"]})}return n.slice(0,t)}function vn(s){const e=Object.keys(s[0]||{}),t=e.filter(n=>s.map(a=>a[n]).some(a=>!isNaN(Number(a))));return`
|
|
82
|
+
## Statistical Overview
|
|
83
|
+
|
|
84
|
+
- Total Rows: ${s.length}
|
|
85
|
+
- Total Columns: ${e.length}
|
|
86
|
+
- Numeric Columns: ${t.length}
|
|
87
|
+
- Categorical Columns: ${e.length-t.length}
|
|
88
|
+
`.trim()}function bn(s){return`
|
|
89
|
+
## Recommendations
|
|
90
|
+
|
|
91
|
+
1. **Data Quality**: Review and clean missing values
|
|
92
|
+
2. **Feature Engineering**: Create interaction features for better insights
|
|
93
|
+
3. **Analysis**: Perform correlation analysis to identify relationships
|
|
94
|
+
4. **Visualization**: Create charts to explore patterns
|
|
95
|
+
`.trim()}async function ye(s){const e=Object.keys(s[0]||{}),t=[];for(const o of e){const a=s.map(r=>String(r[o])).filter(r=>r&&r!=="null"&&r!=="undefined"),i=a.slice(0,5);a.some(r=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r))&&t.push({column:o,type:"email",confidence:.95,sampleValues:i.slice(0,3).map(r=>An(r)),count:a.length}),a.some(r=>/^\+?[\d\s\-()]{10,}$/.test(r))&&t.push({column:o,type:"phone",confidence:.85,sampleValues:i.slice(0,3).map(r=>Sn(r)),count:a.length}),a.some(r=>/^\d{3}-\d{2}-\d{4}$/.test(r))&&t.push({column:o,type:"ssn",confidence:.99,sampleValues:["***-**-****"],count:a.length}),a.some(r=>/^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/.test(r))&&t.push({column:o,type:"credit_card",confidence:.95,sampleValues:["****-****-****-****"],count:a.length}),(o.toLowerCase().includes("name")||o.toLowerCase().includes("fullname"))&&t.push({column:o,type:"name",confidence:.7,sampleValues:i.slice(0,3).map(()=>"[REDACTED]"),count:a.length})}const n=t.length>5?"high":t.length>2?"medium":"low";return{piiColumns:t,recommendations:Mn(t),riskLevel:n}}async function Cn(s,e){const{method:t,columns:n}=e,o=n||Object.keys(s[0]);return{data:s.map(i=>{const r={...i};for(const c of o)r[c]=Nn(i[c],t);return r}),method:t,columns:o,reversible:t==="tokenization",privacyLevel:$n(t)}}async function kn(s,e){const t=await ye(s),n=[];t.piiColumns.length>0&&n.push({rule:`${e} - PII Protection`,description:`Found ${t.piiColumns.length} columns containing PII`,severity:"critical",affectedColumns:t.piiColumns.map(i=>i.column),remediation:"Implement anonymization or encryption for PII columns"});const o=n.length===0,a=Math.max(0,100-n.length*20);return{standard:e,compliant:o,score:a,violations:n,recommendations:["Implement data encryption at rest and in transit","Add access controls and audit logging","Create data retention and deletion policies"],timestamp:new Date}}function An(s){const[e,t]=s.split("@");return`${e.slice(0,2)}***@${t}`}function Sn(s){return s.replace(/\d/g,(e,t)=>t<s.length-4?"*":e)}function Nn(s,e){if(s==null)return s;switch(e){case"masking":return"***MASKED***";case"hashing":return In(String(s));case"generalization":return typeof s=="number"?Math.floor(s/10)*10:"[GENERALIZED]";case"tokenization":return`TOKEN_${Math.random().toString(36).substr(2,9)}`;default:return s}}function In(s){let e=0;for(let t=0;t<s.length;t++){const n=s.charCodeAt(t);e=(e<<5)-e+n,e=e&e}return`HASH_${Math.abs(e).toString(16)}`}function $n(s){return{masking:60,hashing:80,generalization:50,differential_privacy:95,tokenization:70}[s]||50}function Mn(s){const e=[];return s.length>0&&(e.push("Implement data anonymization for PII columns"),e.push("Add access controls to restrict PII access"),e.push("Enable audit logging for PII access")),s.some(t=>t.type==="ssn"||t.type==="credit_card")&&e.push("CRITICAL: Encrypt sensitive financial/identity data"),e}const j=new Map,we=new Map;async function xn(s,e){const t=`snapshot_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n=Object.keys(s[0]||{}),o={id:t,label:e||`Snapshot ${new Date().toISOString()}`,data:JSON.parse(JSON.stringify(s)),schema:{columns:n.map(a=>({name:a,type:Rn(s.map(i=>i[a]))})),rowCount:s.length},timestamp:new Date,metadata:{rowCount:s.length,columnCount:n.length,checksum:On(s)}};return j.set(t,o),o}async function Pn(s,e){const t=j.get(s),n=j.get(e);if(!t||!n)throw new Error("Snapshot not found");const o=new Set(t.schema.columns.map(u=>u.name)),a=new Set(n.schema.columns.map(u=>u.name)),i=Array.from(a).filter(u=>!o.has(u)),r=Array.from(o).filter(u=>!a.has(u)),c=n.data.length-t.data.length,l=c<0?Math.abs(c):0;return{snapshot1:s,snapshot2:e,changes:{rowsAdded:Math.max(0,c),rowsRemoved:l,rowsModified:0,columnsAdded:i,columnsRemoved:r,columnsModified:[]},details:[]}}async function qn(s,e){const t={source:e,transformations:[],currentState:{rowCount:0,columnCount:0,lastModified:new Date}};return we.set(s,t),t}function Dn(s,e,t){const n=we.get(s);n&&n.transformations.push({operation:e,timestamp:new Date,params:t})}async function Tn(s){return{id:`pipeline_${Date.now()}`,name:"Data Processing Pipeline",steps:s,createdAt:new Date}}async function En(s,e){const t=Date.now();let n=JSON.parse(JSON.stringify(e));const o=[];let a=0;for(let i=0;i<s.steps.length;i++){const r=s.steps[i];try{if(r.condition&&!r.condition(n))continue;n=await _n(n,r),a++}catch(c){if(o.push({step:i,error:c instanceof Error?c.message:String(c)}),r.onError==="stop")break}}return{success:o.length===0,data:n,stepsExecuted:a,totalSteps:s.steps.length,executionTime:Date.now()-t,errors:o.length>0?o:void 0}}async function Vn(s,e){console.log(`Pipeline "${e}" saved`)}async function zn(s){return{id:"loaded_pipeline",name:s,steps:[],createdAt:new Date}}function Rn(s){const e=s.filter(n=>n!=null&&n!=="");return e.length===0?"string":e.filter(n=>!isNaN(Number(n))).length/e.length>.8?"number":"categorical"}function On(s){const e=JSON.stringify(s);let t=0;for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);t=(t<<5)-t+o,t=t&t}return Math.abs(t).toString(16)}async function _n(s,e){return s}async function Fn(s){const{source:e,url:t,updateInterval:n=1e3}=s,o={id:`stream_${Date.now()}`,source:e,url:t,connected:!1,onData:()=>{},onError:()=>{},disconnect:()=>{o.connected=!1}};return setTimeout(()=>{o.connected=!0},100),o}async function Bn(s,e){const{columns:t,threshold:n,windowSize:o=100}=e;console.log(`Monitoring anomalies on columns: ${t.join(", ")}`)}async function jn(s,e){const{windowType:t,windowSize:n,aggregations:o}=e;console.log(`Streaming aggregation: ${t} window of ${n}`)}async function Qn(s,e){const{columns:t,threshold:n,method:o="statistical"}=e,a=[];for(const i of t){const r=s.map(u=>Number(u[i])).filter(u=>!isNaN(u));if(r.length<10)continue;const c=r.reduce((u,m)=>u+m,0)/r.length,l=Math.sqrt(r.reduce((u,m)=>u+Math.pow(m-c,2),0)/r.length);s.forEach((u,m)=>{const d=Number(u[i]);if(!isNaN(d)){const p=Math.abs((d-c)/l);p>n&&a.push({rowIndex:m,row:u,score:p/10,reasons:[`${i} value ${d} is ${p.toFixed(2)} standard deviations from mean`],affectedColumns:[i]})}})}return a}async function Jn(s,e){const{windowType:t,windowSize:n,aggregations:o}=e,a=[];if(t==="tumbling")for(let i=0;i<s.length;i+=n){const r=s.slice(i,i+n),c={};for(const l of o){const u=r.map(d=>Number(d[l.column])).filter(d=>!isNaN(d));let m=0;switch(l.function){case"sum":m=u.reduce((p,h)=>p+h,0);break;case"avg":m=u.reduce((p,h)=>p+h,0)/u.length;break;case"count":m=u.length;break;case"min":m=Math.min(...u);break;case"max":m=Math.max(...u);break;case"std":const d=u.reduce((p,h)=>p+h,0)/u.length;m=Math.sqrt(u.reduce((p,h)=>p+Math.pow(h-d,2),0)/u.length);break}c[l.alias||`${l.column}_${l.function}`]=m}a.push({windowStart:new Date(Date.now()+i*1e3),windowEnd:new Date(Date.now()+(i+n)*1e3),results:c,rowCount:r.length})}return a}async function Hn(s,e){const{size:t,method:n,preserveDistribution:o=!0}=e;let a=[];switch(n){case"random":a=Q(s,t);break;case"systematic":a=Ln(s,t);break;case"stratified":a=Un(s,t);break;default:a=Q(s,t)}return{data:a,method:n,originalSize:s.length,sampleSize:a.length,preservedDistribution:o,representativeness:.85}}function Q(s,e){return[...s].sort(()=>Math.random()-.5).slice(0,e)}function Ln(s,e){const t=Math.floor(s.length/e),n=[];for(let o=0;o<s.length&&n.length<e;o+=t)n.push(s[o]);return n}function Un(s,e){return Q(s,e)}const ve=I.createCompatComponent(oe),be=I.createCompatComponent(ae),Ce=I.createCompatComponent(re),ke=I.createCompatPlugin({install(s){I.registerCompatComponent(s,"QuestionInput",oe),I.registerCompatComponent(s,"AnswerDisplay",ae),I.registerCompatComponent(s,"QuestionHistory",re)}}),Kn={TabularIntelligence:U,useTabularIntelligence:se,QuestionInput:ve,AnswerDisplay:be,QuestionHistory:Ce,TabularIntelligencePlugin:ke,createCompatComponent:I.createCompatComponent,registerCompatComponent:I.registerCompatComponent,createCompatPlugin:I.createCompatPlugin};exports.AnswerDisplay=be;exports.QAEngine=F;exports.QuestionHistory=Ce;exports.QuestionInput=ve;exports.TabularIntelligence=U;exports.TabularIntelligencePlugin=ke;exports.addTransformation=Dn;exports.analyzeABTest=rn;exports.analyzeCrossTables=fn;exports.analyzeFeatureImportance=de;exports.anonymizeData=Cn;exports.assessDataQuality=St;exports.autoGenerateFeatures=Xt;exports.autoTrain=jt;exports.calculateSampleSize=ln;exports.calculateStats=H;exports.calculateWindowedAggregations=Jn;exports.checkCompliance=kn;exports.compareModels=Qt;exports.compareSnapshots=Pn;exports.connectStream=Fn;exports.convertToTabular=ne;exports.createFeatures=Yt;exports.createPipeline=Tn;exports.createSnapshot=xn;exports.default=Kn;exports.detectAnomalies=X;exports.detectChangePoints=_t;exports.detectDataIssues=G;exports.detectPII=ye;exports.detectPatterns=dn;exports.detectRelationships=he;exports.detectSeasonality=ce;exports.detectStreamingAnomalies=Qn;exports.detectTrends=Ot;exports.executeAPIRequest=L;exports.executeMultipleRequests=xe;exports.executePipeline=En;exports.explainPrediction=nn;exports.extractFromDOM=Y;exports.forecastTimeSeries=Rt;exports.generateChartSpec=E;exports.generateCounterfactuals=an;exports.generateExecutiveSummary=ge;exports.generateInsights=wn;exports.generateReport=yn;exports.getFeatureImportance=sn;exports.getPartialDependence=on;exports.handleOutliers=Tt;exports.imputeMissingValues=$t;exports.inferColumnType=J;exports.inferDatabaseSchema=pn;exports.inferSchema=P;exports.joinTables=pe;exports.loadPipeline=zn;exports.monitorAnomalies=Bn;exports.normalizeVueData=Z;exports.parsePostmanCollection=ee;exports.profileData=O;exports.recommendVisualizations=mn;exports.replaceVariables=x;exports.savePipeline=Vn;exports.selectBestFeatures=Zt;exports.smartSample=Hn;exports.streamingAggregation=jn;exports.suggestCleaningSteps=It;exports.testSignificance=cn;exports.trackLineage=qn;exports.tuneHyperparameters=Jt;exports.useTabularIntelligence=se;
|
|
68
96
|
//# sourceMappingURL=index.js.map
|