@aivue/tabular-intelligence 2.0.0 → 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 CHANGED
@@ -72,9 +72,23 @@ See [POSTMAN-INTEGRATION.md](./POSTMAN-INTEGRATION.md) for detailed documentatio
72
72
  ## 📦 Installation
73
73
 
74
74
  ```bash
75
- npm install @aivue/tabular-intelligence
75
+ # npm
76
+ npm install @aivue/tabular-intelligence @aivue/core
77
+
78
+ # yarn
79
+ yarn add @aivue/tabular-intelligence @aivue/core
80
+
81
+ # pnpm
82
+ pnpm add @aivue/tabular-intelligence @aivue/core
76
83
  ```
77
84
 
85
+ ### 🔄 Vue Compatibility
86
+
87
+ - **✅ Vue 2**: Compatible with Vue 2.6.0 and higher
88
+ - **✅ Vue 3**: Compatible with all Vue 3.x versions
89
+
90
+ > The package automatically detects which version of Vue you're using and provides the appropriate compatibility layer. This means you can use the same package regardless of whether your project is using Vue 2 or Vue 3.
91
+
78
92
  ## 🚀 Quick Start
79
93
 
80
94
  ### Basic Usage (Local Mode)
@@ -1,4 +1,4 @@
1
- import { Ref } from 'vue';
1
+ import { Ref } from 'vue-demi';
2
2
  import { TabularIntelligence } from '../core/TabularIntelligence';
3
3
  import { TFMConfig, AnalysisResult, AnalysisType, TableSchema, DescriptiveStats, Anomaly, Question, Answer, QARequest, AISummary, TableExtractionOptions, ExtractedTable } from '../types';
4
4
  import { QAEngineConfig } from '../utils/qaEngine';
@@ -1 +1 @@
1
- {"version":3,"file":"useTabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/composables/useTabularIntelligence.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAiB,GAAG,EAAE,MAAM,KAAK,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,KAAK,EACV,SAAS,EAET,cAAc,EACd,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,OAAO,EACP,QAAQ,EACR,MAAM,EACN,SAAS,EAET,SAAS,EACT,sBAAsB,EACtB,cAAc,EACf,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,WAAW,6BAA6B;IAC5C,MAAM,EAAE,SAAS,CAAC;IAClB,IAAI,CAAC,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IAClB,MAAM,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;IAC1B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,4BAA4B;IAE3C,MAAM,EAAE,mBAAmB,CAAC;IAG5B,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACtB,KAAK,EAAE,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;IACzB,UAAU,EAAE,GAAG,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAGvC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAGhC,eAAe,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjC,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;IAC7B,UAAU,EAAE,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAG/B,OAAO,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACxE,mBAAmB,EAAE,MAAM,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IACvD,eAAe,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAClF,iBAAiB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACzF,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IAG1E,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACjF,eAAe,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1C,YAAY,EAAE,MAAM,IAAI,CAAC;IAGzB,cAAc,EAAE,CAAC,OAAO,CAAC,EAAE,sBAAsB,KAAK,cAAc,GAAG,IAAI,CAAC;IAC5E,eAAe,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,sBAAsB,KAAK,IAAI,CAAC;IAG9F,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;IACnD,YAAY,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,CAAC;IACjD,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE,eAAe,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IAC7D,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,6BAA6B,GACrC,4BAA4B,CA+W9B"}
1
+ {"version":3,"file":"useTabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/composables/useTabularIntelligence.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAiB,GAAG,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,KAAK,EACV,SAAS,EAET,cAAc,EACd,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,OAAO,EACP,QAAQ,EACR,MAAM,EACN,SAAS,EAET,SAAS,EACT,sBAAsB,EACtB,cAAc,EACf,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,WAAW,6BAA6B;IAC5C,MAAM,EAAE,SAAS,CAAC;IAClB,IAAI,CAAC,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IAClB,MAAM,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;IAC1B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,4BAA4B;IAE3C,MAAM,EAAE,mBAAmB,CAAC;IAG5B,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACtB,KAAK,EAAE,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;IACzB,UAAU,EAAE,GAAG,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAGvC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAGhC,eAAe,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjC,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;IAC7B,UAAU,EAAE,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAG/B,OAAO,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACxE,mBAAmB,EAAE,MAAM,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IACvD,eAAe,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAClF,iBAAiB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACzF,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IAG1E,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACjF,eAAe,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1C,YAAY,EAAE,MAAM,IAAI,CAAC;IAGzB,cAAc,EAAE,CAAC,OAAO,CAAC,EAAE,sBAAsB,KAAK,cAAc,GAAG,IAAI,CAAC;IAC5E,eAAe,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,sBAAsB,KAAK,IAAI,CAAC;IAG9F,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;IACnD,YAAY,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,CAAC;IACjD,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE,eAAe,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IAC7D,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,6BAA6B,GACrC,4BAA4B,CA+W9B"}
package/dist/index.d.ts CHANGED
@@ -1,13 +1,11 @@
1
- /**
2
- * @aivue/tabular-intelligence
3
- * Tabular Foundation Model (TFM) integration for Vue.js
4
- */
5
- export { TabularIntelligence } from './core/TabularIntelligence';
6
- export { useTabularIntelligence } from './composables/useTabularIntelligence';
1
+ import { TabularIntelligence } from './core/TabularIntelligence';
2
+ import { useTabularIntelligence } from './composables/useTabularIntelligence';
3
+ export { TabularIntelligence };
4
+ export { useTabularIntelligence };
7
5
  export type { UseTabularIntelligenceOptions, UseTabularIntelligenceReturn } from './composables/useTabularIntelligence';
8
- export { default as QuestionInput } from './components/QuestionInput.vue';
9
- export { default as AnswerDisplay } from './components/AnswerDisplay.vue';
10
- export { default as QuestionHistory } from './components/QuestionHistory.vue';
6
+ export declare const QuestionInput: any;
7
+ export declare const AnswerDisplay: any;
8
+ export declare const QuestionHistory: any;
11
9
  export { inferSchema, inferColumnType, calculateStats, detectAnomalies } from './utils/helpers';
12
10
  export { QAEngine, type QAEngineConfig } from './utils/qaEngine';
13
11
  export { extractFromDOM, normalizeVueData } from './utils/tableExtractor';
@@ -28,4 +26,21 @@ export { generateReport, generateExecutiveSummary, generateInsights } from './ad
28
26
  export { detectPII, anonymizeData, checkCompliance } from './advanced/privacy';
29
27
  export { createSnapshot, compareSnapshots, trackLineage, addTransformation, createPipeline, executePipeline, savePipeline, loadPipeline } from './advanced/versioning';
30
28
  export { connectStream, monitorAnomalies, streamingAggregation, detectStreamingAnomalies, calculateWindowedAggregations, smartSample } from './advanced/streaming';
29
+ /**
30
+ * Vue Plugin for Tabular Intelligence
31
+ * Provides global component registration with Vue 2/3 compatibility
32
+ */
33
+ export declare const TabularIntelligencePlugin: any;
34
+ declare const _default: {
35
+ TabularIntelligence: typeof TabularIntelligence;
36
+ useTabularIntelligence: typeof useTabularIntelligence;
37
+ QuestionInput: any;
38
+ AnswerDisplay: any;
39
+ QuestionHistory: any;
40
+ TabularIntelligencePlugin: any;
41
+ createCompatComponent: createCompatComponent;
42
+ registerCompatComponent: registerCompatComponent;
43
+ createCompatPlugin: createCompatPlugin;
44
+ };
45
+ export default _default;
31
46
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,YAAY,EAAE,6BAA6B,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGxH,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAChG,OAAO,EAAE,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC7H,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAG3I,cAAc,SAAS,CAAC;AAOxB,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACrB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG1D,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EACnB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,SAAS,EACT,aAAa,EACb,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,wBAAwB,EACxB,kBAAkB,EACnB,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACxB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACpB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,cAAc,EACf,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EACL,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,gBAAgB,EACjB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,SAAS,EACT,aAAa,EACb,eAAe,EAChB,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,YAAY,EACZ,YAAY,EACb,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,oBAAoB,EACpB,wBAAwB,EACxB,6BAA6B,EAC7B,WAAW,EACZ,MAAM,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAUH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAG9E,OAAO,EAAE,mBAAmB,EAAE,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,CAAC;AAClC,YAAY,EAAE,6BAA6B,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAQxH,eAAO,MAAM,aAAa,KAAgD,CAAC;AAC3E,eAAO,MAAM,aAAa,KAAgD,CAAC;AAC3E,eAAO,MAAM,eAAe,KAAkD,CAAC;AAG/E,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAChG,OAAO,EAAE,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC7H,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAG3I,cAAc,SAAS,CAAC;AAOxB,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACrB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG1D,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EACnB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,SAAS,EACT,aAAa,EACb,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,wBAAwB,EACxB,kBAAkB,EACnB,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,uBAAuB,EACxB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACpB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,cAAc,EACf,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EACL,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,cAAc,EACd,wBAAwB,EACxB,gBAAgB,EACjB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,SAAS,EACT,aAAa,EACb,eAAe,EAChB,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,YAAY,EACZ,YAAY,EACb,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EACL,aAAa,EACb,gBAAgB,EAChB,oBAAoB,EACpB,wBAAwB,EACxB,6BAA6B,EAC7B,WAAW,EACZ,MAAM,sBAAsB,CAAC;AAQ9B;;;GAGG;AACH,eAAO,MAAM,yBAAyB,KAOpC,CAAC;;;;;;;;;;;;AAMH,wBAmBE"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("vue");function x(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=Q(s,o);return{name:o,type:a,nullable:s.some(i=>i[o]==null)}}),rowCount:s.length,name:e}}function Q(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 J(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 G(s,e,t=.5){const n=[],o=1.5+(1-t)*1.5;return e.forEach(a=>{const i=s.map((h,p)=>({value:Number(h[a]),idx:p})).filter(h=>!isNaN(h.value));if(i.length===0)return;const r=[...i].sort((h,p)=>h.value-p.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:h,idx:p})=>{if(h<m||h>d){const g=n.find(y=>y.rowIndex===p),v=h<m?`${a}: ${h.toFixed(2)} < ${m.toFixed(2)}`:`${a}: ${h.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:p,row:s[p],score:.7,reasons:[v],affectedColumns:[a]})}})}),n.sort((a,i)=>i.score-a.score)}class _{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=J(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.
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
3
  `;r+=`**Table Schema:**
4
4
  `,r+=`Table: ${t.name}
@@ -64,7 +64,7 @@ With an OpenAI or Anthropic API key, I can also:
64
64
 
65
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
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 W(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 p=c[0];l=Array.from(p.cells).map((g,v)=>{var C;return((C=g.textContent)==null?void 0:C.trim())||""||`Column${v+1}`}),u=1}else{const p=c[0];l=Array.from(p.cells).map((g,v)=>`Column${v+1}`)}const m=[],d=n?c.slice(u,u+n):c.slice(u);for(const p of d){const g=Array.from(p.cells);if(a&&g.every(y=>{var C;return!((C=y.textContent)!=null&&C.trim())}))continue;const v={};g.forEach((y,C)=>{var E;const P=l[C]||`Column${C+1}`;let I=((E=y.textContent)==null?void 0:E.trim())||"";if(o&&I){const D=parseFloat(I);!isNaN(D)&&I===D.toString()&&(I=D)}v[P]=I}),m.push(v)}return{schema:o&&m.length>0?x(m,"Extracted Table"):we(l,m.length),data:m,source:"dom",metadata:{selector:e,rowCount:m.length,columnCount:l.length,extractedAt:new Date}}}function X(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?Q(a,r.field):"string",nullable:!0})),rowCount:a.length}:a.length>0?i=x(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 we(s,e=0){return{name:"Extracted Table",columns:s.map(t=>({name:t,type:"string",nullable:!0})),rowCount:e}}function Y(s){const e={};s.variable&&s.variable.forEach(a=>{e[a.key]=a.value});const t=s.auth?Z(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(ve(r,t))})}return o(s.item),{name:s.info.name,description:s.info.description,endpoints:n,variables:e,auth:t}}function ve(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?Z(t.auth):e;return{name:s.name,method:t.method,url:t.url.raw,description:t.description,headers:n,queryParams:o,auth:a}}function Z(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 M(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 H(s){const{endpoint:e,variables:t={},additionalHeaders:n={},additionalParams:o={}}=s;try{let a=M(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(M(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]=M(c[d],t)}),e.auth){if(e.auth.type==="apikey"){const d=e.auth.credentials.key||"access_key",h=M(e.auth.credentials.value||"",t);e.auth.credentials.in==="header"&&(c[d]=h)}else if(e.auth.type==="bearer"){const d=M(e.auth.credentials.token||"",t);c.Authorization=`Bearer ${d}`}else if(e.auth.type==="basic"){const d=M(e.auth.credentials.username||"",t),h=M(e.auth.credentials.password||"",t),p=btoa(`${d}:${h}`);c.Authorization=`Basic ${p}`}}const l=await fetch(a,{method:e.method,headers:c}),u={};return l.headers.forEach((d,h)=>{u[h]=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 be(s,e={}){const t=[];for(const n of s){const o=await H({endpoint:n,variables:e});t.push(o)}return t}function ee(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 te{constructor(e,t){this.config={timeout:3e4,...e},t&&(this.qaEngine=new _(t))}initializeQA(e){this.qaEngine=new _(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 W(e)}normalizeVueData(e,t,n){return X(e,t,n)}updateConfig(e){this.config={...this.config,...e}}getConfig(){const{apiKey:e,...t}=this.config;return t}loadPostmanCollection(e){return this.parsedCollection=Y(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 H({endpoint:n,variables:o});if(!a.success)throw new Error(`API request failed: ${a.error}`);const i=ee(a),r=x(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 Ce(s){const e=new te(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=h(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"),h(w,b);throw n.value}finally{t.value=!1}}function h(w,b){const S=i.value||x(a.value);switch(w){case"descriptive_stats":{const N=S.columns.map(A=>J(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=G(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($=>$.type==="number").map($=>$.name),A=(b==null?void 0:b.numClusters)||3,k=Array.from({length:A},($,O)=>({id:O,label:`Cluster ${O+1}`,centroid:{},size:Math.floor(a.value.length/A),characteristics:[`Group ${O+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($=>{A[k][$]=k===$?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 p(){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 P(w,b=!0){a.value=w,b&&(i.value=x(w))}function I(){t.value=!1,n.value=null,o.value=null,r.value=[],c.value=[],l.value=null}async function E(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||x(a.value),N={question:w,schema:S,data:a.value,sampleSize:100,includeAggregates:!0,...b},k=(await e.askQuestion(N)).answer,$={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($),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 D(){t.value=!0,n.value=null;try{const w=i.value||x(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 he(){r.value=[],c.value=[],l.value=null}function pe(w){const b=e.extractFromDOM(w);return b&&(a.value=b.data,i.value=b.schema),b}function ge(w,b,S){const N=e.normalizeVueData(w,b,S);a.value=N.data,i.value=N.schema}function ye(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:p,detectAnomalies:g,performClustering:v,predict:y,askQuestion:E,generateSummary:D,clearHistory:he,extractFromDOM:pe,loadFromVueGrid:ge,updateConfig:C,initializeQA:ye,setData:P,reset:I}}const ke={class:"ti-question-input"},Ae={class:"ti-input-wrapper"},Se=["placeholder","disabled","onKeydown"],Ne=["disabled"],Ie={key:0},$e={key:1,class:"ti-loading"},Me={key:0,class:"ti-hint"},xe=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",ke,[f.createElementVNode("div",Ae,[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,Se),[[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",$e,f.toDisplayString(r.loadingLabel),1)):(f.openBlock(),f.createElementBlock("span",Ie,f.toDisplayString(r.submitLabel),1))],8,Ne)]),r.showHint?(f.openBlock(),f.createElementBlock("div",Me,f.toDisplayString(r.hint),1)):f.createCommentVNode("",!0)]))}}),L=(s,e)=>{const t=s.__vccOpts||s;for(const[n,o]of e)t[n]=o;return t},Pe=L(xe,[["__scopeId","data-v-f96008f3"]]),qe={class:"ti-answer-header"},De={class:"ti-answer-icon"},Te={key:0},Ee={key:1},Ve={class:"ti-answer-meta"},ze={class:"ti-confidence"},Re={class:"ti-timestamp"},Oe={class:"ti-answer-text"},_e={key:0,class:"ti-approximate-notice"},Fe={key:1,class:"ti-reason"},Be={key:2,class:"ti-supporting-data"},je={key:0,class:"ti-supporting-content"},Qe={key:0,class:"ti-aggregates"},Je={key:1,class:"ti-rows"},He={class:"ti-table-wrapper"},Le={class:"ti-table"},Ue=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",qe,[f.createElementVNode("div",De,[n.answer.cannotAnswer?(f.openBlock(),f.createElementBlock("span",Ee,"⚠️")):(f.openBlock(),f.createElementBlock("span",Te,"💡"))]),f.createElementVNode("div",Ve,[f.createElementVNode("div",ze," Confidence: "+f.toDisplayString(Math.round(n.answer.confidence*100))+"% ",1),f.createElementVNode("div",Re,f.toDisplayString(t(n.answer.timestamp)),1)])]),f.createElementVNode("div",Oe,f.toDisplayString(n.answer.text),1),n.answer.isApproximate?(f.openBlock(),f.createElementBlock("div",_e," ℹ️ 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",Fe,[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",Be,[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",je,[n.answer.supportingData.aggregates?(f.openBlock(),f.createElementBlock("div",Qe,[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",Je,[f.createElementVNode("h4",null,"Sample Rows ("+f.toDisplayString(n.answer.supportingData.rows.length)+"):",1),f.createElementVNode("div",He,[f.createElementVNode("table",Le,[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))}}),Ke=L(Ue,[["__scopeId","data-v-d1aaae1d"]]),Ge={class:"ti-question-history"},We={class:"ti-history-header"},Xe={key:0,class:"ti-empty-state"},Ye={key:1,class:"ti-history-list"},Ze=["onClick"],et={class:"ti-question-header"},tt={class:"ti-question-number"},nt={class:"ti-question-time"},st={class:"ti-question-text"},ot={key:0,class:"ti-question-context"},at=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",Ge,[f.createElementVNode("div",We,[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",Xe,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",Ye,[(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",et,[f.createElementVNode("span",tt,"#"+f.toDisplayString(a.questions.length-c),1),f.createElementVNode("span",nt,f.toDisplayString(o(r.timestamp)),1)]),f.createElementVNode("div",st,f.toDisplayString(r.text),1),r.context?(f.openBlock(),f.createElementBlock("div",ot,f.toDisplayString(r.context.rowCount)+" rows ",1)):f.createCommentVNode("",!0)],8,Ze))),128))]))]))}}),rt=L(at,[["__scopeId","data-v-c66393d9"]]);async function R(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 it(s,u);n.push(m)}const o=n.filter(u=>u.type==="numeric").map(u=>u.name),a=ft(s,o),i=pt(s),r=gt(s),c=yt(n,i.count),l=wt(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 it(s,e,t){const n=s.map(m=>m[e]),o=ct(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=lt(n):o==="categorical"?u.categories=ut(n):o==="datetime"&&(u.dateRange=mt(n)),u.quality=dt(u),u}function ct(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 lt(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,h=u+1.5*m,p=e.filter(y=>y<d||y>h).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:p,q1:l,q3:u,iqr:m}}function ut(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 mt(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 dt(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 ft(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=ht(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 ht(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,h=o[m]-i;r+=d*h,c+=d*d,l+=h*h}const u=Math.sqrt(c*l);return u===0?0:r/u}function pt(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 gt(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 yt(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 wt(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 vt(s){const e=await R(s),t=await U(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=bt(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 U(s,e){e||(e=await R(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 bt(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 Ct(s){const e=await R(s);await U(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 kt(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,h)=>d==null||d===""?h:-1).filter(d=>d!==-1);if(u.length===0)continue;let m;switch(t){case"mean":m=V(l);break;case"median":m=At(l);break;case"mode":m=St(l);break;case"knn":a=await Nt(a,c,u);break;case"iterative":a=await ne(a,c,u);break;case"ai":a=await It(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:$t(t),details:r}}function V(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 At(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 St(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 Nt(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 h of i){const p=Number(s[r][h]),g=Number(u[h]);!isNaN(p)&&!isNaN(g)&&(d+=Math.pow(p-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]=V(u)}}return o}async function ne(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=V(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 h of a){const p=Number(s[r][h]),g=Number(u[h]);!isNaN(p)&&!isNaN(g)&&(m+=1/(1+Math.abs(p-g)),d++)}if(d>0){const h=m/d;c+=h*Number(u[e]),l+=h}}n[r][e]=l>0?c/l:V(s.map(u=>u[e]))}return n}async function It(s,e,t){return ne(s,e,t)}function $t(s){return{mean:.6,median:.65,mode:.7,knn:.8,iterative:.85,ai:.9}[s]||.5}async function Mt(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=xt(s,u,n);if(r+=m.length,t==="remove"){const d=new Set(m.map(h=>h.index));i=i.filter((h,p)=>!d.has(p)),c+=m.length}else if(t==="cap"){const d=qt(s,u,n);for(const h of m)h.value<d.lower?i[h.index][u]=d.lower:h.value>d.upper&&(i[h.index][u]=d.upper)}else if(t==="transform")for(let d=0;d<i.length;d++){const h=Number(i[d][u]);!isNaN(h)&&h>0&&(i[d][u]=Math.log(h+1))}l.push({column:u,outliers:m})}return{data:i,outliersDetected:r,outliersRemoved:c,method:t,columns:a,details:l}}function xt(s,e,t){return s.map(n=>Number(n[e])).filter(n=>!isNaN(n)),t==="iqr"?K(s,e):t==="zscore"?Pt(s,e):K(s,e)}function K(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 Pt(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 qt(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 Dt(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=Vt(r);for(let g=1;g<=o;g++){const v=new Date(m.getTime()+g*d),y=u,P=1.96*ae(r.map(I=>I.value));l.push({timestamp:v,value:y,lower:y-P,upper:y+P})}const h=oe(r),p=await se(s,{dateColumn:t,valueColumn:n});return{predictions:l,method:a,horizon:o,confidence:i,trend:{direction:h.direction,strength:h.strength},seasonality:p}}async function Tt(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=oe(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 se(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=zt(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 Et(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,h=Math.abs(d-m),p=ae([...l,...u]);h>o*p&&i.push({index:c,timestamp:a[c].timestamp,type:"mean_shift",confidence:Math.min(h/p,1),before:m,after:d,magnitude:h})}return i}function Vt(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 oe(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 ae(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 zt(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 Rt(s,e){const{targetColumn:t,taskType:n,metric:o,models:a=["linear","tree","ensemble"]}=e,i=Object.keys(s[0]).filter(h=>h!==t),r=s.map(h=>i.map(p=>Number(h[p])||0)),c=s.map(h=>h[t]),l=[];for(const h of a){const p=await z(r,c,h,n);l.push(p)}const u=o||(n==="classification"?"accuracy":"r2Score"),m=l.reduce((h,p)=>{const g=h.metrics[u]||0;return(p.metrics[u]||0)>g?p:h}),d=Qt(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:Jt(l,n),featureImportance:d,metrics:m.metrics}}async function Ot(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=re(r),l=[];for(const m of n){const d=await z(i,r,m,c);l.push(d)}const u=l.reduce((m,d)=>{const h=m.metrics.accuracy||m.metrics.r2Score||0;return(d.metrics.accuracy||d.metrics.r2Score||0)>h?d:m}).name;return{models:l,winner:u,comparisonMetric:c==="classification"?"accuracy":"r2Score"}}async function _t(s,e){const{targetColumn:t,iterations:n=10}=e,o=Object.keys(s[0]).filter(d=>d!==t),a=s.map(d=>o.map(h=>Number(d[h])||0)),i=s.map(d=>d[t]),r=re(i),c=[];for(let d=0;d<n;d++){const h=Ht(),p=await z(a,i,"tree",r,h),g=p.metrics.accuracy||p.metrics.r2Score||0;c.push({parameters:h,score:g,iteration:d})}const l=c.reduce((d,h)=>h.score>d.score?h:d),u=await z(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 z(s,e,t,n,o){const a=Date.now();let i={};if(n==="classification"){const r=e.map(()=>jt(e));i=Ft(e,r)}else{const r=e.reduce((l,u)=>l+u,0)/e.length,c=e.map(()=>r);i=Bt(e,c)}return{name:t.charAt(0).toUpperCase()+t.slice(1),type:t,metrics:i,trainingTime:Date.now()-a,parameters:o||{}}}function re(s){return new Set(s).size<s.length*.05?"classification":"regression"}function Ft(s,e){const n=s.filter((o,a)=>o===e[a]).length/s.length;return{accuracy:n,precision:n,recall:n,f1Score:n}}function Bt(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 jt(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 Qt(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 Jt(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 Ht(){return{maxDepth:Math.floor(Math.random()*10)+3,minSamplesSplit:Math.floor(Math.random()*5)+2,learningRate:Math.random()*.1+.01}}async function Lt(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],h=`${m}_x_${d}`;if(r=r.map(p=>({...p,[h]:(Number(p[m])||0)*(Number(p[d])||0)})),c.push({name:h,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 Ut(s,e){let t=JSON.parse(JSON.stringify(s));for(const n of e)t=Gt(t,n);return t}async function ie(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(Wt(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 Kt(s,e){var r;const{targetColumn:t,method:n,topK:o=10}=e,a=await ie(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 Gt(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 Wt(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 Xt(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],h=Math.random()*2-1;return{feature:m,value:d,shapValue:h,impact:h>0?"positive":"negative",percentage:Math.abs(h)*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 Yt(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 Zt(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 en(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 h of d){const p=i[h],g=typeof p=="number"?p*(1+(Math.random()-.5)*.2):p;u[h]=g,m.push({feature:h,from:p,to:g,changeType:g>p?"increase":"decrease"})}c.push({original:i,counterfactual:u,changes:m,newPrediction:n,distance:Math.random(),feasibility:Math.random()})}return c}async function tn(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=q(a),u=q(i),{pValue:m}=ce(a,i),d=Math.sqrt((l**2+u**2)/2),h=(c-r)/d;let p;m<1-o?p=c>r?"treatment":"control":p="inconclusive";const g=p==="inconclusive"?"No significant difference detected. Consider collecting more data.":`${p==="treatment"?"Treatment":"Control"} group performs better with ${Math.abs(h).toFixed(2)} effect size.`;return{winner:p,pValue:m,confidenceInterval:[c-r-1.96*d,c-r+1.96*d],effectSize:h,statisticalPower:.8,recommendation:g,controlStats:{mean:r,std:l,size:a.length},treatmentStats:{mean:c,std:u,size:i.length}}}async function nn(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}=ce(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:q(a),size:a.length},{name:"Group 2",mean:i.reduce((l,u)=>l+u,0)/i.length,std:q(i),size:i.length}]}}return{testType:e,pValue:.05,statistic:0,significant:!1,alpha:o,interpretation:"Test not fully implemented",groups:[]}}async function sn(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 q(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 ce(s,e){const t=s.reduce((m,d)=>m+d,0)/s.length,n=e.reduce((m,d)=>m+d,0)/e.length,o=q(s)**2,a=q(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-on(Math.abs(l))),statistic:l}}function on(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 an(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=F(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 T({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 T({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 T({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 T({type:"histogram",xColumn:o[0],data:s}),insights:["Shows data distribution and outliers"]}),n.sort((r,c)=>r.priority-c.priority)}async function T(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:F(a.map(r=>r[t]))},data:a};if(n){const r=F(a.map(c=>c[n]));i.yAxis={column:n,label:n,type:r==="datetime"?"numeric":r}}return o&&(i.groupBy=o),i}async function rn(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 F(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 le(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 ue(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 h=un(r,m,c,d,a,i);h&&e.push(h)}}return e}async function cn(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 le({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 ln(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:mn(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 ue(s);return{tables:e,relationships:t}}function un(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 mn(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 dn(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 me(s)}),n.includes("stats")&&a.push({type:"stats",title:"Statistical Overview",content:hn(s)}),n.includes("recommendations")&&a.push({type:"recommendations",title:"Recommendations",content:pn()}),{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 me(s){const e=s.length,t=Object.keys(s[0]||{}).length;return`
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
68
  # Executive Summary
69
69
 
70
70
  This dataset contains **${e} rows** and **${t} columns**.
@@ -78,19 +78,19 @@ This dataset contains **${e} rows** and **${t} columns**.
78
78
  - Consider feature engineering for improved analysis
79
79
  - Review data quality metrics
80
80
  - Explore correlations between variables
81
- `.trim()}async function fn(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 hn(s){const e=Object.keys(s[0]||{}),t=e.filter(n=>s.map(a=>a[n]).some(a=>!isNaN(Number(a))));return`
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
82
  ## Statistical Overview
83
83
 
84
84
  - Total Rows: ${s.length}
85
85
  - Total Columns: ${e.length}
86
86
  - Numeric Columns: ${t.length}
87
87
  - Categorical Columns: ${e.length-t.length}
88
- `.trim()}function pn(s){return`
88
+ `.trim()}function bn(s){return`
89
89
  ## Recommendations
90
90
 
91
91
  1. **Data Quality**: Review and clean missing values
92
92
  2. **Feature Engineering**: Create interaction features for better insights
93
93
  3. **Analysis**: Perform correlation analysis to identify relationships
94
94
  4. **Visualization**: Create charts to explore patterns
95
- `.trim()}async function de(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=>wn(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=>vn(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:An(t),riskLevel:n}}async function gn(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]=bn(i[c],t);return r}),method:t,columns:o,reversible:t==="tokenization",privacyLevel:kn(t)}}async function yn(s,e){const t=await de(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 wn(s){const[e,t]=s.split("@");return`${e.slice(0,2)}***@${t}`}function vn(s){return s.replace(/\d/g,(e,t)=>t<s.length-4?"*":e)}function bn(s,e){if(s==null)return s;switch(e){case"masking":return"***MASKED***";case"hashing":return Cn(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 Cn(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 kn(s){return{masking:60,hashing:80,generalization:50,differential_privacy:95,tokenization:70}[s]||50}function An(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 B=new Map,fe=new Map;async function Sn(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:Dn(s.map(i=>i[a]))})),rowCount:s.length},timestamp:new Date,metadata:{rowCount:s.length,columnCount:n.length,checksum:Tn(s)}};return B.set(t,o),o}async function Nn(s,e){const t=B.get(s),n=B.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 In(s,e){const t={source:e,transformations:[],currentState:{rowCount:0,columnCount:0,lastModified:new Date}};return fe.set(s,t),t}function $n(s,e,t){const n=fe.get(s);n&&n.transformations.push({operation:e,timestamp:new Date,params:t})}async function Mn(s){return{id:`pipeline_${Date.now()}`,name:"Data Processing Pipeline",steps:s,createdAt:new Date}}async function xn(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 En(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 Pn(s,e){console.log(`Pipeline "${e}" saved`)}async function qn(s){return{id:"loaded_pipeline",name:s,steps:[],createdAt:new Date}}function Dn(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 Tn(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 En(s,e){return s}async function Vn(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 zn(s,e){const{columns:t,threshold:n,windowSize:o=100}=e;console.log(`Monitoring anomalies on columns: ${t.join(", ")}`)}async function Rn(s,e){const{windowType:t,windowSize:n,aggregations:o}=e;console.log(`Streaming aggregation: ${t} window of ${n}`)}async function On(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 h=Math.abs((d-c)/l);h>n&&a.push({rowIndex:m,row:u,score:h/10,reasons:[`${i} value ${d} is ${h.toFixed(2)} standard deviations from mean`],affectedColumns:[i]})}})}return a}async function _n(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((h,p)=>h+p,0);break;case"avg":m=u.reduce((h,p)=>h+p,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((h,p)=>h+p,0)/u.length;m=Math.sqrt(u.reduce((h,p)=>h+Math.pow(p-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 Fn(s,e){const{size:t,method:n,preserveDistribution:o=!0}=e;let a=[];switch(n){case"random":a=j(s,t);break;case"systematic":a=Bn(s,t);break;case"stratified":a=jn(s,t);break;default:a=j(s,t)}return{data:a,method:n,originalSize:s.length,sampleSize:a.length,preservedDistribution:o,representativeness:.85}}function j(s,e){return[...s].sort(()=>Math.random()-.5).slice(0,e)}function Bn(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 jn(s,e){return j(s,e)}exports.AnswerDisplay=Ke;exports.QAEngine=_;exports.QuestionHistory=rt;exports.QuestionInput=Pe;exports.TabularIntelligence=te;exports.addTransformation=$n;exports.analyzeABTest=tn;exports.analyzeCrossTables=cn;exports.analyzeFeatureImportance=ie;exports.anonymizeData=gn;exports.assessDataQuality=vt;exports.autoGenerateFeatures=Lt;exports.autoTrain=Rt;exports.calculateSampleSize=sn;exports.calculateStats=J;exports.calculateWindowedAggregations=_n;exports.checkCompliance=yn;exports.compareModels=Ot;exports.compareSnapshots=Nn;exports.connectStream=Vn;exports.convertToTabular=ee;exports.createFeatures=Ut;exports.createPipeline=Mn;exports.createSnapshot=Sn;exports.detectAnomalies=G;exports.detectChangePoints=Et;exports.detectDataIssues=U;exports.detectPII=de;exports.detectPatterns=rn;exports.detectRelationships=ue;exports.detectSeasonality=se;exports.detectStreamingAnomalies=On;exports.detectTrends=Tt;exports.executeAPIRequest=H;exports.executeMultipleRequests=be;exports.executePipeline=xn;exports.explainPrediction=Xt;exports.extractFromDOM=W;exports.forecastTimeSeries=Dt;exports.generateChartSpec=T;exports.generateCounterfactuals=en;exports.generateExecutiveSummary=me;exports.generateInsights=fn;exports.generateReport=dn;exports.getFeatureImportance=Yt;exports.getPartialDependence=Zt;exports.handleOutliers=Mt;exports.imputeMissingValues=kt;exports.inferColumnType=Q;exports.inferDatabaseSchema=ln;exports.inferSchema=x;exports.joinTables=le;exports.loadPipeline=qn;exports.monitorAnomalies=zn;exports.normalizeVueData=X;exports.parsePostmanCollection=Y;exports.profileData=R;exports.recommendVisualizations=an;exports.replaceVariables=M;exports.savePipeline=Pn;exports.selectBestFeatures=Kt;exports.smartSample=Fn;exports.streamingAggregation=Rn;exports.suggestCleaningSteps=Ct;exports.testSignificance=nn;exports.trackLineage=In;exports.tuneHyperparameters=_t;exports.useTabularIntelligence=Ce;
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;
96
96
  //# sourceMappingURL=index.js.map