diff --git a/README.md b/README.md index 042d8fe..9295034 100644 --- a/README.md +++ b/README.md @@ -50,15 +50,24 @@ Open-source AI assistant for ERPNext. Ask business questions in plain English an 9. **Module-Wise Training Data Automation** — changAI includes tools to auto-generate training data on a per-module basis across your ERPNext installation. You can select individual modules such as Accounts, Inventory, or HR and generate targeted training data for each, allowing the model's retrieval accuracy to improve incrementally without needing to retrain everything at once. 10. **Fine-Tuned Embedding Model** — changAI uses a custom fine-tuned embedding model built on nomic-embed-text-v1.5, specifically trained on ERPNext schema and retrieval data for better semantic matching. + 11. **Translation Support** — changAI supports multilingual ERP usage by translating values across all DocTypes. This allows users to interact with ERPNext in their preferred language. Users can configure their preferred language directly in ChangAI Settings. +12. **English & Arabic Language Support** - changAI supports ERP interactions in both English and Arabic, enabling users to query and manage ERP data in their preferred language while preserving master data values accurately. + +13. **ERP Report Navigation & Smart Filter Detection** - changAI can identify when a user is requesting a standard ERPNext report and automatically open the appropriate report with relevant filters applied. + +14. **Entity Creation from Natural Language** - changAI allows users to create ERP records directly from natural language requests. Users can create customers, suppliers, items, projects, leads, opportunities, and other ERP entities by simply describing what they need. changAI automatically opens the appropriate ERPNext form with detected values pre-filled, reducing manual data entry and improving productivity. + +**You can Enable or Disable ChangAI from "ChangAI Settings Doctype"** ## Tech Stack **Backend** ** Please note new URL on github https://github.com/ERPGulf/changai** - [Frappe Framework](https://frappeframework.com) — Full-stack Python web framework that powers ERPNext. Handles authentication, permissions, database queries, and API routing. -- Python 3.10+ — Core language for all backend logic, model serving, and pipeline orchestration. +- Python 3.14 — Core language for all backend logic, model serving, and pipeline orchestration. +**Note** - Python 3.14 requires sudo apt-get install build-essential python3-dev before bench get-app **AI and Machine Learning** @@ -199,7 +208,8 @@ Natural Language Result is returned as a human-readable answer No. changAI is built for non-technical users. You type a question in plain English and the system handles schema lookup, query generation, and result formatting automatically. **Which ERPNext versions are supported?** -changAI supports ERPNext v14, v15, and v16 on Ubuntu with Python 3.10 or higher. +changAI supports ERPNext v15, and v16 on Ubuntu with Python 3.14 or higher. +**Note** - Python 3.14 requires sudo apt-get install build-essential python3-dev before bench get-app **Which modules does changAI cover out of the box?** changAI ships pre-configured with the standard ERPNext schema, so modules like Accounts, Inventory, Purchasing, Sales, and HR work immediately after installation without any additional mapping. Custom doctypes and fields require a schema sync using an Anthropic Claude API key. diff --git a/changai/changai/api/v2/assets/business_keywords_v1.json b/changai/changai/api/v2/assets/business_keywords_v1.json index 013ff8e..9b992f6 100644 --- a/changai/changai/api/v2/assets/business_keywords_v1.json +++ b/changai/changai/api/v2/assets/business_keywords_v1.json @@ -27908,6 +27908,8 @@ "المدفوعات", "المبيعات الشهرية", "المشتريات الشهرية", + "أنشئ", + "صنفًا", "BOM" ] } \ No newline at end of file diff --git a/changai/changai/api/v2/assets/changai_alias_map.json b/changai/changai/api/v2/assets/changai_alias_map.json index 61b40c7..4e45bff 100644 --- a/changai/changai/api/v2/assets/changai_alias_map.json +++ b/changai/changai/api/v2/assets/changai_alias_map.json @@ -1318,6 +1318,7 @@ "sounds great": "i agree", "sounds right": "i agree", "looks good": "i agree", + "thanku": "thank you", "feine": "fine", "fiene": "fine", "fein": "fine", diff --git a/changai/changai/api/v2/assets/metaschema_clean_v2.json b/changai/changai/api/v2/assets/metaschema_clean_v2.json index 10ed020..53d2f7c 100644 --- a/changai/changai/api/v2/assets/metaschema_clean_v2.json +++ b/changai/changai/api/v2/assets/metaschema_clean_v2.json @@ -2949,7 +2949,6 @@ "naming_series": "TEXT", "salutation": "TEXT", "customer_name": "TEXT", - "customer_name_ar": "TEXT", "zatca_customer_name_in_arabic": "TEXT", "custom_b2c": "TEXT", "custom_buyer_id_type": "TEXT", @@ -4538,10 +4537,8 @@ }, "tabEmployee": { "employee": "TEXT", - "employee_ar": "TEXT", "naming_series": "TEXT", "first_name": "TEXT", - "first_name_ar": "TEXT", "middle_name": "TEXT", "last_name": "TEXT", "employee_name": "TEXT", @@ -5566,7 +5563,6 @@ "naming_series": "TEXT", "item_code": "TEXT", "item_name": "TEXT", - "item_name_ar": "TEXT", "item_group": "TEXT", "stock_uom": "TEXT", "disabled": "TEXT", @@ -11841,11 +11837,9 @@ "naming_series": "TEXT", "customer": "TEXT", "custom_b2c": "TEXT", - "customer_ar": "TEXT", "customer_name": "TEXT", "tax_id": "TEXT", "company": "TEXT", - "company_ar": "TEXT", "company_tax_id": "TEXT", "posting_date": "TEXT", "posting_time": "TEXT", @@ -14568,7 +14562,6 @@ "tabToDo": { "status": "TEXT", "priority": "TEXT", - "priority_ar": "TEXT", "color": "TEXT", "date": "TEXT", "allocated_to": "TEXT", diff --git a/changai/changai/api/v2/assets/non_erp_combined.processed.cache.pkl b/changai/changai/api/v2/assets/non_erp_combined.processed.cache.pkl index 25d4599..af55b35 100644 Binary files a/changai/changai/api/v2/assets/non_erp_combined.processed.cache.pkl and b/changai/changai/api/v2/assets/non_erp_combined.processed.cache.pkl differ diff --git a/changai/changai/api/v2/assets/non_erp_combined.processed.json b/changai/changai/api/v2/assets/non_erp_combined.processed.json index 67b7e84..76acf2b 100644 --- a/changai/changai/api/v2/assets/non_erp_combined.processed.json +++ b/changai/changai/api/v2/assets/non_erp_combined.processed.json @@ -93372,6 +93372,13 @@ "priority": 70, "is_active": true }, + { + "category": "conversation", + "user_input": "fine thanks.", + "response": "Glad to hear that! 😊 changAI by ERPGulf is here whenever you need assistance.", + "priority": 70, + "is_active": true + }, { "category": "conversation", "user_input": "are you religious", @@ -136922,14 +136929,14 @@ { "category": "negative", "user_input": "no thanks", - "response": "No problem.", + "response": "You're welcome! Let me know if you need anything else.", "priority": 100, "is_active": true }, { "category": "negative", "user_input": "no thank you", - "response": "Alright.", + "response": "Alright.🙂", "priority": 100, "is_active": true }, diff --git a/changai/changai/api/v2/assets/report_intent_map.json b/changai/changai/api/v2/assets/report_intent_map.json new file mode 100644 index 0000000..ef60b10 --- /dev/null +++ b/changai/changai/api/v2/assets/report_intent_map.json @@ -0,0 +1,191 @@ +{ + "account statement": "General Ledger", + "customer account statement": "General Ledger", + "supplier account statement": "General Ledger", + "customer statement": "General Ledger", + "supplier statement": "General Ledger", + "party statement": "General Ledger", + "ledger statement": "General Ledger", + "general ledger": "General Ledger", + "gl": "General Ledger", + "g l": "General Ledger", + "ledger entries": "General Ledger", + "journal entries": "General Ledger", + "customer ledger": "Customer Ledger Summary", + "supplier ledger": "Supplier Ledger Summary", + "payment ledger": "Payment Ledger", + "share ledger": "Share Ledger", + "trial balance": "Trial Balance", + "tb": "Trial Balance", + "trial bal": "Trial Balance", + "party trial balance": "Trial Balance for Party", + "balance sheet": "Balance Sheet", + "profit and loss": "Profit and Loss Statement", + "p and l": "Profit and Loss Statement", + "p&l": "Profit and Loss Statement", + "cash flow": "Cash Flow", + "financial ratios": "Financial Ratios", + "profitability analysis": "Profitability Analysis", + "account balance": "Account Balance", + "voucher balance": "Voucher-wise Balance", + "dimension balance": "Dimension-wise Accounts Balance Report", + "budget variance": "Budget Variance Report", + "accounts receivable": "Accounts Receivable", + "ar": "Accounts Receivable", + "receivable": "Accounts Receivable", + "receivable aging": "Accounts Receivable", + "customer outstanding": "Accounts Receivable", + "customer dues": "Accounts Receivable", + "accounts receivable summary": "Accounts Receivable Summary", + "accounts payable": "Accounts Payable", + "ap": "Accounts Payable", + "payable": "Accounts Payable", + "payable aging": "Accounts Payable", + "supplier outstanding": "Accounts Payable", + "supplier dues": "Accounts Payable", + "accounts payable summary": "Accounts Payable Summary", + "stock ledger": "Stock Ledger", + "item ledger": "Stock Ledger", + "stock movement": "Stock Ledger", + "inventory movement": "Stock Ledger", + "stock balance": "Stock Balance", + "item balance": "Item Balance (Simple)", + "stock ageing": "Stock Ageing", + "stock aging": "Stock Ageing", + "stock analytics": "Stock Analytics", + "warehouse stock": "Warehouse Wise Stock Balance", + "warehouse stock balance": "Warehouse Wise Stock Balance", + "reserved stock": "Reserved Stock", + "item shortage": "Item Shortage Report", + "shortage report": "Item Shortage Report", + "available batch": "Available Batch Report", + "batch balance": "Batch-Wise Balance History", + "stock projected qty": "Stock Projected Qty", + "total stock summary": "Total Stock Summary", + "fifo": "FIFO Queue vs Qty After Transaction Comparison", + "fifo queue": "FIFO Queue vs Qty After Transaction Comparison", + "stock valuation": "Stock and Account Value Comparison", + "incorrect stock value": "Incorrect Stock Value Report", + "stock ledger variance": "Stock Ledger Variance", + "serial number status": "Serial No Status", + "serial no status": "Serial No Status", + "serial ledger": "Serial No Ledger", + "serial number ledger": "Serial No Ledger", + "available serial": "Available Serial No", + "available serial number": "Available Serial No", + "serial warranty": "Serial No Warranty Expiry", + "warranty expiry": "Serial No Warranty Expiry", + "serial service contract": "Serial No Service Contract Expiry", + "serial batch summary": "Serial and Batch Summary", + "incorrect serial batch": "Incorrect Serial and Batch Bundle", + "sales analytics": "Sales Analytics", + "sales analysis": "Sales Analytics", + "sales report": "Sales Analytics", + "sales summary": "Sales Analytics", + "sales trend": "Sales Invoice Trends", + "sales trends": "Sales Invoice Trends", + "sales invoice trends": "Sales Invoice Trends", + "sales order trends": "Sales Order Trends", + "sales register": "Sales Register", + "sales invoice register": "Sales Register", + "sales order analysis": "Sales Order Analysis", + "item sales": "Item-wise Sales Register", + "item wise sales": "Item-wise Sales Register", + "item sales register": "Item-wise Sales Register", + "item sales history": "Item-wise Sales History", + "sales payment": "Sales Payment Summary", + "sales payment summary": "Sales Payment Summary", + "sales partner commission": "Sales Partner Commission Summary", + "sales person commission": "Sales Person Commission Summary", + "sales person transaction": "Sales Person-wise Transaction Summary", + "purchase analytics": "Purchase Analytics", + "purchase analysis": "Purchase Analytics", + "purchase report": "Purchase Analytics", + "purchase summary": "Purchase Analytics", + "purchase trend": "Purchase Invoice Trends", + "purchase trends": "Purchase Invoice Trends", + "purchase invoice trends": "Purchase Invoice Trends", + "purchase order trends": "Purchase Order Trends", + "purchase receipt trends": "Purchase Receipt Trends", + "purchase register": "Purchase Register", + "purchase invoice register": "Purchase Register", + "purchase order analysis": "Purchase Order Analysis", + "item purchase": "Item-wise Purchase Register", + "item wise purchase": "Item-wise Purchase Register", + "item purchase register": "Item-wise Purchase Register", + "item purchase history": "Item-wise Purchase History", + "procurement tracker": "Procurement Tracker", + "supplier quotation comparison": "Supplier Quotation Comparison", + "gross profit": "Gross Profit", + "profit report": "Gross Profit", + "sales profit": "Gross Profit", + "margin report": "Gross Profit", + "gross and net profit": "Gross and Net Profit Report", + "net profit": "Gross and Net Profit Report", + "vat report": "VAT Report ZATCA on Sales & Purchase", + "zatca report": "Zatca Status Report", + "zatca status": "Zatca Status Report", + "vat audit": "VAT Audit Report", + "uae vat": "UAE VAT 201", + "tax withholding": "Tax Withholding Details", + "tds summary": "TDS Computation Summary", + "customer credit": "Customer Credit Balance", + "customer credit balance": "Customer Credit Balance", + "customer acquisition": "Customer Acquisition and Loyalty", + "customer loyalty": "Customer Acquisition and Loyalty", + "customer price": "Customer-wise Item Price", + "inactive customers": "Inactive Customers", + "lead details": "Lead Details", + "lead conversion": "Lead Conversion Time", + "sales pipeline": "Sales Pipeline Analytics", + "opportunity summary": "Opportunity Summary by Sales Stage", + "lost opportunity": "Lost Opportunity", + "lost quotations": "Lost Quotations", + "employee analytics": "Employee Analytics", + "employee report": "Employee Analytics", + "employee information": "Employee Information", + "employee leave": "Employee Leave Balance", + "leave balance": "Employee Leave Balance", + "leave ledger": "Leave Ledger", + "attendance sheet": "Monthly Attendance Sheet", + "monthly attendance": "Monthly Attendance Sheet", + "shift attendance": "Shift Attendance", + "employee birthday": "Employee Birthday", + "employee exits": "Employee Exits", + "project summary": "Project Summary", + "project report": "Project Summary", + "project profitability": "Project Profitability", + "project billing": "Project Billing Summary", + "employee billing": "Employee Billing Summary", + "timesheet summary": "Daily Timesheet Summary", + "daily timesheet": "Daily Timesheet Summary", + "employee hours": "Employee Hours Utilization Based On Timesheet", + "work order summary": "Work Order Summary", + "work order report": "Work Order Summary", + "open work orders": "Open Work Orders", + "completed work orders": "Completed Work Orders", + "work orders in progress": "Work Orders in Progress", + "production analytics": "Production Analytics", + "production report": "Production Analytics", + "production planning": "Production Planning Report", + "production plan": "Production Plan Summary", + "bom explorer": "BOM Explorer", + "bom stock": "BOM Stock Report", + "bom variance": "BOM Variance Report", + "work order materials": "Work Order Consumed Materials", + "process loss": "Process Loss Report", + "asset register": "Fixed Asset Register", + "fixed asset register": "Fixed Asset Register", + "asset depreciation": "Asset Depreciation Ledger", + "asset balance": "Asset Depreciations and Balances", + "asset activity": "Asset Activity", + "asset maintenance": "Asset Maintenance", + "issue summary": "Issue Summary", + "issue analytics": "Issue Analytics", + "support hours": "Support Hour Distribution", + "first response issues": "First Response Time for Issues", + "prepared report analytics": "Prepared Report Analytics", + "address contacts": "Addresses And Contacts", + "database storage": "Database Storage Usage By Tables", + "permitted documents": "Permitted Documents For User" +} \ No newline at end of file diff --git a/changai/changai/api/v2/auto_gen_api.py b/changai/changai/api/v2/auto_gen_api.py index ab51097..e939eef 100644 --- a/changai/changai/api/v2/auto_gen_api.py +++ b/changai/changai/api/v2/auto_gen_api.py @@ -63,7 +63,8 @@ def ensure_file_folder(folder_path: str, is_private: int = 1) -> str: current_path = next_path return current_path -@frappe.whitelist(allow_guest=False) + + def get_mod(app_names: list[str]): if isinstance(app_names, str): app_names = frappe.parse_json(app_names) @@ -275,8 +276,27 @@ def sync_master_data_smart() -> Dict[str, Any]: removed_total += len(removed_ids) for rec in live_records: - entity_id = rec.get(title_field) if title_field in rec else rec.get("name") - rebuilt_rows.append(_build_master_data_row(entity_type, entity_id,title_field)) + if mod == "Item": + item_code = rec.get("name") + if item_code: + rebuilt_rows.append( + _build_master_data_row( + entity_type, + item_code, + "name" + )) + item_name = rec.get(title_field) + if item_name: + rebuilt_rows.append( + _build_master_data_row( + entity_type, + item_name, + title_field + ) + ) + else: + entity_id = rec.get(title_field) if title_field in rec else rec.get("name") + rebuilt_rows.append(_build_master_data_row(entity_type, entity_id,title_field)) final_data = rebuilt_rows @@ -313,7 +333,7 @@ def _clean_schema_fields(by_table: Dict[str, Dict[str, Any]]) -> None: field.pop("join_hint", None) -@frappe.whitelist(allow_guest=False) + def get_doctypes_changed_since(last_sync: Optional[str]) -> List[str]: app_names=["erpnext","frappe"] erpnext_modules = get_mod(app_names) @@ -352,6 +372,7 @@ def get_doctypes_changed_since(last_sync: Optional[str]) -> List[str]: return results TABLES_JSON = "tables.json" YML_EXTENSIONS = (".yaml", ".yml") +REPORTS_JSON = "reports.json" def _normalize_schema_payload(payload: Any) -> tuple[Dict[str, Any], List[Dict[str, Any]]]: @@ -536,9 +557,10 @@ def _write_schema_outputs( by_table: Dict[str, Dict[str, Any]], current_tables: List[str], ) -> None: + reports = [] ordered_blocks = [by_table[t] for t in current_tables if t in by_table] final_tables = [block["table"] for block in ordered_blocks] - + reports = frappe.get_all("Report",fields=["name","report_name","ref_doctype"]) write_filedoctype( SCHEMA_YAML, {"_meta": meta, "tables": ordered_blocks}, @@ -549,6 +571,11 @@ def _write_schema_outputs( final_tables, folder=RAG_FOLDER, ) + write_filedoctype( + REPORTS_JSON, + reports, + folder=RAG_FOLDER, + ) @@ -567,7 +594,8 @@ def _process_schema_table(table: str, by_table: Dict[str, Dict[str, Any]]) -> bo frappe.clear_cache(doctype=dt) meta_dt = frappe.get_meta(dt) - + block = by_table.setdefault(table, {}) + block["is_table"] = bool(meta_dt.istable) existing_fields = _get_existing_fields_for_table(by_table, table) fields = _build_fields_from_meta(meta_dt, existing_fields) _update_or_create_table_block(by_table, table, fields) @@ -678,7 +706,7 @@ def sync_tables_and_schema_smart() -> Dict[str, Any]: changed_tables = {_tab(dt) for dt in changed_doctypes} missing_from_schema = {t for t in current_tables if t not in by_table} - tables_to_process =current_tables + tables_to_process = current_tables for table in tables_to_process: _process_schema_table(table, by_table) diff --git a/changai/changai/api/v2/build_cards_faiss_index_v2.py b/changai/changai/api/v2/build_cards_faiss_index_v2.py index f761773..881e032 100644 --- a/changai/changai/api/v2/build_cards_faiss_index_v2.py +++ b/changai/changai/api/v2/build_cards_faiss_index_v2.py @@ -31,11 +31,12 @@ def _get_fvs_paths() -> tuple: schema_path = os.path.join(app_base, "schema_fvs") schema_emb_path = os.path.join(app_base, "emb_dir") master_path = os.path.join(private_base, "masterdata_fvs") + report_path = os.path.join(app_base, "report_fvs") - for p in (app_base, private_base, table_path, schema_path, master_path): + for p in (app_base, private_base, table_path, schema_path, master_path, report_path): os.makedirs(p, exist_ok=True) - return app_base, private_base, table_path, schema_path, master_path,schema_emb_path + return app_base, private_base, table_path, schema_path, master_path, schema_emb_path, report_path RAG_FOLDER = "Home/RAG Sources" HNSW_M = 32 @@ -116,6 +117,26 @@ def _assert_dir_inside_base(dir_path: str, base_dir: str) -> Path: raise ValueError(f"Unsafe output dir (outside base): {d}") return d +def build_report_docs(report_list: List[Dict[str, Any]]) -> List[Document]: + """ + Build one Document per report name from reports.json. + reports.json is a flat list: ["Sales Invoice", "Purchase Order", ...] + """ + docs = [] + for report in report_list: + report_name = report.get("report_name") + ref_doctype = report.get("ref_doctype") + if not isinstance(report_name, str) or not report_name.strip(): + continue + docs.append(Document( + page_content=f"{report_name}", + metadata={ + "type": "report", + "report_name": report_name, + "ref_doctype": ref_doctype, + } + )) + return docs def build_table_docs(table_list: List[str]) -> List[Document]: """ @@ -361,13 +382,20 @@ def build_all_fvs() -> Dict[str, Any]: "message": "All 3 FVS build jobs have been queued. Check Error Logs for progress.", } - +@frappe.whitelist(allow_guest=False) def build_table_fvs_job(): try: - app_base, _, table_path, _, _,_ = _get_fvs_paths() + app_base, _, table_path, _, _,_, report_path = _get_fvs_paths() tables_list = _load_json_from_file_doc("tables.json") + reports_list = _load_json_from_file_doc("reports.json") table_docs = build_table_docs(tables_list) + try: + report_docs = build_report_docs(reports_list) + except Exception as e: + frappe.log_error(frappe.get_traceback(), "Build Report FVS Failed") + raise _build_and_save_faiss(table_docs, table_path, "ERPNext Table FVS", app_base) + _build_and_save_faiss(report_docs, report_path, "ERPNext Report FVS", app_base) frappe.logger().info(f"ERPNext Table FVS built: {len(table_docs)} docs") except Exception : frappe.log_error(frappe.get_traceback(), "Build Table FVS Failed") @@ -412,7 +440,7 @@ def build_schema_fvs_job(): schema = _load_yaml_from_file_doc("schema.yaml") # schema = clean_schema(schema,schema_path) schema_docs = build_schema_docs(schema) - app_base, _, _, schema_path, _,schema_emb_dir = _get_fvs_paths() + app_base, _, _, schema_path, _,schema_emb_dir, _ = _get_fvs_paths() # clean_schema(schema_path,schema_path) _build_and_save_faiss(schema_docs, schema_path, "ERPNext Schema FVS", app_base) save_field_matrix(schema_docs, schema_emb_dir) @@ -424,7 +452,7 @@ def build_schema_fvs_job(): def build_master_data_fvs_job(): try: - _, private_base, _, _, master_path,_ = _get_fvs_paths() + _, private_base, _, _, master_path,_, _ = _get_fvs_paths() master_data = _load_yaml_from_file_doc("master_data.yaml") entity_docs = build_entity_docs(master_data) _build_and_save_faiss(entity_docs, master_path, "ERPNext Master Data FVS", private_base) diff --git a/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_docs.pkl b/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_docs.pkl index f3d3d57..c180c65 100644 Binary files a/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_docs.pkl and b/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_docs.pkl differ diff --git a/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_embs.npy b/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_embs.npy index 99f91a6..f0fecdd 100644 Binary files a/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_embs.npy and b/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/field_embs.npy differ diff --git a/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/table_to_idx.pkl b/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/table_to_idx.pkl index f89d58c..9e0ce61 100644 Binary files a/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/table_to_idx.pkl and b/changai/changai/api/v2/fvs_stores/erpnext/emb_dir/table_to_idx.pkl differ diff --git a/changai/changai/api/v2/fvs_stores/erpnext/report_fvs/index.faiss b/changai/changai/api/v2/fvs_stores/erpnext/report_fvs/index.faiss new file mode 100644 index 0000000..9812c61 Binary files /dev/null and b/changai/changai/api/v2/fvs_stores/erpnext/report_fvs/index.faiss differ diff --git a/changai/changai/api/v2/fvs_stores/erpnext/report_fvs/index.pkl b/changai/changai/api/v2/fvs_stores/erpnext/report_fvs/index.pkl new file mode 100644 index 0000000..8945fd9 Binary files /dev/null and b/changai/changai/api/v2/fvs_stores/erpnext/report_fvs/index.pkl differ diff --git a/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.faiss b/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.faiss index b09e9be..88b1900 100644 Binary files a/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.faiss and b/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.faiss differ diff --git a/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.pkl b/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.pkl index d55fef1..18d1a15 100644 Binary files a/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.pkl and b/changai/changai/api/v2/fvs_stores/erpnext/schema_fvs/index.pkl differ diff --git a/changai/changai/api/v2/fvs_stores/erpnext/table_fvs/index.faiss b/changai/changai/api/v2/fvs_stores/erpnext/table_fvs/index.faiss index 7ac261a..3d1bb78 100644 Binary files a/changai/changai/api/v2/fvs_stores/erpnext/table_fvs/index.faiss and b/changai/changai/api/v2/fvs_stores/erpnext/table_fvs/index.faiss differ diff --git a/changai/changai/api/v2/schema_utils.py b/changai/changai/api/v2/schema_utils.py index fd5664c..ffa9856 100644 --- a/changai/changai/api/v2/schema_utils.py +++ b/changai/changai/api/v2/schema_utils.py @@ -11,16 +11,78 @@ from frappe.utils import getdate from frappe import _ from pathlib import Path +from collections import OrderedDict, defaultdict +_PHONETIC_BUCKETS = defaultdict(list) +import jellyfish +from rapidfuzz import fuzz, process +_VALUE_TO_FIELD = {} -def word_match(entity_word,values): + +def phonetic_bucket(): + global _PHONETIC_BUCKETS, _VALUE_TO_FIELD from changai.changai.api.v2.auto_gen_api import _read_filedoctype - from changai.changai.api.v2.text2sql_pipeline_v2 import is_erp_query master_data_content = _read_filedoctype("master_data.yaml") master_items = master_data_content["data"] - values = [item["filters"]["value"] for item in master_items] - response = is_erp_query(True, entity_word, values, 70) - return response + for item in master_items: + table = item["entity_type"] + field = item["filters"]["field"] + value = item["filters"]["value"] + _VALUE_TO_FIELD[value] = f"{table}.{field}:{value}" + first_word = value.split()[0] + key = jellyfish.metaphone(first_word) + _PHONETIC_BUCKETS[key].append(value) + + +@frappe.whitelist(allow_guest=False) +def phonetic_match(isreport: bool, word: str, threshold: int = 60): + global _PHONETIC_BUCKETS, _VALUE_TO_FIELD + + original_word = word + + candidates = [] + seen = set() + + phonetic_bucket() + + # check EVERY word in the query + for token in original_word.split(): + if len(token) <= 2: + continue + + key = jellyfish.metaphone(token) + + for value in _PHONETIC_BUCKETS.get(key, []): + if value not in seen: + seen.add(value) + candidates.append(value) + + if not candidates: + return { + "entity_labels": [], + "reason": "no phonetic candidates found" + } + + result = process.extract( + original_word, + candidates, + scorer=fuzz.WRatio, + limit=5, + score_cutoff=threshold + ) + + results = [] + + for match, score, _ in result: + label = _VALUE_TO_FIELD.get(match) + + if label: + results.append(label) + + return { + "entity_labels": results, + "reason": "phonetic match found" + } @@ -157,6 +219,49 @@ def validate_sql_schema(sql: str, dialect: str = "mysql") -> dict: "Account" ] + +def is_doctype_schema_changed(doc,last_sync): + doctype_modified = frappe.db.get_value( + "DocType", + doc, + "modified" + ) + custom_field_modified = frappe.db.get_value( + "Custom Field", + {"dt": doc}, + "max(modified)" + ) + property_setter_modified = frappe.db.get_value( + "Property Setter", + {"doc_type": doc}, + "max(modified)" + ) + latest = max( + [ + d for d in [ + doctype_modified, + custom_field_modified, + property_setter_modified + ] if d + ], + default=None + ) + if latest and last_sync and bool(getdate(latest) > getdate(last_sync)): + return True + return False + + +def is_master_data_changed(last_sync): + for doc in MASTER_DOCTYPES: + latest_modified = frappe.db.get_value( + doc, + {}, + "max(modified)" + ) + return bool(getdate(latest_modified) > getdate(last_sync)) if latest_modified and last_sync else False + return False + + @frappe.whitelist(allow_guest=False) def check_file_updates(file_name :str): settings = frappe.get_single("ChangAI Settings") @@ -169,35 +274,41 @@ def check_file_updates(file_name :str): if not last_sync: return { - "update_status": False, - "data": True, + "is_stale": False, + "data": False, "days": 0, "last_sync": None } if file_name == "schema.yaml": - changed = frappe.db.exists( - "DocType", - { - "modified": [">", last_sync] - } - ) - - elif file_name == "master_data.yaml": changed = False - for doc in MASTER_DOCTYPES: - if frappe.db.exists(doc, {"modified": [">", last_sync]}): + doctypes = frappe.db.get_all("DocType", {"istable": 0}, pluck="name") + for doc in doctypes: + if is_doctype_schema_changed(doc, last_sync): changed = True break - days = days_diff(today(), getdate(last_sync)) - return { - "update_status": not bool(changed), - "data": True, - "days": days, - "last_sync": last_sync - } + elif file_name == "master_data.yaml": + changed = False + if is_master_data_changed(last_sync): + changed = True + + days = days_diff(today(), getdate(last_sync)) + if changed == True: + return { + "is_stale": True, + "data": True, + "days": days, + "last_sync": last_sync + } + else: + return { + "is_stale":False, + "data": True, + "days": days, + "last_sync": last_sync + } @frappe.whitelist() @@ -273,9 +384,3 @@ def convert_yaml_schema_to_sqlglot_meta() -> dict: "ok": False, "message": str(e) } - -@frappe.whitelist(allow_guest=False) -def test(): - res=check_file_updates("master_data.yaml") - if not res.get("update_status"): - frappe.throw(_("Please update master data for entity recognition to work. Click on Update Master Data button in Training tab in ChangAI Settings.
Check Quick Start Guide Here 👇")) diff --git a/changai/changai/api/v2/text2sql_pipeline_v2.py b/changai/changai/api/v2/text2sql_pipeline_v2.py index 062e18a..cb74f89 100644 --- a/changai/changai/api/v2/text2sql_pipeline_v2.py +++ b/changai/changai/api/v2/text2sql_pipeline_v2.py @@ -39,7 +39,7 @@ save_turn_2, inject_prompt, ) -from changai.changai.api.v2.non_erp_handler import IntelligentStaticResponder +# from changai.changai.api.v2.non_erp_handler import IntelligentStaticResponder from huggingface_hub import snapshot_download from frappe.desk.reportview import build_match_conditions import shutil @@ -54,6 +54,7 @@ _FIELD_DOCS_CACHE = None _FIELD_EMBS_CACHE = None _TABLE_TO_IDX_CACHE = None +_VS_REPORT=None _KEYWORDS_SET=None _KEYWORDS_LIST=None ERPGULF_LINK = "https://app.erpgulf.com/en/products/chang-ai-an-ai-agent" @@ -77,7 +78,7 @@ SQL_REWRITE_PROMPT = """You are an ERP query rewriter and entity detector. Return ONLY valid JSON: -{{"standalone_question":"...","contains_values":true/false}} +{{"standalone_question":"...","contains_values":true/false,"entity_word":["..."]}} TASK 1 — FOLLOW-UP - If the query depends on previous messages, rewrite it as a complete standalone question. @@ -87,7 +88,8 @@ contains_values = TRUE: Any noun that refers to a specific named master record (item name, customer name, supplier name, warehouse name, employee name) If not sure, also set contains_values = TRUE, otherwise contains_values = FALSE. - +if contains_values = TRUE, then entity_word = the most relevant noun/entity name from the question and place it here and return only if contains_values is TRUE. +if multiple entites are present,place all of them in entity_word list. TASK 3 — ERP CONTEXTUAL REWRITE 1. Normalize: @@ -325,6 +327,7 @@ def read_asset(file_name: str, base: str = "assets") -> Any: {CHANGAI_GUIDE_LINK}""" MODEL_ID = "gemini-2.5-flash-lite" RETRY_LIMIT = 2 +REPORT_INTENT_MAP = read_asset("report_intent_map.json",base="assets") bk = read_asset("business_keywords_v1.json", base="assets") BUSINESS_KEYWORDS = bk.get("business_keywords", bk) @@ -1019,7 +1022,14 @@ def _safe_strip(v): # Shared State class SQLState(TypedDict, total=False): + filters:str entity_type_list:List[str] + create_entity:bool + open_report:bool + report_name:str + entity_name:str + doc:str + reports_filter_before_call:list entity_type:str final_prompt:str request_id: str @@ -1027,6 +1037,7 @@ class SQLState(TypedDict, total=False): session_id: str question: str contains_values: bool + entity_words:List[str] formatted_q: str hits: List[Any] context: str @@ -1046,6 +1057,19 @@ class SQLState(TypedDict, total=False): selected_tables: List[str] top_fields: Dict[str, Any] selected_fields: str + message:str + stop_followup:bool + +def route_action(state: SQLState) -> str: + if state.get("stop_followup"): + return "STOP_FOLLOW" + if state.get("create_entity"): + return "CREATE_ENTITY" + + if state.get("open_report"): + return "OPEN_REPORT" + + return "CONTINUE" def fill_sql_prompt(question: str, context: str) -> str: @@ -1133,7 +1157,6 @@ def is_erp_query(master_match:bool, q: str, words_list: list,cut_off_perc:int) - "matched_value": match, } - words = tokenize_mixed(q) for word in words: @@ -1190,7 +1213,8 @@ def send_non_erp_request(state: SQLState) -> SQLState: return {**state, "non_erp_res": "", "error": "No question provided"} # prompt = NON_ERP_PROMPT.format(question=qstn) try: - response = handle_non_erp_query(qstn) + # response = handle_non_erp_query(qstn) + response = non_erp_response(qstn) # response = call_model(prompt, "llm") if not response or not response.get("data"): return {**state,"non_erp_res": "", "error": str(response)} @@ -1205,6 +1229,15 @@ def _parse_rewrite_response(raw: Any, user_qstn: str) -> Tuple[str, bool]: standalone = "" contains_values = False obj = None + doc = None + entity_words = [] + stop_followup =False + entity_name = None + report_name = None + open_report = False + create_entity = False + report_intent = None + message=None if isinstance(raw, dict): obj = raw @@ -1219,23 +1252,42 @@ def _parse_rewrite_response(raw: Any, user_qstn: str) -> Tuple[str, bool]: if isinstance(obj, dict): standalone = (obj.get("standalone_question") or "").strip() or standalone contains_values = bool(obj.get("contains_values")) + entity_words = obj.get("entity_words") or [] if contains_values else [] + create_entity = bool(obj.get("create_entity")) + create_entity = obj.get("create_entity") if create_entity else False + if create_entity : + doc = obj.get("doctype") + entity_name = obj.get("entity_name") + open_report = bool(obj.get("open_report")) + if open_report: + report_name = obj.get("report_name") + report_intent = obj.get("report_intent") + stop_followup = bool(obj.get("stop_followup")) + if stop_followup: + message = obj.get("message") + elif isinstance(obj, list) and not standalone: standalone = json.dumps(obj) - return standalone or user_qstn.strip(), contains_values + return standalone or user_qstn.strip(), contains_values, entity_words,create_entity, doc,entity_name,report_name,open_report,report_intent,stop_followup,message SQL_REWRITE_SYS_PROMPT = read_asset("sql_rewrite_sys_prompt.txt", base="prompts") SQL_REWRITE_USER_PROMPT = read_asset("sql_rewrite_user_prompt.txt", base="prompts") def rewrite_question(state: SQLState) -> SQLState: + report_intent = None request_id = state.get("request_id") user_qstn = state.get("question") or "" session_id = state.get("session_id") + entity_words = [] sys_prompt = SQL_REWRITE_SYS_PROMPT prompt = inject_prompt(user_qstn, session_id) - + report_name_new=None try: raw = call_model(prompt, "llm",sys_prompt) - standalone, contains_values = _parse_rewrite_response(raw, user_qstn) + standalone, contains_values,entity_words,create_entity, doc,entity_name,report_name,open_report,report_intent,stop_followup,message = _parse_rewrite_response(raw, user_qstn) + if report_intent: + report_name_new = match_report_intent(report_intent) + publish_pipeline_update( request_id, @@ -1246,10 +1298,19 @@ def rewrite_question(state: SQLState) -> SQLState: return { **state, + "report_name":report_name_new or report_name or "", + "report_intent": report_intent, + "open_report":open_report, + "create_entity":create_entity, + "entity_name":entity_name if create_entity else None, + "doc":doc if create_entity else None, "formatted_q": standalone, "contains_values": contains_values, + "entity_words": entity_words, "formatting_prompt": prompt, "error": None, + "message":message if stop_followup else None, + "stop_followup": stop_followup } except frappe.exceptions.ValidationError: @@ -1266,38 +1327,50 @@ def rewrite_question(state: SQLState) -> SQLState: return {**state, "error": str(e)} -def get_table_vs(): - global _VS_TABLE +def get_vs(istable: bool): + global _VS_TABLE, _VS_REPORT - if _VS_TABLE is None: - emb = get_embedding_engine() - if emb is None: - frappe.throw(_(EMBEDDING_ENGINE_NONE_MESSG)) + emb = get_embedding_engine() + if emb is None: + frappe.throw(_(EMBEDDING_ENGINE_NONE_MESSG)) - # get app root dynamically - app_path = frappe.get_app_path("changai") + app_path = frappe.get_app_path("changai") - table_vs_path = os.path.join( - app_path, - "changai", - "api", - "v2", - "fvs_stores", - "erpnext", - "table_fvs" - ) + if istable: + if _VS_TABLE is None: + table_vs_path = os.path.join( + app_path, "changai", "api", "v2", + "fvs_stores", "erpnext", "table_fvs" + ) - if not os.path.exists(table_vs_path): - frappe.throw(_("FAISS table store not found at {0}\n" - "Check Quick Start Guide Here 👇:\n {1}").format(table_vs_path,CHANGAI_GUIDE_LINK)) + if not os.path.exists(table_vs_path): + frappe.throw(_("FAISS table store not found at {0}").format(table_vs_path)) - _VS_TABLE = FAISS.load_local( - table_vs_path, - emb, - allow_dangerous_deserialization=True - ) + _VS_TABLE = FAISS.load_local( + table_vs_path, + emb, + allow_dangerous_deserialization=True + ) + + return _VS_TABLE + + else: + if _VS_REPORT is None: + report_vs_path = os.path.join( + app_path, "changai", "api", "v2", + "fvs_stores", "erpnext", "report_fvs" + ) + + if not os.path.exists(report_vs_path): + frappe.throw(_("FAISS report store not found at {0}").format(report_vs_path)) - return _VS_TABLE + _VS_REPORT = FAISS.load_local( + report_vs_path, + emb, + allow_dangerous_deserialization=True + ) + + return _VS_REPORT @@ -1382,7 +1455,45 @@ def _get_cached_embedding(q: str, request_id: str) -> tuple: return tuple(vec) # tuple for hashability -def call_fvs_table_search(q: str, request_id: str) -> List[str]: +def create_entity(state:SQLState): + request_id = state.get("request_id") + res = call_fvs_table_search(True, state.get("formatted_q"), state.get("request_id")) + prompt = f"""You are selecting the correct ERPNext DocType for entity creation. +User query: +{state.get("formatted_q")} +Candidate DocTypes: +{res[:10]} +Rules: +- Choose only one DocType from the candidate list. +- Use only the given candidate DocTypes. +- Do not add the "tab" prefix. +- Return only valid JSON. +- Do not return explanations or extra text. +- If no suitable DocType is found, return {{"doctype": ""}}. +Output format: +{{"doctype": "chosen_doctype_name"}} + + """ + publish_pipeline_update( + request_id, + "Detecting doctype for creation", + "Detecting doctype for creation", + done=True +) + res = call_gemini(prompt,"") + try: + if isinstance(res, str): + res = res.replace("```json", "").replace("```", "").strip() + result = json.loads(res) + doctype = result.get("doctype", "") + return {**state,"doc": doctype} + except json.JSONDecodeError as e: + return {**state,"error":str(e)} + + + + +def call_fvs_table_search(get_table: bool, q: str, request_id: str) -> List[str]: # get cached embedding publish_pipeline_update( request_id, @@ -1397,7 +1508,7 @@ def call_fvs_table_search(q: str, request_id: str) -> List[str]: "q_vec_ready", _("q_vec_ready") ) - vs = get_table_vs() + vs = get_vs(get_table) publish_pipeline_update( request_id, "vs_ready", @@ -1416,7 +1527,7 @@ def call_fvs_table_search(q: str, request_id: str) -> List[str]: continue doc_id = vs.index_to_docstore_id[idx] doc = vs.docstore.search(doc_id) - t = doc.metadata.get("table") + t = doc.metadata.get("table") if get_table else doc.metadata.get("report_name") if t and t not in seen: seen.add(t) out.append(t) @@ -1447,7 +1558,7 @@ def build_hnsw_index(embeddings): def call_retrieve_multi_line(user_question: str, request_id: str) -> Dict[str, Any]: try: - top_tables = call_fvs_table_search(user_question, request_id) + top_tables = call_fvs_table_search(True, user_question, request_id) publish_pipeline_update( request_id, "table_retrieval_done", @@ -1517,6 +1628,7 @@ def call_fvs_field_search_global_k( d = docs[doc_i] meta = getattr(d, "metadata", {}) or {} + is_table = meta.get("is_table") table = meta.get("table") field = meta.get("field") or meta.get("name") @@ -1541,7 +1653,12 @@ def call_fvs_field_search_global_k( opts = meta["options"] if isinstance(opts, list): name += " {" + ", ".join(str(o) for o in opts[:5]) + "}" - grouped.setdefault(table, []).append(name) + grouped.setdefault(table, { + "is_table": is_table, + "fields": [] + }) + + grouped[table]["fields"].append(name) res = format_schema_context(grouped) # 🔥 final compact string @@ -1726,7 +1843,7 @@ def replace_block(match): return re.sub(pattern, replace_block, top_fields, count=1, flags=re.DOTALL) -def local_entity_embedder(q: str,state: SQLState = None) -> List[Dict[str, Any]]: +def local_entity_embedder(q: str) -> List[Dict[str, Any]]: hits = get_master_vs().similarity_search(q, k=20) out, seen = [], set() for h in hits: @@ -1747,7 +1864,7 @@ def local_entity_embedder(q: str,state: SQLState = None) -> List[Dict[str, Any]] return out -def call_entity_retriever(qstn: str,state: SQLState) -> Dict[str, Any]: +def call_entity_retriever(isreport: bool, qstn: str, state: Dict) -> Dict[str, Any]: config = ChangAIConfig.get() if config["REMOTE"] and config["llm"] == "QWEN3": response = remote_entity_embedder(qstn) @@ -1764,13 +1881,32 @@ def call_entity_retriever(qstn: str,state: SQLState) -> Dict[str, Any]: return {"raw": body, "cards": cards} else: - results = local_entity_embedder(qstn,state) - cards = [ - r.get("entity_label") - for r in results - if r.get("entity_label") - ] - return {"raw": results, "cards": cards} + from changai.changai.api.v2.schema_utils import phonetic_match + entity_words = state.get("entity_words") + cards = [] + debug=[] + if entity_words is None: + return {"cards":[]} + for word in entity_words: + result = phonetic_match(isreport, word) + labels = result.get("entity_labels") or [] + debug.append({ + "word": word, + "result": result, + "labels": labels + }) + for label in labels: + if isreport: + try: + table_field, _ = labels.split(":", 1) + table, field = table_field.split(".", 1) + doctype = table.removeprefix("tab") + state["doc"] = doctype + except Exception: + pass + if label and label not in cards: + cards.append(label) + return {"cards": cards} # # Node 5:Repair Loop :Simple prompt for one more try. @@ -1834,7 +1970,7 @@ def detect_specific_entities(state: SQLState) -> SQLState: "ERPGulf.com" ).format(settingsUrl, CHANGAI_GUIDE_LINK, ERPGULF_LINK)) - if not res.get("update_status") and res.get("days", 0) > 0: + if res.get("is_stale") and res.get("days", 0) > 0: frappe.throw(_( "Your master data is {0} days old. " "Because of this, results may not be accurate. " @@ -1846,11 +1982,11 @@ def detect_specific_entities(state: SQLState) -> SQLState: "ERPGulf.com" ).format(res.get("days"), settingsUrl, CHANGAI_GUIDE_LINK, ERPGULF_LINK)) - out = call_entity_retriever(q,state) + out = call_entity_retriever(False, q, state) return { **state, "entity_cards": out.get("cards") or [], - "entity_raw": out.get("raw"), + # "entity_raw": out.get("raw"), } except frappe.exceptions.ValidationError: raise @@ -2065,6 +2201,178 @@ def routeNonErpToAI(state: SQLState): return res + +def prepare_report_action(state: SQLState) -> SQLState: + report_name = None + q = state.get("formatted_q") or state.get("question") or "" + request_id = state.get("request_id") + report_name = state.get("report_name") + + cards = call_entity_retriever(True, q, state) if state.get("contains_values") else {"cards": []} + + # reports_listed = call_fvs_table_search(False, q, request_id) + doctype = state.get("doc") if state.get("doc") else None + result = [] + # for report in reports_listed[:30]: + # report_name = report.get("name") if isinstance(report, dict) else report + # result.append({ + # "report": report_name, + # "filters": get_report_filter_fields(report_name) + # }) + result.append({"report":report_name,"filters": get_report_filter_fields(report_name)}) + prompt = f""" +Given the user query: +{q} +Detected DocType: use this value only for filtering by party type. +{doctype} +Available Report and Filter Fields: +{result} +after seeing the reports look wisely at the question and find the intent that speaks of report name take that intent and match with listed reports +and find the best matching report name. +Carefully identify the report intent from the user's question and match only that intent against the available report names. Do not use entity names, entity types, party names, customer names, supplier names, or filter values to choose the report, even if similar words appear in the listed report names. Entity information must be used only for filters, not for report_name selection. +even if the right report name is not ranked top find it from the top 10 and use it . +Entity Cards: +{cards} +Report selection MUST be based on the user's requested report type first. +Entity type (Customer, Supplier, Employee, etc.) is only used for filters and MUST NOT determine the report name. +Examples: +User: "show account statement for nova supplier" +Report: General Ledger +Filters: +{{ + "party_type": "Supplier", + "party": "nova supplier" +}} +TASK +Select exactly ONE report from the Available Reports and Filter Fields. +Step 1 - Understand User Intent +- Analyze the user's intent and meaning carefully. +- Match reports by meaning and business purpose, not only exact words. +- Consider synonyms and common ERP terminology. +Examples: +- "account statement", "customer statement", "supplier statement", "ledger statement" → usually General Ledger when available. +- "profit report" → Gross Profit. +- "trial balance" → Trial Balance. +- "balance sheet" → Balance Sheet. +Step 2 - Select the Best Report +- report_name MUST be selected only from the provided report list. +- Never invent a report name. +- Never return an empty report name. +- Choose the report whose purpose best matches the user's request. +- If multiple reports are similar, select the one whose available filters best satisfy the user's request. +- Report selection is more important than filter selection. +- Do not choose a report simply because a filter matches. +Step 3 - Apply Filters +- Use ONLY filters that exist in the selected report. +- Never invent filter names. +- Never invent filter values. +- Use Entity Card values whenever applicable. +- Apply only relevant filters supported by the selected report. +Party Filtering Rules +If: +- detected DocType is Customer, Supplier, Employee, Shareholder, Student, Member, or any party-type entity +AND +- selected report contains both party_type and party filters +THEN: +- party_type = detected DocType +- party = entity value from Entity Card +Example: +DocType = Customer +Entity Card: +customer_name: مؤسسة الإبداع التجارية +Filters: +{{ + "party_type": "Customer", + "party": "مؤسسة الإبداع التجارية" +}} +Important: +- Never infer party_type from the entity value. +- Always use the detected DocType. +- Prefer party_type + party over name-based filters whenever both are available. +Date Rules +Whenever a report requires date filtering: +- Convert relative dates into explicit dates. +- Use DD-MM-YYYY format only. +- Never use natural language dates. +Date Format Rules: +- Always output dates in YYYY-MM-DD format. +- Never use DD-MM-YYYY, MM-DD-YYYY, or natural language dates. +- Convert all relative dates to YYYY-MM-DD before returning filters. +Validation Before Answering +Verify: +1. report_name exists in Available Reports. +2. Every filter exists in the selected report. +3. Every filter value comes from the user query, Entity Cards, or a valid date conversion. +4. No invented report names. +5. No invented filters. +6. No empty report_name. +7. Report intent matches the user's request. +Return ONLY valid JSON: +{{ + "report_name": "", + "filters": {{ + "": "" + }} +}} +**Always use party_type when it is avaible for filtering if filtering by party name like customer, supplier,item etc +STRICT OUTPUT +- Return only JSON. +- No markdown. +- No explanations. +- No comments. +- Response must start with {{ and end with }}. +""" + + response = call_model(prompt, "llm", "") + + raw_response = str(response or "").strip() + raw_response = raw_response.replace("```json", "").replace("```", "").strip() + + frappe.logger().info(f"prepare_report_action raw response: {repr(raw_response)}") + + if not raw_response: + response = {"report_name": "", "filters": {}} + else: + try: + response = json.loads(raw_response) + except json.JSONDecodeError: + frappe.log_error( + f"Invalid JSON from prepare_report_action:\n{raw_response}", + "prepare_report_action JSON Error" + ) + response = {"report_name": "", "filters": {}} + + if not isinstance(response, dict): + response = {"report_name": "", "filters": {}} + publish_pipeline_update( + request_id, + "Detected Report name & filters", + "Detected Report name & filters", + data={"report_name": response.get("report_name"),"filters":response.get("filters")}, + done=True + ) + return { + **state, + "report_name": response.get("report_name") or "", + "filters": response.get("filters") or {}, + "reports_filter_before_call":result[:30], + "entity_cards": cards.get("cards") or [], + "entity_raw": cards, + "error": None, + } + + +# def route_action(state: SQLState): +# if state.get("create_entity") is True: +# qstn = state.get("user_question") +# response = call_fvs_table_search(False, qstn) +# return response +# return "CREATE_ENTITY" +# if state.get("open_report") is True: +# return "OPEN_REPORT" +# else: +# return "CONTINUE" + # Building the Workflow Graph workflow=StateGraph(SQLState) workflow.add_node("rewrite_question",rewrite_question) @@ -2077,11 +2385,28 @@ def routeNonErpToAI(state: SQLState): workflow.add_node("repair_sql",repair_sqlquery) workflow.add_node("send_non_erp_request",send_non_erp_request) workflow.add_node("routeNonErpToAI",routeNonErpToAI) +workflow.add_node("prepare_report_action", prepare_report_action) +workflow.add_node("create_entity", create_entity) +# workflow.add_node("stop_follow_msg_api", stop_follow_msg_api) + + workflow.set_entry_point("guardrail_router") workflow.add_conditional_edges("guardrail_router",route_guardrail,{"ERP":"rewrite_question","NON_ERP":"routeNonErpToAI"}) # workflow.add_edge("guardrail_router", "rewrite_question") workflow.add_edge("routeNonErpToAI", END) -workflow.add_edge("rewrite_question", "retrieve") +workflow.add_conditional_edges( + "rewrite_question", + route_action, + { + "CREATE_ENTITY": "create_entity", + "OPEN_REPORT": "prepare_report_action", + "STOP_FOLLOW":END, + "CONTINUE": "retrieve", + } +) +workflow.add_edge("prepare_report_action", END) +workflow.add_edge("create_entity", END) +# workflow.add_edge("stop_follow_msg_api", END) workflow.add_edge("retrieve","detect_entities") workflow.add_conditional_edges("detect_entities", route_after_entities, {"CONTEXT":"build_context","DIRECT":"generate_sql"}) workflow.add_edge("build_context", "generate_sql") @@ -2175,11 +2500,16 @@ def save_logs( tries: Optional[int] = None, err: Any = None, formatted_result: Any = None, + tables:Any=None, + fields:Any=None, + entity_debug:Any=None, + type_=None ) -> str: def to_json_if_needed(v: Any) -> Any: if isinstance(v, (dict, list)): return json.dumps(v, default=str, ensure_ascii=False) return v + MAX_LOG_LEN = 140 doc = frappe.new_doc("ChangAI Logs") doc.user_question = user_question @@ -2192,11 +2522,18 @@ def to_json_if_needed(v: Any) -> Any: doc.error = to_json_if_needed(err) doc.result = to_json_if_needed(result) doc.formatted_result = to_json_if_needed(formatted_result) + doc.tables = to_json_if_needed(tables) + doc.fields = to_json_if_needed(fields) + doc.entity = to_json_if_needed(entity_debug) + doc.type = type_ doc.insert(ignore_permissions=True) return doc.name def format_data_conversationally(user_data: Any) -> str: + # Safe: CONVERSATION_TEMPLATE is a hardcoded internal template string. + # User SQL result is passed only as data context, not as template source. + # nosemgrep: frappe-semgrep-rules.rules.security.frappe-ssti return render_template( CONVERSATION_TEMPLATE, # nosemgrep: frappe-semgrep-rules.rules.security.frappe-ssti @@ -2577,7 +2914,7 @@ def debug_entity_retriever(q: str,state: SQLState): return { "query": q, "raw_response": resp, - "parsed_entity_cards": call_entity_retriever(q,state) + "parsed_entity_cards": call_entity_retriever(False, q,state) } @@ -2605,26 +2942,28 @@ def _invoke_pipeline(user_question: str, chat_id: str, request_id: str,sendNonEr return None, {"Bot": "⚠️ An unexpected error occurred. Please try again.", "error": str(e)} -def _handle_non_erp(final: SQLState, user_question: str, chat_id: str) -> Dict: - non_erp_res = _safe_strip(final.get("non_erp_res", "")) - formatted_q = _safe_strip(final.get("formatted_q", "")) - err = final.get("error") +def _handle_non_erp_(non_erp_res,formatted_q,err,user_question: str,request_id:str, chat_id: str) -> Dict: if not non_erp_res: if err: frappe.log_error(err, "ChangAI NON_ERP Error") + save_logs(user_question=user_question, formatted_q="Not formatted as its NONERP",err=err, result=non_erp_res,type_="NonERP") + return { "Question": user_question, "Formatted-Question": formatted_q, "Bot": err if err else "⚠️ Could not get a response. Please try again.", } - + if not err and non_erp_res: try: - save_turn_2(session_id=chat_id, user_text=user_question, bot_text=non_erp_res,type_="non_erp") - save_logs(user_question=user_question, formatted_q="Not formatted as its NONERP", result=non_erp_res) + publish_pipeline_update(request_id, "mapped to non-erp", "Mapped as NON-ERP") + save_turn_2(session_id=chat_id, user_text=formatted_q or user_question, bot_text=non_erp_res,type_="non_erp") + save_logs(user_question=user_question, formatted_q="Not formatted as its NONERP",err="None", result=non_erp_res,type_="NonERP") except Exception as e: frappe.log_error(f"Failed to save NON_ERP logs: {e}", "ChangAI Logs") + save_logs(user_question=user_question, formatted_q="Not formatted as its NONERP",err=str(e), result=non_erp_res,type_="NonERP") + return {"Question": user_question, "Formatted-Question": formatted_q, "Bot": non_erp_res} @@ -2653,47 +2992,103 @@ def _get_sql_error_message(err: Any, val: Dict) -> str: return f"⚠️ The model generated an invalid query. {error_text}" +def _handle_sql_result( + memory_status: Dict, + request_id: str, + sql_prompt: Optional[str], + final: Optional[Dict], + sql: str, + orm: Optional[str], + formatted_q: Optional[str], + fields: Optional[str], + selected_tables: Optional[List], + val: Optional[Dict], + entity_debug: Optional[Dict], + user_question: str, + chat_id: str +) -> Dict: + final = final or {} + val = val or {} + entity_debug = entity_debug or {} + selected_tables = selected_tables or [] + fields = fields or "" + formatted_q = formatted_q or user_question -def _handle_sql_result(memory_status: Dict, sql_prompt: str, final: SQLState, sql: str, orm: str, formatted_q: str, fields: str, - selected_tables: List, val: Dict, entity_debug: Dict, - user_question: str, chat_id: str) -> Dict: try: - request_id = final.get("request_id") - org_sql = final.get("sql") + request_id = request_id or final.get("request_id") + org_sql = final.get("sql") or sql extracted_tables = extract_tables_from_sql(sql) - sql_result = execute_query(sql, extracted_tables) - publish_pipeline_update( - request_id, - "sql_executed", - "Query executed" - ) + try: + sql_result = execute_query(sql, extracted_tables) + except Exception as e: + # err = str(e) + final["error"] = str(e) + + publish_pipeline_update(request_id, "sql_executed", "Query executed") + + entity_words = final.get("entity_words") or [] + except Exception as e: + final["error"] = str(e) return {"ok": False, "error": f"SQL Execution Failed: {e}"} - context = (final.get("context") or final.get("selected_fields") or "")[:800] - contains_values = final.get("contains_values") or "" + context = (final.get("context") or final.get("selected_fields") or fields or "")[:800] + contains_values = final.get("contains_values") or entity_debug.get("contains_values") or "" err = final.get("error") + formatted_result = format_data(user_question, sql_result) + publish_pipeline_update( - request_id, - "format_data_completed", - "Completed Formatting Result", - done=True -) + request_id, + "format_data_completed", + "Completed Formatting Result", + done=True + ) + if not err: try: - save_turn_2(session_id=chat_id, user_text=formatted_q, bot_text=formatted_result, type_="erp") - save_logs(user_question=user_question, formatted_q=formatted_q, context=context, - sql=sql, val=val, result=sql_result, formatted_result=formatted_result) + save_turn_2( + session_id=chat_id, + user_text=formatted_q, + bot_text=formatted_result, + type_="erp" + ) except Exception as e: - return {"error": str(e)} - + save_logs( + user_question=user_question, + formatted_q=formatted_q, + context=context, + sql=sql, + val=val, + err=str(e), + result=sql_result, + formatted_result=formatted_result, + tables=selected_tables, + fields=fields, + entity_debug=entity_debug, + type_="ERP" + ) + return {"ok": False, "error": str(e)} + save_logs( + user_question=user_question, + formatted_q=formatted_q, + context=context, + sql=sql, + val=val, + err=err if err else "", + result=sql_result, + formatted_result=formatted_result, + tables=selected_tables, + fields=fields, + entity_debug=entity_debug, + type_="ERP" + ) return { - "Model returned SQL":org_sql, - "context":context, - # "Memory Status":memory_status, + "Model returned SQL": org_sql, + "context": context, + "entity_words": entity_words, "Question": user_question, - "Formated Question":formatted_q, + "Formated Question": formatted_q, "Cleaned SQL": sql, "ORM": orm, "Tables": selected_tables, @@ -2701,10 +3096,11 @@ def _handle_sql_result(memory_status: Dict, sql_prompt: str, final: SQLState, sq "Entity Values present ?": contains_values, "Validation": val, "Error": err, - "result":sql_result, + "result": sql_result, "EntityDebug": entity_debug if entity_debug.get("contains_values") else None, "Bot": formatted_result, } + def retry_sql(sql, error, formatted_q, sql_prompt): retry_prompt = SQL_SYS_PROMPT + """ @@ -2803,76 +3199,43 @@ def is_thread_erp(q:str,chat_id:str): else: return False +from rapidfuzz import fuzz +@frappe.whitelist() +def find_similar_log_question(new_question:str, threshold: int = 90): + logs = frappe.get_all( + "ChangAI Logs", + fields=["name", "user_question", "sql_generated","rewritten_question","fields","tables","error","entity","result"], + limit_page_length=500 + ) + best_match = None + best_score = 0 + for log in logs: + score = fuzz.token_set_ratio(new_question, log.rewritten_question) -@frappe.whitelist(allow_guest=False) -def run_text2sql_pipeline(user_question: str, chat_id: str, request_id: str, sendNonErptoAI: bool = False) -> Dict: - memory_status = check_memory_status() - final, err_response = _invoke_pipeline(user_question, chat_id, request_id, sendNonErptoAI) - if err_response: - return err_response - - entity_debug = { - "contains_values": final.get("contains_values"), - "entity_cards": final.get("entity_cards") or [], - } - - if (final.get("query_type") or "NON_ERP") == "NON_ERP": - return _handle_non_erp(final, user_question, chat_id) - - sql = clean_sql(final.get("sql")) or "" - orm = clean_sql(final.get("orm") or "") - formatted_q = _safe_strip(final.get("formatted_q") or "") - selected_tables = final.get("selected_tables") or [] - fields = _safe_strip(final.get("selected_fields") or "") - sql_prompt = _safe_strip(final.get("sql_prompt") or "") - final_prompt = final.get("final_prompt") or "" - try: - context = final.get("context") - except Exception as e: - frappe.log_error(e, "Error occurred while fetching final values") - err = final.get("error") + if score > best_score: + best_score = score + best_match = log - # # # guard empty sql - # # # if not sql: - # # # return _error_response(memory_status, user_question, formatted_q, context, - # # # selected_tables, fields, sql, - # # # {"ok": False, "error": "SQL is empty"}, - # # # entity_debug, 0, "SQL not valid or missing", err) - # retried_sql1, retried_orm1, retry1_val_res = retry_sql(retried_sql, retry_val_res.get("error"), formatted_q, sql_prompt) - # if retry1_val_res.get("ok"): - # return _handle_sql_result(memory_status, sql_prompt, final, retried_sql1, retried_orm1, - # formatted_q, fields, selected_tables, retry1_val_res, - # entity_debug, user_question, chat_id) - res = validate_sql_schema(sql) - publish_pipeline_update(request_id, "sql_validated", _("SQL validation Completed")) - - # valid on first try - if res.get("ok") and sql.upper().startswith("SELECT"): - return _handle_sql_result(memory_status, sql_prompt, final, sql, orm, - formatted_q, fields, selected_tables, res, - entity_debug, user_question, chat_id) - - # retry 2 - retried_sql2, retried_orm2, retry2_val_res = retry_sql(sql, res.get("error"), formatted_q, sql_prompt) - if retry2_val_res.get("ok"): - return _handle_sql_result(memory_status, sql_prompt, final, retried_sql2, retried_orm2, - formatted_q, fields, selected_tables, retry2_val_res, - entity_debug, user_question, chat_id) - - # retry 3 - retried_sql3, retried_orm3, retry3_val_res = retry_sql(retried_sql2, retry2_val_res.get("error"), formatted_q, sql_prompt) - if retry3_val_res.get("ok"): - return _handle_sql_result(memory_status, sql_prompt, final, retried_sql3, retried_orm3, - formatted_q, fields, selected_tables, retry3_val_res, - entity_debug, user_question, chat_id) - - # all retries failed - final_error = retry2_val_res.get("error") or retry1_val_res.get("error") or retry3_val_res.get("error") or res.get("error") or "SQL not valid or missing" - return _error_response(memory_status, user_question, formatted_q, context, - selected_tables, fields, retried_sql2 or sql, - retry2_val_res, entity_debug, 2, final_error, err) + if best_score >= threshold: + return { + "matched": True, + "score": best_score, + "log_name": best_match.name, + "question": best_match.user_question, + "sql": best_match.sql_generated, + "rewritten_question":best_match.rewritten_question, + "fields":best_match.fields, + "tables":best_match.tables, + "entity_debug":best_match.entity, + "result":best_match.result, + "error":best_match.error + } + return { + "matched": False, + "score": best_score + } def _error_response(memory_status, user_question, formatted_q, context, selected_tables, fields, sql, validation, @@ -2921,9 +3284,9 @@ def load_on_startup(): message=f"PID={os.getpid()} | module={__name__} | file={__file__} | loaded={_EMBEDDER_INSTANCE is not None} | id={id(_EMBEDDER_INSTANCE)}" try: - # get_symspell() + load_non_erp_data() get_embedding_engine() - get_table_vs() + get_vs() load_field_matrix() gemini_client() get_master_vs() @@ -2987,3 +3350,234 @@ def get_embedding_engine_test(): "load_time": time.time() - t3, "result": "loaded_now" } + + +_NON_ERP_DATA = None +_NON_ERP_QUESTIONS = None +_NON_ERP_RESPONSE_MAP = None + + +def load_non_erp_data(): + global _NON_ERP_DATA, _NON_ERP_QUESTIONS, _NON_ERP_RESPONSE_MAP + + if _NON_ERP_DATA is not None: + return _NON_ERP_QUESTIONS, _NON_ERP_RESPONSE_MAP + try: + _NON_ERP_DATA = read_asset("non_erp_combined.processed.json") + except Exception as e: + frappe.log_error(f"Failed to load NON-ERP data: {e}", "ChangAI NON-ERP Data Load Error") + _NON_ERP_DATA = [] + + _NON_ERP_QUESTIONS = [] + _NON_ERP_RESPONSE_MAP = {} + + for item in _NON_ERP_DATA: + q = item.get("user_input") + if not q: + continue + + _NON_ERP_QUESTIONS.append(q) + _NON_ERP_RESPONSE_MAP[q] = item.get("response") + + return _NON_ERP_QUESTIONS, _NON_ERP_RESPONSE_MAP + + +def non_erp_response(non_erp_q: str) -> Optional[str]: + questions, response_map = load_non_erp_data() + result = process.extractOne( + non_erp_q, + questions, + scorer=fuzz.WRatio, + score_cutoff=65 + ) + if not result: + return {"data":"Hey Iam ChangAI from ERPGulf,iam here to help you with your queries..."} + matched_q = result[0] + return {"data": response_map.get(matched_q, "Hey Iam ChangAI from ERPGulf,iam here to help you with your queries...")} + + +@frappe.whitelist(allow_guest=False) +def run_text2sql_pipeline(user_question: str, chat_id: str, request_id: str, sendNonErptoAI: bool = False) -> Dict: + memory_status = check_memory_status() + logs = find_similar_log_question(user_question) + if logs.get("matched") and logs["error"] == "" and logs.get("type") != "NonERP": + publish_pipeline_update(request_id, "cache_hit", "Using cached result") + # return True,logs + # if logs.get("rewritten_question") == "Not formatted as its NONERP": + # return _handle_non_erp_(logs.get("result"),logs.get("rewritten_question"),logs.get("error"), user_question, chat_id) + formatted_q = logs.get("rewritten_question") + sql = logs.get("sql") + tables = json.loads(logs.get("tables") or "[]") + fields =logs.get("fields") or "" + entity_debug = json.loads(logs.get("entity_debug") or "{}") + return _handle_sql_result( + memory_status, + request_id, + None, + {}, + sql, + None, + formatted_q, + fields, + tables, + {"ok": True, "from_cache": True}, + entity_debug, + user_question, + chat_id +) + else: + final, err_response = _invoke_pipeline(user_question, chat_id, request_id, sendNonErptoAI) + if err_response: + return err_response + + entity_debug = { + "contains_values": final.get("contains_values"), + "entity_cards": final.get("entity_cards") or [], + } + + if (final.get("query_type") or "NON_ERP") == "NON_ERP": + non_erp_res = _safe_strip(final.get("non_erp_res", "")) + formatted_q = _safe_strip(final.get("formatted_q", "")) + err = final.get("error") + return _handle_non_erp_(non_erp_res,formatted_q,err, user_question,request_id, chat_id) + + sql = clean_sql(final.get("sql")) or "" + orm = clean_sql(final.get("orm") or "") + formatted_q = _safe_strip(final.get("formatted_q") or "") + if final.get("create_entity") is True: + return { + "create_entity":True, + "doc": final.get("doc"), + "entity_name": final.get("entity_name") + } + if final.get("open_report") is True: + return { + "open_report": True, + "report_name": final.get("report_name"), + "filters": final["filters"], + "reports_filter_before_call": final.get("reports_filter_before_call"), + "entity_raw": final.get("entity_raw"), + "question_rewritten": formatted_q + } + if final.get("stop_followup"): + save_turn_2(session_id=chat_id, user_text=user_question, bot_text=final.get("message"),type_="non_erp") + save_logs( + user_question=user_question, + formatted_q=None, + context=None, + sql=None, + val=None, + err=err if err else "", + result=None, + formatted_result=final.get("message"), + tables=None, + fields=None, + entity_debug=None, + type="NonERP" + ) + publish_pipeline_update( + request_id, + "Stop follow-up detected", + "Stop follow-up detected", + data={"message": final.get("message")}, + done=True +) + return { + "Model returned SQL": None, + "context": None, + "entity_words": None, + "Question": user_question, + "Formated Question": formatted_q, + "Cleaned SQL": None, + "stop_followup": True, + "ORM": None, + "Tables": None, + "Fields": None, + "Entity Values present ?": None, + "Validation": None, + "Error": err, + "result": fNone, + "EntityDebug": None, + "Bot": final.get("message"), + } + selected_tables = final.get("selected_tables") or [] + fields = _safe_strip(final.get("selected_fields") or "") + sql_prompt = _safe_strip(final.get("sql_prompt") or "") + final_prompt = final.get("final_prompt") or "" + entity_words=final.get("entity_words") or [] + try: + context = final.get("context") + except Exception as e: + frappe.log_error(e, "Error occurred while fetching final values") + err = final.get("error") + + # # # guard empty sql + # # # if not sql: + # # # return _error_response(memory_status, user_question, formatted_q, context, + # # # selected_tables, fields, sql, + # # # {"ok": False, "error": "SQL is empty"}, + # # # entity_debug, 0, "SQL not valid or missing", err) + # retried_sql1, retried_orm1, retry1_val_res = retry_sql(retried_sql, retry_val_res.get("error"), formatted_q, sql_prompt) + # if retry1_val_res.get("ok"): + # return _handle_sql_result(memory_status,request_id, sql_prompt, final, retried_sql1, retried_orm1, + # formatted_q, fields, selected_tables, retry1_val_res, + # entity_debug, user_question, chat_id) + res = validate_sql_schema(sql) + publish_pipeline_update(request_id, "sql_validated", _("SQL validation Completed")) + + # valid on first try + if res.get("ok") and sql.upper().startswith("SELECT"): + return _handle_sql_result(memory_status,request_id, sql_prompt, final, sql, orm, + formatted_q, fields, selected_tables, res, + entity_debug, user_question, chat_id) + + # retry 2 + retried_sql2, retried_orm2, retry2_val_res = retry_sql(sql, res.get("error"), formatted_q, sql_prompt) + if retry2_val_res.get("ok"): + return _handle_sql_result(memory_status,request_id, sql_prompt, final, retried_sql2, retried_orm2, + formatted_q, fields, selected_tables, retry2_val_res, + entity_debug, user_question, chat_id) + + # retry 3 + retried_sql3, retried_orm3, retry3_val_res = retry_sql(retried_sql2, retry2_val_res.get("error"), formatted_q, sql_prompt) + if retry3_val_res.get("ok"): + return _handle_sql_result(memory_status,request_id, sql_prompt, final, retried_sql3, retried_orm3, + formatted_q, fields, selected_tables, retry3_val_res, + entity_debug, user_question, chat_id) + + # all retries failed + final_error = retry2_val_res.get("error") or retry3_val_res.get("error") or res.get("error") or "SQL not valid or missing" + return _error_response(memory_status, user_question, formatted_q, context, + selected_tables, fields, retried_sql2 or sql, + retry2_val_res, entity_debug, 2, final_error, err) + +from frappe.desk.query_report import get_script +def get_report_filter_fields(report_name: str): + try: + script = get_script(report_name).get("script") or "" + except Exception: + return [] + + fieldnames = re.findall( + r'fieldname\s*:\s*["\']([^"\']+)["\']', + script + ) + + return "|".join(dict.fromkeys(fieldnames)) + + +def match_report_intent(report_intent: str): + choices = list(REPORT_INTENT_MAP.keys()) + match = process.extractOne( + report_intent.lower(), + choices, + scorer=fuzz.WRatio, + score_cutoff=75 + ) + if not match: + return "" + + matched_intent = match[0] + return REPORT_INTENT_MAP[matched_intent] + + diff --git a/changai/changai/doctype/changai_logs/changai_logs.json b/changai/changai/doctype/changai_logs/changai_logs.json index e13675d..aece98c 100644 --- a/changai/changai/doctype/changai_logs/changai_logs.json +++ b/changai/changai/doctype/changai_logs/changai_logs.json @@ -14,7 +14,11 @@ "validation_and_error_section", "error", "validation", - "tries" + "tries", + "fields", + "tables", + "entity", + "type" ], "fields": [ { @@ -66,12 +70,33 @@ "fieldname": "tries", "fieldtype": "Data", "label": "Tries" + }, + { + "fieldname": "fields", + "fieldtype": "Long Text", + "label": "Fields" + }, + { + "fieldname": "tables", + "fieldtype": "Long Text", + "label": "Tables" + }, + { + "fieldname": "entity", + "fieldtype": "Long Text", + "label": "Entity" + }, + { + "fieldname": "type", + "fieldtype": "Select", + "label": "Type", + "options": "ERP\nNonERP" } ], "grid_page_length": 50, "index_web_pages_for_search": 1, "links": [], - "modified": "2026-03-05 08:37:32.434521", + "modified": "2026-06-04 12:40:18.522183", "modified_by": "Administrator", "module": "Changai", "name": "ChangAI Logs", diff --git a/changai/changai/doctype/changai_logs/test_changai_logs.py b/changai/changai/doctype/changai_logs/test_changai_logs.py new file mode 100644 index 0000000..021ab4c --- /dev/null +++ b/changai/changai/doctype/changai_logs/test_changai_logs.py @@ -0,0 +1,9 @@ +# Copyright (c) 2026, ERpGulf and Contributors +# See license.txt + +# import frappe +from frappe.tests.utils import FrappeTestCase + + +class TestChangAILogs(FrappeTestCase): + pass diff --git a/changai/changai/doctype/changai_settings/changai_settings.js b/changai/changai/doctype/changai_settings/changai_settings.js index e27147e..7088c74 100644 --- a/changai/changai/doctype/changai_settings/changai_settings.js +++ b/changai/changai/doctype/changai_settings/changai_settings.js @@ -278,7 +278,7 @@ async function check_updates(file_name) { file_name: file_name } }); - const update = r.message?.update_status; + const is_stale = r.message?.is_stale; const data = r.message?.data; const days = r.message?.days ?? 0; const last_sync = r.message?.last_sync; @@ -288,7 +288,7 @@ async function check_updates(file_name) { let badge_text = "Unknown"; - if (update === false) { + if (is_stale === true) { if (days > 1) { badge_class = "badge-yellow"; badge_text = `${formatted_date}` @@ -299,7 +299,7 @@ async function check_updates(file_name) { } } - if (update === true) { + if (is_stale === false) { if (data) { badge_class = "badge-green"; badge_text = `${formatted_date}` diff --git a/changai/changai/prompts/sql_rewrite_sys_prompt.txt b/changai/changai/prompts/sql_rewrite_sys_prompt.txt index c21a877..44bf6f9 100644 --- a/changai/changai/prompts/sql_rewrite_sys_prompt.txt +++ b/changai/changai/prompts/sql_rewrite_sys_prompt.txt @@ -1,18 +1,48 @@ You are an ERP query rewriter and entity detector. Return ONLY valid JSON: -{{"standalone_question":"...","contains_values":true/false}} +{{"standalone_question":"...","contains_values":true/false,"entity_words":["..."]}} TASK 1 — FOLLOW-UP - Analyze the last user message and last AI reply together. - If the last AI reply ended with a question and the user message is a reply to it, rewrite using the AI’s last question intent. -- If the query depends on chat history, rewrite it as a complete standalone question by analysing the chat history . -- Otherwise keep it unchanged. - +- If the query depends on chat history, rewrite it as a complete standalone question by analysing the chat history . - Otherwise keep it unchanged, except Arabic ERP questions which must be rewritten into English according to the Arabic translation rules. +TASK 1.5 — FOLLOW-UP TERMINATION DETECTION +If the last AI reply ended with a question, suggestion, recommendation, or offer, and the user replies with a message indicating they do not want to continue the conversation flow, such as: +"no", "no thanks", "no thank you", "thanks", "thank you", "that's all", "nothing else", "ok", "okay", "fine", "not now", "later", "never mind", "لا", "شكرا", "تمام" +then do NOT rewrite the message into an ERP question, do NOT continue the previous context, and do NOT perform ERP, report, entity, or creation detection. +Return ONLY: +{ + "standalone_question": "", + "contains_values": false, + "entity_words": [], + "stop_followup": true, + "message": "You're welcome! Let me know if you need anything else." +} +If the user replies positively to the AI's last question or suggestion, such as: +"yes", "yes please", "sure", "go ahead", "continue", "show me", "proceed", "ok show me", "نعم" +then continue with the normal follow-up rewriting rules and return: +{ + "standalone_question": "", + "contains_values": "", + "stop_followup": false, + "message":"", + "entity_words": [], +} TASK 2 — ENTITY DETECTION contains_values = TRUE: Any noun that refers to a specific named master record (item name, customer name, supplier name, warehouse name, employee name) If not sure, also set contains_values = TRUE, otherwise contains_values = FALSE. +contains_values = TRUE if question mentions any specific named record +(person name, item name, item code, supplier, warehouse, employee) +if contains_values = TRUE: +- entity_word = ONLY specific names or codes the user mentioned +- NEVER include generic words like "customer", "item", "supplier" +- if none, return empty list [] +EXAMPLES: +"sales for Amrin and Susan" → ["Amrin", "Susan"] +"stock of ITEM-0001 and iPhone" → ["ITEM-0001", "iPhone"] +"show all customers" → contains_values: false, entity_word: [] TASK 3 — ERP CONTEXTUAL REWRITE @@ -80,4 +110,91 @@ STRICT RULES: - If the query is ambiguous, ask for clarification and set "clarify": true. - this is very important.Do not map user intent to non-existent fields. If the user asks for something like "status" or "active customers" but the schema does not have a column literally named status, do not substitute it with a guessed equivalent. Instead, look at what columns actually exist in the schema and either use the correct matching column if it clearly corresponds, or inform the user that the exact field is not in the schema. - Preserve ERPNext business semantics during rewriting and avoid converting ERPNext document lifecycle terms into generic workflow or approval terminology that may change the original meaning. -- if the user question is in Arabic translate and rewrite into English ERPNext questions, preserve the original ERP business meaning and document lifecycle semantics in english. \ No newline at end of file +- Note ** - If the user question is in Arabic, you MUST rewrite the question in English but entity values must be in the language that user mentioned in the question if the entty values are mentioned in arabic preserve arabic only for entity values remaining part u can translate into english. + +Example: +Input: +اعرض تقرير سجل المخزون للصنف شاشة سامسونج +Detected entity: +شاشة سامسونج +Output: +Show the Stock Ledger report for Item شاشة سامسونج +entity_words: +["شاشة سامسونج"] +- Never keep an Arabic ERP question unchanged. +- Keep entity values exactly as provided by the user. +- When storing entity_words, preserve the original language used by the user. +If the user question is requesting entity creation (for example: "create customer", "create a supplier named ABC", "add a new item mobile phone") +return only this : +if the user mentioned the entity name for any doctype in question for creation then you must add it in the entity name . +{{"create_entity": true, "entity_name": ""}} +if the user is asking to view a report +Open ERPNext report when the user is asking for a specific ERP report, ledger, statement, balance, or aging view. + +Examples: +- Show account statement for Abdulla +→ Open Report (General Ledger / Customer Statement) +- Open Trial Balance for this year +→ Open Report +- Show Stock Ledger for Samsung Screen +→ Open Report +- Show Accounts Receivable for Customer ABC +→ Open Report +- Open Gross Profit report +→ Open Report +- Show FIFO report +→ Open Report +if the question comes similar to this then set open_report = True and set contains value true if the question contain any enitty values. +If open_report = true, extract the report intent phrase from the user question. +The report intent phrase should represent the business reporting request and should not contain customer names, supplier names, item names, dates, quantities, or filter values. +Examples: +"Show the account statement for Customer مؤسسة الإبداع التجارية" +→ "account statement" +"Can I get Abdulla's statement?" +→ "statement" +"Need stock ledger for Samsung Screen" +→ "stock ledger" +"trial bal this yr" +→ "trial balance" +"show me ar aging for customer abc" +→ "accounts receivable aging" +"fifo report for main warehouse" +→ "fifo" +If open_report = false, return an empty report_intent. +if entity values in question add them into entity words list like below . +and return +{{ + "standalone_question":"rewritten question here", + "open_report":True, + "report_name":"General Ledger", + "contains_values":True, + "entity_words":["abdulla"], + "report_intent": "" + +}} +otherwise if question is like + the user is asking for analysis, summary, trends, top records, totals, comparisons, or custom reporting, generate SQL and show the results in ChangAI. + +Other Examples: +- Show sales report this month +- Give me a monthly sales summary for last year +- Show top 10 customers by sales +- Show supplier-wise purchase report +then you just return the {{"standalone_question":"...","contains_values":true/false,"entity_words":["..."]}} +- Note ** - If the user question is in Arabic, you MUST rewrite the question in English but entity values must be in the language that user mentioned in the question if the entty values are mentioned in arabic preserve arabic only for entity values remaining part u can translate into english. +important : if the question is arabic rewrite whole question to english except the entity names. +Rules: +- If the user mentions one or more specific entity names, set contains_values=true. +- Every specific entity name from the question must be added to entity_words. +- If contains_values=true, entity_words cannot be []. +- For two customer names, include both names. +- standalone_question must be always be in english even if the user question is in english.that is very important. +If the request is not a creation request, return the normal output with whatever comes in there {{"standalone_question":"...","contains_values":true/false,"entity_words":["..."]}} +- Return ONLY valid JSON. +- Do NOT return markdown. +- Do NOT wrap the response in ```json blocks. +- Do NOT include explanations, notes, comments, or reasoning. +- The response must start with '{' and end with '}'. +- All keys and string values must use double quotes. +- Never return text before or after the JSON. + diff --git a/changai/changai/prompts/sql_system_prompt.txt b/changai/changai/prompts/sql_system_prompt.txt index 012f39f..03359a7 100644 --- a/changai/changai/prompts/sql_system_prompt.txt +++ b/changai/changai/prompts/sql_system_prompt.txt @@ -114,10 +114,14 @@ NEVER return empty sql. Always generate the best possible perfect SELECT query u - Output ONLY raw JSON. No explanation. No markdown. No extra keys. Never ever give empty sql.that is wrong.also donot give syntax errors in sql. also do not assume fields or tables if they are not in the given schema. +also Apply docstatus = 1 only for submitted transactional ERP documents such as Sales Invoice, Purchase Invoice, Sales Order, Purchase Order, Payment Entry, Journal Entry, Delivery Note, Purchase Receipt, Stock Entry, Work Order, and similar transaction records. +Do NOT apply docstatus filters to master data documents such as Customer, Supplier, Item, Employee, Warehouse, Project, Lead, Opportunity, Address, Contact, Company, Territory, Country, Currency, UOM, Cost Center, Department, and other master records unless the user explicitly asks for Draft, Submitted, or Cancelled records. - Output Format: { "sql": "", "orm": "" } FINAL CHECK: Did you verify every field exists in SCHEMA CONTEXT? +Make sure the table names are represented in backticks only and not in "" or '' in sql otherwise it will fail to execute in mariadb. +for Main table no need to take the fields like parent.for child table u can consider those . If sql is empty → you have failed. Output best partial query instead. diff --git a/changai/changai/prompts/sql_user_prompt.txt b/changai/changai/prompts/sql_user_prompt.txt index 6ba79c9..5bdbfdb 100644 --- a/changai/changai/prompts/sql_user_prompt.txt +++ b/changai/changai/prompts/sql_user_prompt.txt @@ -7,7 +7,7 @@ When generating SQL for entity retrieval, you MUST use the exact field name and Do not use the raw user text or replace the field name with another field like `name`. SCHEMA CONTEXT: {context} GENERIC FIELDS (available on ALL transaction doctypes): -name, creation, modified, owner, company, docstatus, naming_series, amended_from +name, creation, modified, owner, company, docstatus, naming_series, amended_from. GENERIC FIELDS (available on ALL master doctypes): name, creation, modified, owner, disabled, naming_series -REMINDER: Use only fields from SCHEMA CONTEXT. +REMINDER: Use only fields from SCHEMA CONTEXT.and never ever use a field or a table that is not in the given schema. diff --git a/changai/changai/replicate_model_files/changai_retriever/.cog/tmp/build20251119120842.983667/requirements.txt b/changai/changai/replicate_model_files/changai_retriever/.cog/tmp/build20251119120842.983667/requirements.txt index 07f72be..00ccb89 100644 --- a/changai/changai/replicate_model_files/changai_retriever/.cog/tmp/build20251119120842.983667/requirements.txt +++ b/changai/changai/replicate_model_files/changai_retriever/.cog/tmp/build20251119120842.983667/requirements.txt @@ -1,5 +1,5 @@ --extra-index-url https://download.pytorch.org/whl/cpu -torch==2.3.1 +torch>=2.8.0 faiss-cpu==1.8.0 numpy==1.26.4 sentence-transformers>=2.6.0 diff --git a/changai/public/dist/changai-chatbot.js b/changai/public/dist/changai-chatbot.js index ab89094..60ea2d3 100644 --- a/changai/public/dist/changai-chatbot.js +++ b/changai/public/dist/changai-chatbot.js @@ -1,53 +1,53 @@ -var vp=Object.defineProperty;var _p=(Pt,se,pt)=>se in Pt?vp(Pt,se,{enumerable:!0,configurable:!0,writable:!0,value:pt}):Pt[se]=pt;var we=(Pt,se,pt)=>_p(Pt,typeof se!="symbol"?se+"":se,pt);(function(){"use strict";var Ns;function Pt(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const se={},pt=[],Qt=()=>{},Dl=()=>!1,es=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Bs=e=>e.startsWith("onUpdate:"),ht=Object.assign,ei=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},Nl=Object.prototype.hasOwnProperty,ge=(e,t)=>Nl.call(e,t),Q=Array.isArray,pn=e=>ts(e)==="[object Map]",ti=e=>ts(e)==="[object Set]",be=e=>typeof e=="function",Ce=e=>typeof e=="string",zt=e=>typeof e=="symbol",Ae=e=>e!==null&&typeof e=="object",ni=e=>(Ae(e)||be(e))&&be(e.then)&&be(e.catch),si=Object.prototype.toString,ts=e=>si.call(e),Fl=e=>ts(e).slice(8,-1),ri=e=>ts(e)==="[object Object]",Hs=e=>Ce(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,Cn=Pt(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),ns=e=>{const t=Object.create(null);return n=>t[n]||(t[n]=e(n))},Bl=/-(\w)/g,Ut=ns(e=>e.replace(Bl,(t,n)=>n?n.toUpperCase():"")),Hl=/\B([A-Z])/g,Jt=ns(e=>e.replace(Hl,"-$1").toLowerCase()),ii=ns(e=>e.charAt(0).toUpperCase()+e.slice(1)),zs=ns(e=>e?`on${ii(e)}`:""),jt=(e,t)=>!Object.is(e,t),ss=(e,...t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:s,value:n})},js=e=>{const t=parseFloat(e);return isNaN(t)?e:t},zl=e=>{const t=Ce(e)?Number(e):NaN;return isNaN(t)?e:t};let oi;const rs=()=>oi||(oi=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"?window:typeof global!="undefined"?global:{});function Vs(e){if(Q(e)){const t={};for(let n=0;n{if(n){const s=n.split(jl);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function ye(e){let t="";if(Ce(e))t=e;else if(Q(e))for(let n=0;n!!(e&&e.__v_isRef===!0),Qe=e=>Ce(e)?e:e==null?"":Q(e)||Ae(e)&&(e.toString===si||!be(e.toString))?ai(e)?Qe(e.value):JSON.stringify(e,ui,2):String(e),ui=(e,t)=>ai(t)?ui(e,t.value):pn(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,r],i)=>(n[qs(s,i)+" =>"]=r,n),{})}:ti(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>qs(n))}:zt(t)?qs(t):Ae(t)&&!Q(t)&&!ri(t)?String(t):t,qs=(e,t="")=>{var n;return zt(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};let Je;class Gl{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=Je,!t&&Je&&(this.index=(Je.scopes||(Je.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t0&&--this._on===0&&(Je=this.prevScope,this.prevScope=void 0)}stop(t){if(this._active){this._active=!1;let n,s;for(n=0,s=this.effects.length;n0)return;if(In){let t=In;for(In=void 0;t;){const n=t.next;t.next=void 0,t.flags&=-9,t=n}}let e;for(;Pn;){let t=Pn;for(Pn=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(s){e||(e=s)}t=n}}if(e)throw e}function pi(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function hi(e){let t,n=e.depsTail,s=n;for(;s;){const r=s.prevDep;s.version===-1?(s===n&&(n=r),Zs(s),Yl(s)):t=s,s.dep.activeLink=s.prevActiveLink,s.prevActiveLink=void 0,s=r}e.deps=t,e.depsTail=n}function Ys(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(gi(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function gi(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Mn)||(e.globalVersion=Mn,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Ys(e))))return;e.flags|=2;const t=e.dep,n=_e,s=gt;_e=e,gt=!0;try{pi(e);const r=e.fn(e._value);(t.version===0||jt(r,e._value))&&(e.flags|=128,e._value=r,t.version++)}catch(r){throw t.version++,r}finally{_e=n,gt=s,hi(e),e.flags&=-3}}function Zs(e,t=!1){const{dep:n,prevSub:s,nextSub:r}=e;if(s&&(s.nextSub=r,e.prevSub=void 0),r&&(r.prevSub=s,e.nextSub=void 0),n.subs===e&&(n.subs=s,!s&&n.computed)){n.computed.flags&=-5;for(let i=n.computed.deps;i;i=i.nextDep)Zs(i,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function Yl(e){const{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}let gt=!0;const mi=[];function It(){mi.push(gt),gt=!1}function Mt(){const e=mi.pop();gt=e===void 0?!0:e}function bi(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const n=_e;_e=void 0;try{t()}finally{_e=n}}}let Mn=0;class Zl{constructor(t,n){this.sub=t,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class Xs{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!_e||!gt||_e===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==_e)n=this.activeLink=new Zl(_e,this),_e.deps?(n.prevDep=_e.depsTail,_e.depsTail.nextDep=n,_e.depsTail=n):_e.deps=_e.depsTail=n,xi(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const s=n.nextDep;s.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=s),n.prevDep=_e.depsTail,n.nextDep=void 0,_e.depsTail.nextDep=n,_e.depsTail=n,_e.deps===n&&(_e.deps=s)}return n}trigger(t){this.version++,Mn++,this.notify(t)}notify(t){Gs();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{Ks()}}}function xi(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let s=t.deps;s;s=s.nextDep)xi(s)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const Qs=new WeakMap,en=Symbol(""),Js=Symbol(""),Ln=Symbol("");function Ue(e,t,n){if(gt&&_e){let s=Qs.get(e);s||Qs.set(e,s=new Map);let r=s.get(n);r||(s.set(n,r=new Xs),r.map=s,r.key=n),r.track()}}function Lt(e,t,n,s,r,i){const o=Qs.get(e);if(!o){Mn++;return}const a=l=>{l&&l.trigger()};if(Gs(),t==="clear")o.forEach(a);else{const l=Q(e),c=l&&Hs(n);if(l&&n==="length"){const u=Number(s);o.forEach((p,g)=>{(g==="length"||g===Ln||!zt(g)&&g>=u)&&a(p)})}else switch((n!==void 0||o.has(void 0))&&a(o.get(n)),c&&a(o.get(Ln)),t){case"add":l?c&&a(o.get("length")):(a(o.get(en)),pn(e)&&a(o.get(Js)));break;case"delete":l||(a(o.get(en)),pn(e)&&a(o.get(Js)));break;case"set":pn(e)&&a(o.get(en));break}}Ks()}function hn(e){const t=oe(e);return t===e?t:(Ue(t,"iterate",Ln),lt(e)?t:t.map(Fe))}function is(e){return Ue(e=oe(e),"iterate",Ln),e}const Xl={__proto__:null,[Symbol.iterator](){return er(this,Symbol.iterator,Fe)},concat(...e){return hn(this).concat(...e.map(t=>Q(t)?hn(t):t))},entries(){return er(this,"entries",e=>(e[1]=Fe(e[1]),e))},every(e,t){return Ot(this,"every",e,t,void 0,arguments)},filter(e,t){return Ot(this,"filter",e,t,n=>n.map(Fe),arguments)},find(e,t){return Ot(this,"find",e,t,Fe,arguments)},findIndex(e,t){return Ot(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return Ot(this,"findLast",e,t,Fe,arguments)},findLastIndex(e,t){return Ot(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return Ot(this,"forEach",e,t,void 0,arguments)},includes(...e){return tr(this,"includes",e)},indexOf(...e){return tr(this,"indexOf",e)},join(e){return hn(this).join(e)},lastIndexOf(...e){return tr(this,"lastIndexOf",e)},map(e,t){return Ot(this,"map",e,t,void 0,arguments)},pop(){return On(this,"pop")},push(...e){return On(this,"push",e)},reduce(e,...t){return yi(this,"reduce",e,t)},reduceRight(e,...t){return yi(this,"reduceRight",e,t)},shift(){return On(this,"shift")},some(e,t){return Ot(this,"some",e,t,void 0,arguments)},splice(...e){return On(this,"splice",e)},toReversed(){return hn(this).toReversed()},toSorted(e){return hn(this).toSorted(e)},toSpliced(...e){return hn(this).toSpliced(...e)},unshift(...e){return On(this,"unshift",e)},values(){return er(this,"values",Fe)}};function er(e,t,n){const s=is(e),r=s[t]();return s!==e&&!lt(e)&&(r._next=r.next,r.next=()=>{const i=r._next();return i.value&&(i.value=n(i.value)),i}),r}const Ql=Array.prototype;function Ot(e,t,n,s,r,i){const o=is(e),a=o!==e&&!lt(e),l=o[t];if(l!==Ql[t]){const p=l.apply(e,i);return a?Fe(p):p}let c=n;o!==e&&(a?c=function(p,g){return n.call(this,Fe(p),g,e)}:n.length>2&&(c=function(p,g){return n.call(this,p,g,e)}));const u=l.call(o,c,s);return a&&r?r(u):u}function yi(e,t,n,s){const r=is(e);let i=n;return r!==e&&(lt(e)?n.length>3&&(i=function(o,a,l){return n.call(this,o,a,l,e)}):i=function(o,a,l){return n.call(this,o,Fe(a),l,e)}),r[t](i,...s)}function tr(e,t,n){const s=oe(e);Ue(s,"iterate",Ln);const r=s[t](...n);return(r===-1||r===!1)&&sr(n[0])?(n[0]=oe(n[0]),s[t](...n)):r}function On(e,t,n=[]){It(),Gs();const s=oe(e)[t].apply(e,n);return Ks(),Mt(),s}const Jl=Pt("__proto__,__v_isRef,__isVue"),wi=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(zt));function ea(e){zt(e)||(e=String(e));const t=oe(this);return Ue(t,"has",e),t.hasOwnProperty(e)}class vi{constructor(t=!1,n=!1){this._isReadonly=t,this._isShallow=n}get(t,n,s){if(n==="__v_skip")return t.__v_skip;const r=this._isReadonly,i=this._isShallow;if(n==="__v_isReactive")return!r;if(n==="__v_isReadonly")return r;if(n==="__v_isShallow")return i;if(n==="__v_raw")return s===(r?i?Ai:Ei:i?Si:Ti).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(s)?t:void 0;const o=Q(t);if(!r){let l;if(o&&(l=Xl[n]))return l;if(n==="hasOwnProperty")return ea}const a=Reflect.get(t,n,je(t)?t:s);return(zt(n)?wi.has(n):Jl(n))||(r||Ue(t,"get",n),i)?a:je(a)?o&&Hs(n)?a:a.value:Ae(a)?r?Ri(a):us(a):a}}class _i extends vi{constructor(t=!1){super(!1,t)}set(t,n,s,r){let i=t[n];if(!this._isShallow){const l=Vt(i);if(!lt(s)&&!Vt(s)&&(i=oe(i),s=oe(s)),!Q(t)&&je(i)&&!je(s))return l?!1:(i.value=s,!0)}const o=Q(t)&&Hs(n)?Number(n)e,os=e=>Reflect.getPrototypeOf(e);function ia(e,t,n){return function(...s){const r=this.__v_raw,i=oe(r),o=pn(i),a=e==="entries"||e===Symbol.iterator&&o,l=e==="keys"&&o,c=r[e](...s),u=n?nr:t?fs:Fe;return!t&&Ue(i,"iterate",l?Js:en),{next(){const{value:p,done:g}=c.next();return g?{value:p,done:g}:{value:a?[u(p[0]),u(p[1])]:u(p),done:g}},[Symbol.iterator](){return this}}}}function ls(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function oa(e,t){const n={get(r){const i=this.__v_raw,o=oe(i),a=oe(r);e||(jt(r,a)&&Ue(o,"get",r),Ue(o,"get",a));const{has:l}=os(o),c=t?nr:e?fs:Fe;if(l.call(o,r))return c(i.get(r));if(l.call(o,a))return c(i.get(a));i!==o&&i.get(r)},get size(){const r=this.__v_raw;return!e&&Ue(oe(r),"iterate",en),Reflect.get(r,"size",r)},has(r){const i=this.__v_raw,o=oe(i),a=oe(r);return e||(jt(r,a)&&Ue(o,"has",r),Ue(o,"has",a)),r===a?i.has(r):i.has(r)||i.has(a)},forEach(r,i){const o=this,a=o.__v_raw,l=oe(a),c=t?nr:e?fs:Fe;return!e&&Ue(l,"iterate",en),a.forEach((u,p)=>r.call(i,c(u),c(p),o))}};return ht(n,e?{add:ls("add"),set:ls("set"),delete:ls("delete"),clear:ls("clear")}:{add(r){!t&&!lt(r)&&!Vt(r)&&(r=oe(r));const i=oe(this);return os(i).has.call(i,r)||(i.add(r),Lt(i,"add",r,r)),this},set(r,i){!t&&!lt(i)&&!Vt(i)&&(i=oe(i));const o=oe(this),{has:a,get:l}=os(o);let c=a.call(o,r);c||(r=oe(r),c=a.call(o,r));const u=l.call(o,r);return o.set(r,i),c?jt(i,u)&&Lt(o,"set",r,i):Lt(o,"add",r,i),this},delete(r){const i=oe(this),{has:o,get:a}=os(i);let l=o.call(i,r);l||(r=oe(r),l=o.call(i,r)),a&&a.call(i,r);const c=i.delete(r);return l&&Lt(i,"delete",r,void 0),c},clear(){const r=oe(this),i=r.size!==0,o=r.clear();return i&&Lt(r,"clear",void 0,void 0),o}}),["keys","values","entries",Symbol.iterator].forEach(r=>{n[r]=ia(r,e,t)}),n}function as(e,t){const n=oa(e,t);return(s,r,i)=>r==="__v_isReactive"?!e:r==="__v_isReadonly"?e:r==="__v_raw"?s:Reflect.get(ge(n,r)&&r in s?n:s,r,i)}const la={get:as(!1,!1)},aa={get:as(!1,!0)},ua={get:as(!0,!1)},ca={get:as(!0,!0)},Ti=new WeakMap,Si=new WeakMap,Ei=new WeakMap,Ai=new WeakMap;function fa(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function da(e){return e.__v_skip||!Object.isExtensible(e)?0:fa(Fl(e))}function us(e){return Vt(e)?e:cs(e,!1,ta,la,Ti)}function pa(e){return cs(e,!1,sa,aa,Si)}function Ri(e){return cs(e,!0,na,ua,Ei)}function Tp(e){return cs(e,!0,ra,ca,Ai)}function cs(e,t,n,s,r){if(!Ae(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;const i=da(e);if(i===0)return e;const o=r.get(e);if(o)return o;const a=new Proxy(e,i===2?s:n);return r.set(e,a),a}function gn(e){return Vt(e)?gn(e.__v_raw):!!(e&&e.__v_isReactive)}function Vt(e){return!!(e&&e.__v_isReadonly)}function lt(e){return!!(e&&e.__v_isShallow)}function sr(e){return e?!!e.__v_raw:!1}function oe(e){const t=e&&e.__v_raw;return t?oe(t):e}function ha(e){return!ge(e,"__v_skip")&&Object.isExtensible(e)&&Us(e,"__v_skip",!0),e}const Fe=e=>Ae(e)?us(e):e,fs=e=>Ae(e)?Ri(e):e;function je(e){return e?e.__v_isRef===!0:!1}function J(e){return ga(e,!1)}function ga(e,t){return je(e)?e:new ma(e,t)}class ma{constructor(t,n){this.dep=new Xs,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?t:oe(t),this._value=n?t:Fe(t),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(t){const n=this._rawValue,s=this.__v_isShallow||lt(t)||Vt(t);t=s?t:oe(t),jt(t,n)&&(this._rawValue=t,this._value=s?t:Fe(t),this.dep.trigger())}}function ba(e){return je(e)?e.value:e}const xa={get:(e,t,n)=>t==="__v_raw"?e:ba(Reflect.get(e,t,n)),set:(e,t,n,s)=>{const r=e[t];return je(r)&&!je(n)?(r.value=n,!0):Reflect.set(e,t,n,s)}};function Ci(e){return gn(e)?e:new Proxy(e,xa)}class ya{constructor(t,n,s){this.fn=t,this.setter=n,this._value=void 0,this.dep=new Xs(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=Mn-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=s}notify(){if(this.flags|=16,!(this.flags&8)&&_e!==this)return di(this,!0),!0}get value(){const t=this.dep.track();return gi(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function wa(e,t,n=!1){let s,r;return be(e)?s=e:(s=e.get,r=e.set),new ya(s,r,n)}const ds={},ps=new WeakMap;let tn;function va(e,t=!1,n=tn){if(n){let s=ps.get(n);s||ps.set(n,s=[]),s.push(e)}}function _a(e,t,n=se){const{immediate:s,deep:r,once:i,scheduler:o,augmentJob:a,call:l}=n,c=O=>r?O:lt(O)||r===!1||r===0?$t(O,1):$t(O);let u,p,g,w,E=!1,m=!1;if(je(e)?(p=()=>e.value,E=lt(e)):gn(e)?(p=()=>c(e),E=!0):Q(e)?(m=!0,E=e.some(O=>gn(O)||lt(O)),p=()=>e.map(O=>{if(je(O))return O.value;if(gn(O))return c(O);if(be(O))return l?l(O,2):O()})):be(e)?t?p=l?()=>l(e,2):e:p=()=>{if(g){It();try{g()}finally{Mt()}}const O=tn;tn=u;try{return l?l(e,3,[w]):e(w)}finally{tn=O}}:p=Qt,t&&r){const O=p,z=r===!0?1/0:r;p=()=>$t(O(),z)}const A=Kl(),T=()=>{u.stop(),A&&A.active&&ei(A.effects,u)};if(i&&t){const O=t;t=(...z)=>{O(...z),T()}}let W=m?new Array(e.length).fill(ds):ds;const K=O=>{if(!(!(u.flags&1)||!u.dirty&&!O))if(t){const z=u.run();if(r||E||(m?z.some((P,I)=>jt(P,W[I])):jt(z,W))){g&&g();const P=tn;tn=u;try{const I=[z,W===ds?void 0:m&&W[0]===ds?[]:W,w];W=z,l?l(t,3,I):t(...I)}finally{tn=P}}}else u.run()};return a&&a(K),u=new ci(p),u.scheduler=o?()=>o(K,!1):K,w=O=>va(O,!1,u),g=u.onStop=()=>{const O=ps.get(u);if(O){if(l)l(O,4);else for(const z of O)z();ps.delete(u)}},t?s?K(!0):W=u.run():o?o(K.bind(null,!0),!0):u.run(),T.pause=u.pause.bind(u),T.resume=u.resume.bind(u),T.stop=T,T}function $t(e,t=1/0,n){if(t<=0||!Ae(e)||e.__v_skip||(n=n||new Set,n.has(e)))return e;if(n.add(e),t--,je(e))$t(e.value,t,n);else if(Q(e))for(let s=0;s{$t(s,t,n)});else if(ri(e)){for(const s in e)$t(e[s],t,n);for(const s of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,s)&&$t(e[s],t,n)}return e}const $n=[];let rr=!1;function Sp(e,...t){if(rr)return;rr=!0,It();const n=$n.length?$n[$n.length-1].component:null,s=n&&n.appContext.config.warnHandler,r=ka();if(s)mn(s,n,11,[e+t.map(i=>{var o,a;return(a=(o=i.toString)==null?void 0:o.call(i))!=null?a:JSON.stringify(i)}).join(""),n&&n.proxy,r.map(({vnode:i})=>`at <${mo(n,i.type)}>`).join(` +var vd=Object.defineProperty;var _d=(Pt,oe,mt)=>oe in Pt?vd(Pt,oe,{enumerable:!0,configurable:!0,writable:!0,value:mt}):Pt[oe]=mt;var _e=(Pt,oe,mt)=>_d(Pt,typeof oe!="symbol"?oe+"":oe,mt);(function(){"use strict";var Fs;function Pt(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const oe={},mt=[],Jt=()=>{},Dl=()=>!1,ts=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Hs=e=>e.startsWith("onUpdate:"),bt=Object.assign,Jr=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},Nl=Object.prototype.hasOwnProperty,me=(e,t)=>Nl.call(e,t),Q=Array.isArray,hn=e=>ns(e)==="[object Map]",ei=e=>ns(e)==="[object Set]",be=e=>typeof e=="function",Pe=e=>typeof e=="string",Ut=e=>typeof e=="symbol",Re=e=>e!==null&&typeof e=="object",ti=e=>(Re(e)||be(e))&&be(e.then)&&be(e.catch),ni=Object.prototype.toString,ns=e=>ni.call(e),Fl=e=>ns(e).slice(8,-1),si=e=>ns(e)==="[object Object]",zs=e=>Pe(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,Pn=Pt(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),ss=e=>{const t=Object.create(null);return n=>t[n]||(t[n]=e(n))},Bl=/-(\w)/g,jt=ss(e=>e.replace(Bl,(t,n)=>n?n.toUpperCase():"")),Hl=/\B([A-Z])/g,en=ss(e=>e.replace(Hl,"-$1").toLowerCase()),ri=ss(e=>e.charAt(0).toUpperCase()+e.slice(1)),Us=ss(e=>e?`on${ri(e)}`:""),Vt=(e,t)=>!Object.is(e,t),rs=(e,...t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:s,value:n})},Vs=e=>{const t=parseFloat(e);return isNaN(t)?e:t},zl=e=>{const t=Pe(e)?Number(e):NaN;return isNaN(t)?e:t};let ii;const is=()=>ii||(ii=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"?window:typeof global!="undefined"?global:{});function qs(e){if(Q(e)){const t={};for(let n=0;n{if(n){const s=n.split(jl);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function we(e){let t="";if(Pe(e))t=e;else if(Q(e))for(let n=0;n!!(e&&e.__v_isRef===!0),Je=e=>Pe(e)?e:e==null?"":Q(e)||Re(e)&&(e.toString===ni||!be(e.toString))?li(e)?Je(e.value):JSON.stringify(e,ai,2):String(e),ai=(e,t)=>li(t)?ai(e,t.value):hn(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,r],i)=>(n[Ws(s,i)+" =>"]=r,n),{})}:ei(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>Ws(n))}:Ut(t)?Ws(t):Re(t)&&!Q(t)&&!si(t)?String(t):t,Ws=(e,t="")=>{var n;return Ut(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};let et;class Gl{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=et,!t&&et&&(this.index=(et.scopes||(et.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t0&&--this._on===0&&(et=this.prevScope,this.prevScope=void 0)}stop(t){if(this._active){this._active=!1;let n,s;for(n=0,s=this.effects.length;n0)return;if(Mn){let t=Mn;for(Mn=void 0;t;){const n=t.next;t.next=void 0,t.flags&=-9,t=n}}let e;for(;In;){let t=In;for(In=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(s){e||(e=s)}t=n}}if(e)throw e}function pi(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function di(e){let t,n=e.depsTail,s=n;for(;s;){const r=s.prevDep;s.version===-1?(s===n&&(n=r),Xs(s),Yl(s)):t=s,s.dep.activeLink=s.prevActiveLink,s.prevActiveLink=void 0,s=r}e.deps=t,e.depsTail=n}function Zs(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(hi(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function hi(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===On)||(e.globalVersion=On,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Zs(e))))return;e.flags|=2;const t=e.dep,n=Te,s=xt;Te=e,xt=!0;try{pi(e);const r=e.fn(e._value);(t.version===0||Vt(r,e._value))&&(e.flags|=128,e._value=r,t.version++)}catch(r){throw t.version++,r}finally{Te=n,xt=s,di(e),e.flags&=-3}}function Xs(e,t=!1){const{dep:n,prevSub:s,nextSub:r}=e;if(s&&(s.nextSub=r,e.prevSub=void 0),r&&(r.prevSub=s,e.nextSub=void 0),n.subs===e&&(n.subs=s,!s&&n.computed)){n.computed.flags&=-5;for(let i=n.computed.deps;i;i=i.nextDep)Xs(i,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function Yl(e){const{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}let xt=!0;const gi=[];function It(){gi.push(xt),xt=!1}function Mt(){const e=gi.pop();xt=e===void 0?!0:e}function mi(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const n=Te;Te=void 0;try{t()}finally{Te=n}}}let On=0;class Zl{constructor(t,n){this.sub=t,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class Qs{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!Te||!xt||Te===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==Te)n=this.activeLink=new Zl(Te,this),Te.deps?(n.prevDep=Te.depsTail,Te.depsTail.nextDep=n,Te.depsTail=n):Te.deps=Te.depsTail=n,bi(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const s=n.nextDep;s.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=s),n.prevDep=Te.depsTail,n.nextDep=void 0,Te.depsTail.nextDep=n,Te.depsTail=n,Te.deps===n&&(Te.deps=s)}return n}trigger(t){this.version++,On++,this.notify(t)}notify(t){Ks();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{Ys()}}}function bi(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let s=t.deps;s;s=s.nextDep)bi(s)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const Js=new WeakMap,tn=Symbol(""),er=Symbol(""),Ln=Symbol("");function je(e,t,n){if(xt&&Te){let s=Js.get(e);s||Js.set(e,s=new Map);let r=s.get(n);r||(s.set(n,r=new Qs),r.map=s,r.key=n),r.track()}}function Ot(e,t,n,s,r,i){const o=Js.get(e);if(!o){On++;return}const a=l=>{l&&l.trigger()};if(Ks(),t==="clear")o.forEach(a);else{const l=Q(e),f=l&&zs(n);if(l&&n==="length"){const u=Number(s);o.forEach((d,g)=>{(g==="length"||g===Ln||!Ut(g)&&g>=u)&&a(d)})}else switch((n!==void 0||o.has(void 0))&&a(o.get(n)),f&&a(o.get(Ln)),t){case"add":l?f&&a(o.get("length")):(a(o.get(tn)),hn(e)&&a(o.get(er)));break;case"delete":l||(a(o.get(tn)),hn(e)&&a(o.get(er)));break;case"set":hn(e)&&a(o.get(tn));break}}Ys()}function gn(e){const t=ue(e);return t===e?t:(je(t,"iterate",Ln),ut(e)?t:t.map(Be))}function os(e){return je(e=ue(e),"iterate",Ln),e}const Xl={__proto__:null,[Symbol.iterator](){return tr(this,Symbol.iterator,Be)},concat(...e){return gn(this).concat(...e.map(t=>Q(t)?gn(t):t))},entries(){return tr(this,"entries",e=>(e[1]=Be(e[1]),e))},every(e,t){return Lt(this,"every",e,t,void 0,arguments)},filter(e,t){return Lt(this,"filter",e,t,n=>n.map(Be),arguments)},find(e,t){return Lt(this,"find",e,t,Be,arguments)},findIndex(e,t){return Lt(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return Lt(this,"findLast",e,t,Be,arguments)},findLastIndex(e,t){return Lt(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return Lt(this,"forEach",e,t,void 0,arguments)},includes(...e){return nr(this,"includes",e)},indexOf(...e){return nr(this,"indexOf",e)},join(e){return gn(this).join(e)},lastIndexOf(...e){return nr(this,"lastIndexOf",e)},map(e,t){return Lt(this,"map",e,t,void 0,arguments)},pop(){return $n(this,"pop")},push(...e){return $n(this,"push",e)},reduce(e,...t){return xi(this,"reduce",e,t)},reduceRight(e,...t){return xi(this,"reduceRight",e,t)},shift(){return $n(this,"shift")},some(e,t){return Lt(this,"some",e,t,void 0,arguments)},splice(...e){return $n(this,"splice",e)},toReversed(){return gn(this).toReversed()},toSorted(e){return gn(this).toSorted(e)},toSpliced(...e){return gn(this).toSpliced(...e)},unshift(...e){return $n(this,"unshift",e)},values(){return tr(this,"values",Be)}};function tr(e,t,n){const s=os(e),r=s[t]();return s!==e&&!ut(e)&&(r._next=r.next,r.next=()=>{const i=r._next();return i.value&&(i.value=n(i.value)),i}),r}const Ql=Array.prototype;function Lt(e,t,n,s,r,i){const o=os(e),a=o!==e&&!ut(e),l=o[t];if(l!==Ql[t]){const d=l.apply(e,i);return a?Be(d):d}let f=n;o!==e&&(a?f=function(d,g){return n.call(this,Be(d),g,e)}:n.length>2&&(f=function(d,g){return n.call(this,d,g,e)}));const u=l.call(o,f,s);return a&&r?r(u):u}function xi(e,t,n,s){const r=os(e);let i=n;return r!==e&&(ut(e)?n.length>3&&(i=function(o,a,l){return n.call(this,o,a,l,e)}):i=function(o,a,l){return n.call(this,o,Be(a),l,e)}),r[t](i,...s)}function nr(e,t,n){const s=ue(e);je(s,"iterate",Ln);const r=s[t](...n);return(r===-1||r===!1)&&rr(n[0])?(n[0]=ue(n[0]),s[t](...n)):r}function $n(e,t,n=[]){It(),Ks();const s=ue(e)[t].apply(e,n);return Ys(),Mt(),s}const Jl=Pt("__proto__,__v_isRef,__isVue"),yi=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(Ut));function ea(e){Ut(e)||(e=String(e));const t=ue(this);return je(t,"has",e),t.hasOwnProperty(e)}class wi{constructor(t=!1,n=!1){this._isReadonly=t,this._isShallow=n}get(t,n,s){if(n==="__v_skip")return t.__v_skip;const r=this._isReadonly,i=this._isShallow;if(n==="__v_isReactive")return!r;if(n==="__v_isReadonly")return r;if(n==="__v_isShallow")return i;if(n==="__v_raw")return s===(r?i?Ei:Si:i?ki:Ti).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(s)?t:void 0;const o=Q(t);if(!r){let l;if(o&&(l=Xl[n]))return l;if(n==="hasOwnProperty")return ea}const a=Reflect.get(t,n,Ve(t)?t:s);return(Ut(n)?yi.has(n):Jl(n))||(r||je(t,"get",n),i)?a:Ve(a)?o&&zs(n)?a:a.value:Re(a)?r?Ai(a):cs(a):a}}class vi extends wi{constructor(t=!1){super(!1,t)}set(t,n,s,r){let i=t[n];if(!this._isShallow){const l=qt(i);if(!ut(s)&&!qt(s)&&(i=ue(i),s=ue(s)),!Q(t)&&Ve(i)&&!Ve(s))return l?!1:(i.value=s,!0)}const o=Q(t)&&zs(n)?Number(n)e,ls=e=>Reflect.getPrototypeOf(e);function ia(e,t,n){return function(...s){const r=this.__v_raw,i=ue(r),o=hn(i),a=e==="entries"||e===Symbol.iterator&&o,l=e==="keys"&&o,f=r[e](...s),u=n?sr:t?ps:Be;return!t&&je(i,"iterate",l?er:tn),{next(){const{value:d,done:g}=f.next();return g?{value:d,done:g}:{value:a?[u(d[0]),u(d[1])]:u(d),done:g}},[Symbol.iterator](){return this}}}}function as(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function oa(e,t){const n={get(r){const i=this.__v_raw,o=ue(i),a=ue(r);e||(Vt(r,a)&&je(o,"get",r),je(o,"get",a));const{has:l}=ls(o),f=t?sr:e?ps:Be;if(l.call(o,r))return f(i.get(r));if(l.call(o,a))return f(i.get(a));i!==o&&i.get(r)},get size(){const r=this.__v_raw;return!e&&je(ue(r),"iterate",tn),Reflect.get(r,"size",r)},has(r){const i=this.__v_raw,o=ue(i),a=ue(r);return e||(Vt(r,a)&&je(o,"has",r),je(o,"has",a)),r===a?i.has(r):i.has(r)||i.has(a)},forEach(r,i){const o=this,a=o.__v_raw,l=ue(a),f=t?sr:e?ps:Be;return!e&&je(l,"iterate",tn),a.forEach((u,d)=>r.call(i,f(u),f(d),o))}};return bt(n,e?{add:as("add"),set:as("set"),delete:as("delete"),clear:as("clear")}:{add(r){!t&&!ut(r)&&!qt(r)&&(r=ue(r));const i=ue(this);return ls(i).has.call(i,r)||(i.add(r),Ot(i,"add",r,r)),this},set(r,i){!t&&!ut(i)&&!qt(i)&&(i=ue(i));const o=ue(this),{has:a,get:l}=ls(o);let f=a.call(o,r);f||(r=ue(r),f=a.call(o,r));const u=l.call(o,r);return o.set(r,i),f?Vt(i,u)&&Ot(o,"set",r,i):Ot(o,"add",r,i),this},delete(r){const i=ue(this),{has:o,get:a}=ls(i);let l=o.call(i,r);l||(r=ue(r),l=o.call(i,r)),a&&a.call(i,r);const f=i.delete(r);return l&&Ot(i,"delete",r,void 0),f},clear(){const r=ue(this),i=r.size!==0,o=r.clear();return i&&Ot(r,"clear",void 0,void 0),o}}),["keys","values","entries",Symbol.iterator].forEach(r=>{n[r]=ia(r,e,t)}),n}function us(e,t){const n=oa(e,t);return(s,r,i)=>r==="__v_isReactive"?!e:r==="__v_isReadonly"?e:r==="__v_raw"?s:Reflect.get(me(n,r)&&r in s?n:s,r,i)}const la={get:us(!1,!1)},aa={get:us(!1,!0)},ua={get:us(!0,!1)},ca={get:us(!0,!0)},Ti=new WeakMap,ki=new WeakMap,Si=new WeakMap,Ei=new WeakMap;function fa(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function pa(e){return e.__v_skip||!Object.isExtensible(e)?0:fa(Fl(e))}function cs(e){return qt(e)?e:fs(e,!1,ta,la,Ti)}function da(e){return fs(e,!1,sa,aa,ki)}function Ai(e){return fs(e,!0,na,ua,Si)}function kd(e){return fs(e,!0,ra,ca,Ei)}function fs(e,t,n,s,r){if(!Re(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;const i=pa(e);if(i===0)return e;const o=r.get(e);if(o)return o;const a=new Proxy(e,i===2?s:n);return r.set(e,a),a}function mn(e){return qt(e)?mn(e.__v_raw):!!(e&&e.__v_isReactive)}function qt(e){return!!(e&&e.__v_isReadonly)}function ut(e){return!!(e&&e.__v_isShallow)}function rr(e){return e?!!e.__v_raw:!1}function ue(e){const t=e&&e.__v_raw;return t?ue(t):e}function ha(e){return!me(e,"__v_skip")&&Object.isExtensible(e)&&js(e,"__v_skip",!0),e}const Be=e=>Re(e)?cs(e):e,ps=e=>Re(e)?Ai(e):e;function Ve(e){return e?e.__v_isRef===!0:!1}function J(e){return ga(e,!1)}function ga(e,t){return Ve(e)?e:new ma(e,t)}class ma{constructor(t,n){this.dep=new Qs,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?t:ue(t),this._value=n?t:Be(t),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(t){const n=this._rawValue,s=this.__v_isShallow||ut(t)||qt(t);t=s?t:ue(t),Vt(t,n)&&(this._rawValue=t,this._value=s?t:Be(t),this.dep.trigger())}}function ba(e){return Ve(e)?e.value:e}const xa={get:(e,t,n)=>t==="__v_raw"?e:ba(Reflect.get(e,t,n)),set:(e,t,n,s)=>{const r=e[t];return Ve(r)&&!Ve(n)?(r.value=n,!0):Reflect.set(e,t,n,s)}};function Ri(e){return mn(e)?e:new Proxy(e,xa)}class ya{constructor(t,n,s){this.fn=t,this.setter=n,this._value=void 0,this.dep=new Qs(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=On-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=s}notify(){if(this.flags|=16,!(this.flags&8)&&Te!==this)return fi(this,!0),!0}get value(){const t=this.dep.track();return hi(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function wa(e,t,n=!1){let s,r;return be(e)?s=e:(s=e.get,r=e.set),new ya(s,r,n)}const ds={},hs=new WeakMap;let nn;function va(e,t=!1,n=nn){if(n){let s=hs.get(n);s||hs.set(n,s=[]),s.push(e)}}function _a(e,t,n=oe){const{immediate:s,deep:r,once:i,scheduler:o,augmentJob:a,call:l}=n,f=$=>r?$:ut($)||r===!1||r===0?$t($,1):$t($);let u,d,g,y,E=!1,x=!1;if(Ve(e)?(d=()=>e.value,E=ut(e)):mn(e)?(d=()=>f(e),E=!0):Q(e)?(x=!0,E=e.some($=>mn($)||ut($)),d=()=>e.map($=>{if(Ve($))return $.value;if(mn($))return f($);if(be($))return l?l($,2):$()})):be(e)?t?d=l?()=>l(e,2):e:d=()=>{if(g){It();try{g()}finally{Mt()}}const $=nn;nn=u;try{return l?l(e,3,[y]):e(y)}finally{nn=$}}:d=Jt,t&&r){const $=d,z=r===!0?1/0:r;d=()=>$t($(),z)}const M=Kl(),m=()=>{u.stop(),M&&M.active&&Jr(M.effects,u)};if(i&&t){const $=t;t=(...z)=>{$(...z),m()}}let H=x?new Array(e.length).fill(ds):ds;const Y=$=>{if(!(!(u.flags&1)||!u.dirty&&!$))if(t){const z=u.run();if(r||E||(x?z.some((O,P)=>Vt(O,H[P])):Vt(z,H))){g&&g();const O=nn;nn=u;try{const P=[z,H===ds?void 0:x&&H[0]===ds?[]:H,y];H=z,l?l(t,3,P):t(...P)}finally{nn=O}}}else u.run()};return a&&a(Y),u=new ui(d),u.scheduler=o?()=>o(Y,!1):Y,y=$=>va($,!1,u),g=u.onStop=()=>{const $=hs.get(u);if($){if(l)l($,4);else for(const z of $)z();hs.delete(u)}},t?s?Y(!0):H=u.run():o?o(Y.bind(null,!0),!0):u.run(),m.pause=u.pause.bind(u),m.resume=u.resume.bind(u),m.stop=m,m}function $t(e,t=1/0,n){if(t<=0||!Re(e)||e.__v_skip||(n=n||new Set,n.has(e)))return e;if(n.add(e),t--,Ve(e))$t(e.value,t,n);else if(Q(e))for(let s=0;s{$t(s,t,n)});else if(si(e)){for(const s in e)$t(e[s],t,n);for(const s of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,s)&&$t(e[s],t,n)}return e}const Dn=[];let ir=!1;function Sd(e,...t){if(ir)return;ir=!0,It();const n=Dn.length?Dn[Dn.length-1].component:null,s=n&&n.appContext.config.warnHandler,r=Ta();if(s)bn(s,n,11,[e+t.map(i=>{var o,a;return(a=(o=i.toString)==null?void 0:o.call(i))!=null?a:JSON.stringify(i)}).join(""),n&&n.proxy,r.map(({vnode:i})=>`at <${go(n,i.type)}>`).join(` `),r]);else{const i=[`[Vue warn]: ${e}`,...t];r.length&&i.push(` -`,...Ta(r))}Mt(),rr=!1}function ka(){let e=$n[$n.length-1];if(!e)return[];const t=[];for(;e;){const n=t[0];n&&n.vnode===e?n.recurseCount++:t.push({vnode:e,recurseCount:0});const s=e.component&&e.component.parent;e=s&&s.vnode}return t}function Ta(e){const t=[];return e.forEach((n,s)=>{t.push(...s===0?[]:[` -`],...Sa(n))}),t}function Sa({vnode:e,recurseCount:t}){const n=t>0?`... (${t} recursive calls)`:"",s=e.component?e.component.parent==null:!1,r=` at <${mo(e.component,e.type,s)}`,i=">"+n;return e.props?[r,...Ea(e.props),i]:[r+i]}function Ea(e){const t=[],n=Object.keys(e);return n.slice(0,3).forEach(s=>{t.push(...Pi(s,e[s]))}),n.length>3&&t.push(" ..."),t}function Pi(e,t,n){return Ce(t)?(t=JSON.stringify(t),n?t:[`${e}=${t}`]):typeof t=="number"||typeof t=="boolean"||t==null?n?t:[`${e}=${t}`]:je(t)?(t=Pi(e,oe(t.value),!0),n?t:[`${e}=Ref<`,t,">"]):be(t)?[`${e}=fn${t.name?`<${t.name}>`:""}`]:(t=oe(t),n?t:[`${e}=`,t])}function mn(e,t,n,s){try{return s?e(...s):e()}catch(r){hs(r,t,n)}}function _t(e,t,n,s){if(be(e)){const r=mn(e,t,n,s);return r&&ni(r)&&r.catch(i=>{hs(i,t,n)}),r}if(Q(e)){const r=[];for(let i=0;i>>1,r=Ge[s],i=Dn(r);i=Dn(n)?Ge.push(e):Ge.splice(Ra(t),0,e),e.flags|=1,Mi()}}function Mi(){gs||(gs=Ii.then($i))}function Ca(e){Q(e)?bn.push(...e):qt&&e.id===-1?qt.splice(xn+1,0,e):e.flags&1||(bn.push(e),e.flags|=1),Mi()}function Li(e,t,n=kt+1){for(;nDn(n)-Dn(s));if(bn.length=0,qt){qt.push(...t);return}for(qt=t,xn=0;xne.id==null?e.flags&2?-1:1/0:e.id;function $i(e){try{for(kt=0;kt{s._d&&lo(-1);const i=ms(t);let o;try{o=e(...r)}finally{ms(i),s._d&&lo(1)}return o};return s._n=!0,s._c=!0,s._d=!0,s}function Pa(e,t){if(at===null)return e;const n=Es(at),s=e.dirs||(e.dirs=[]);for(let r=0;re.__isTeleport,Wt=Symbol("_leaveCb"),bs=Symbol("_enterCb");function Ma(){const e={isMounted:!1,isLeaving:!1,isUnmounting:!1,leavingVNodes:new Map};return Hn(()=>{e.isMounted=!0}),xs(()=>{e.isUnmounting=!0}),e}const ut=[Function,Array],Bi={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:ut,onEnter:ut,onAfterEnter:ut,onEnterCancelled:ut,onBeforeLeave:ut,onLeave:ut,onAfterLeave:ut,onLeaveCancelled:ut,onBeforeAppear:ut,onAppear:ut,onAfterAppear:ut,onAppearCancelled:ut},Hi=e=>{const t=e.subTree;return t.component?Hi(t.component):t},La={name:"BaseTransition",props:Bi,setup(e,{slots:t}){const n=co(),s=Ma();return()=>{const r=t.default&&Vi(t.default(),!0);if(!r||!r.length)return;const i=zi(r),o=oe(e),{mode:a}=o;if(s.isLeaving)return lr(i);const l=ji(i);if(!l)return lr(i);let c=or(l,o,s,n,p=>c=p);l.type!==Ke&&Nn(l,c);let u=n.subTree&&ji(n.subTree);if(u&&u.type!==Ke&&!on(l,u)&&Hi(n).type!==Ke){let p=or(u,o,s,n);if(Nn(u,p),a==="out-in"&&l.type!==Ke)return s.isLeaving=!0,p.afterLeave=()=>{s.isLeaving=!1,n.job.flags&8||n.update(),delete p.afterLeave,u=void 0},lr(i);a==="in-out"&&l.type!==Ke?p.delayLeave=(g,w,E)=>{const m=Ui(s,u);m[String(u.key)]=u,g[Wt]=()=>{w(),g[Wt]=void 0,delete c.delayedLeave,u=void 0},c.delayedLeave=()=>{E(),delete c.delayedLeave,u=void 0}}:u=void 0}else u&&(u=void 0);return i}}};function zi(e){let t=e[0];if(e.length>1){for(const n of e)if(n.type!==Ke){t=n;break}}return t}const Oa=La;function Ui(e,t){const{leavingVNodes:n}=e;let s=n.get(t.type);return s||(s=Object.create(null),n.set(t.type,s)),s}function or(e,t,n,s,r){const{appear:i,mode:o,persisted:a=!1,onBeforeEnter:l,onEnter:c,onAfterEnter:u,onEnterCancelled:p,onBeforeLeave:g,onLeave:w,onAfterLeave:E,onLeaveCancelled:m,onBeforeAppear:A,onAppear:T,onAfterAppear:W,onAppearCancelled:K}=t,O=String(e.key),z=Ui(n,e),P=(j,te)=>{j&&_t(j,s,9,te)},I=(j,te)=>{const ue=te[1];P(j,te),Q(j)?j.every($=>$.length<=1)&&ue():j.length<=1&&ue()},re={mode:o,persisted:a,beforeEnter(j){let te=l;if(!n.isMounted)if(i)te=A||l;else return;j[Wt]&&j[Wt](!0);const ue=z[O];ue&&on(e,ue)&&ue.el[Wt]&&ue.el[Wt](),P(te,[j])},enter(j){let te=c,ue=u,$=p;if(!n.isMounted)if(i)te=T||c,ue=W||u,$=K||p;else return;let Z=!1;const Y=j[bs]=B=>{Z||(Z=!0,B?P($,[j]):P(ue,[j]),re.delayedLeave&&re.delayedLeave(),j[bs]=void 0)};te?I(te,[j,Y]):Y()},leave(j,te){const ue=String(e.key);if(j[bs]&&j[bs](!0),n.isUnmounting)return te();P(g,[j]);let $=!1;const Z=j[Wt]=Y=>{$||($=!0,te(),Y?P(m,[j]):P(E,[j]),j[Wt]=void 0,z[ue]===e&&delete z[ue])};z[ue]=e,w?I(w,[j,Z]):Z()},clone(j){const te=or(j,t,n,s,r);return r&&r(te),te}};return re}function lr(e){if(ar(e))return e=Gt(e),e.children=null,e}function ji(e){if(!ar(e))return Fi(e.type)&&e.children?zi(e.children):e;if(e.component)return e.component.subTree;const{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&be(n.default))return n.default()}}function Nn(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Nn(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function Vi(e,t=!1,n){let s=[],r=0;for(let i=0;i1)for(let i=0;iFn(E,t&&(Q(t)?t[m]:t),n,s,r));return}if(Bn(s)&&!r){s.shapeFlag&512&&s.type.__asyncResolved&&s.component.subTree.component&&Fn(e,t,n,s.component.subTree);return}const i=s.shapeFlag&4?Es(s.component):s.el,o=r?null:i,{i:a,r:l}=e,c=t&&t.r,u=a.refs===se?a.refs={}:a.refs,p=a.setupState,g=oe(p),w=p===se?()=>!1:E=>ge(g,E);if(c!=null&&c!==l&&(Ce(c)?(u[c]=null,w(c)&&(p[c]=null)):je(c)&&(c.value=null)),be(l))mn(l,a,12,[o,u]);else{const E=Ce(l),m=je(l);if(E||m){const A=()=>{if(e.f){const T=E?w(l)?p[l]:u[l]:l.value;r?Q(T)&&ei(T,i):Q(T)?T.includes(i)||T.push(i):E?(u[l]=[i],w(l)&&(p[l]=u[l])):(l.value=[i],e.k&&(u[e.k]=l.value))}else E?(u[l]=o,w(l)&&(p[l]=o)):m&&(l.value=o,e.k&&(u[e.k]=o))};o?(A.id=-1,nt(A,n)):A()}}}rs().requestIdleCallback,rs().cancelIdleCallback;const Bn=e=>!!e.type.__asyncLoader,ar=e=>e.type.__isKeepAlive;function Da(e,t,n=Yt,s=!1){if(n){const r=n[e]||(n[e]=[]),i=t.__weh||(t.__weh=(...o)=>{It();const a=xr(n),l=_t(t,n,e,o);return a(),Mt(),l});return s?r.unshift(i):r.push(i),i}}const qi=e=>(t,n=Yt)=>{(!Vn||e==="sp")&&Da(e,(...s)=>t(...s),n)},Hn=qi("m"),xs=qi("bum"),Na=Symbol.for("v-ndc");function ys(e,t,n,s){let r;const i=n,o=Q(e);if(o||Ce(e)){const a=o&&gn(e);let l=!1,c=!1;a&&(l=!lt(e),c=Vt(e),e=is(e)),r=new Array(e.length);for(let u=0,p=e.length;ut(a,l,void 0,i));else{const a=Object.keys(e);r=new Array(a.length);for(let l=0,c=a.length;le?po(e)?Es(e):ur(e.parent):null,zn=ht(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>ur(e.parent),$root:e=>ur(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>e.type,$forceUpdate:e=>e.f||(e.f=()=>{ir(e.update)}),$nextTick:e=>e.n||(e.n=Tt.bind(e.proxy)),$watch:e=>Qt}),cr=(e,t)=>e!==se&&!e.__isScriptSetup&&ge(e,t),Fa={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:n,setupState:s,data:r,props:i,accessCache:o,type:a,appContext:l}=e;let c;if(t[0]!=="$"){const w=o[t];if(w!==void 0)switch(w){case 1:return s[t];case 2:return r[t];case 4:return n[t];case 3:return i[t]}else{if(cr(s,t))return o[t]=1,s[t];if(r!==se&&ge(r,t))return o[t]=2,r[t];if((c=e.propsOptions[0])&&ge(c,t))return o[t]=3,i[t];if(n!==se&&ge(n,t))return o[t]=4,n[t];o[t]=0}}const u=zn[t];let p,g;if(u)return t==="$attrs"&&Ue(e.attrs,"get",""),u(e);if((p=a.__cssModules)&&(p=p[t]))return p;if(n!==se&&ge(n,t))return o[t]=4,n[t];if(g=l.config.globalProperties,ge(g,t))return g[t]},set({_:e},t,n){const{data:s,setupState:r,ctx:i}=e;return cr(r,t)?(r[t]=n,!0):s!==se&&ge(s,t)?(s[t]=n,!0):ge(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(i[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:s,appContext:r,propsOptions:i}},o){let a;return!!n[o]||e!==se&&ge(e,o)||cr(t,o)||(a=i[0])&&ge(a,o)||ge(s,o)||ge(zn,o)||ge(r.config.globalProperties,o)},defineProperty(e,t,n){return n.get!=null?e._.accessCache[t]=0:ge(n,"value")&&this.set(e,t,n.value,null),Reflect.defineProperty(e,t,n)}};function Wi(){return{app:null,config:{isNativeTag:Dl,performance:!1,globalProperties:{},optionMergeStrategies:{},errorHandler:void 0,warnHandler:void 0,compilerOptions:{}},mixins:[],components:{},directives:{},provides:Object.create(null),optionsCache:new WeakMap,propsCache:new WeakMap,emitsCache:new WeakMap}}let Ba=0;function Ha(e,t){return function(s,r=null){be(s)||(s=ht({},s)),r!=null&&!Ae(r)&&(r=null);const i=Wi(),o=new WeakSet,a=[];let l=!1;const c=i.app={_uid:Ba++,_component:s,_props:r,_container:null,_context:i,_instance:null,version:Su,get config(){return i.config},set config(u){},use(u,...p){return o.has(u)||(u&&be(u.install)?(o.add(u),u.install(c,...p)):be(u)&&(o.add(u),u(c,...p))),c},mixin(u){return c},component(u,p){return p?(i.components[u]=p,c):i.components[u]},directive(u,p){return p?(i.directives[u]=p,c):i.directives[u]},mount(u,p,g){if(!l){const w=c._ceVNode||Me(s,r);return w.appContext=i,g===!0?g="svg":g===!1&&(g=void 0),e(w,u,g),l=!0,c._container=u,u.__vue_app__=c,Es(w.component)}},onUnmount(u){a.push(u)},unmount(){l&&(_t(a,c._instance,16),e(null,c._container),delete c._container.__vue_app__)},provide(u,p){return i.provides[u]=p,c},runWithContext(u){const p=yn;yn=c;try{return u()}finally{yn=p}}};return c}}let yn=null;function za(e,t,n=!1){const s=co();if(s||yn){let r=yn?yn._context.provides:s?s.parent==null||s.ce?s.vnode.appContext&&s.vnode.appContext.provides:s.parent.provides:void 0;if(r&&e in r)return r[e];if(arguments.length>1)return n&&be(t)?t.call(s&&s.proxy):t}}const Gi={},Ki=()=>Object.create(Gi),Yi=e=>Object.getPrototypeOf(e)===Gi;function Ua(e,t,n,s=!1){const r={},i=Ki();e.propsDefaults=Object.create(null),Zi(e,t,r,i);for(const o in e.propsOptions[0])o in r||(r[o]=void 0);n?e.props=s?r:pa(r):e.type.props?e.props=r:e.props=i,e.attrs=i}function ja(e,t,n,s){const{props:r,attrs:i,vnode:{patchFlag:o}}=e,a=oe(r),[l]=e.propsOptions;let c=!1;if((s||o>0)&&!(o&16)){if(o&8){const u=e.vnode.dynamicProps;for(let p=0;pe==="_"||e==="__"||e==="_ctx"||e==="$stable",pr=e=>Q(e)?e.map(Et):[Et(e)],qa=(e,t,n)=>{if(t._n)return t;const s=Ni((...r)=>pr(t(...r)),n);return s._c=!1,s},Qi=(e,t,n)=>{const s=e._ctx;for(const r in e){if(dr(r))continue;const i=e[r];if(be(i))t[r]=qa(r,i,s);else if(i!=null){const o=pr(i);t[r]=()=>o}}},Ji=(e,t)=>{const n=pr(t);e.slots.default=()=>n},eo=(e,t,n)=>{for(const s in t)(n||!dr(s))&&(e[s]=t[s])},Wa=(e,t,n)=>{const s=e.slots=Ki();if(e.vnode.shapeFlag&32){const r=t.__;r&&Us(s,"__",r,!0);const i=t._;i?(eo(s,t,n),n&&Us(s,"_",i,!0)):Qi(t,s)}else t&&Ji(e,t)},Ga=(e,t,n)=>{const{vnode:s,slots:r}=e;let i=!0,o=se;if(s.shapeFlag&32){const a=t._;a?n&&a===1?i=!1:eo(r,t,n):(i=!t.$stable,Qi(t,r)),o=t}else t&&(Ji(e,t),o={default:1});if(i)for(const a in r)!dr(a)&&o[a]==null&&delete r[a]},nt=au;function Ka(e){return Ya(e)}function Ya(e,t){const n=rs();n.__VUE__=!0;const{insert:s,remove:r,patchProp:i,createElement:o,createText:a,createComment:l,setText:c,setElementText:u,parentNode:p,nextSibling:g,setScopeId:w=Qt,insertStaticContent:E}=e,m=(f,h,b,k=null,v=null,_=null,M=void 0,C=null,R=!!h.dynamicChildren)=>{if(f===h)return;f&&!on(f,h)&&(k=le(f),pe(f,v,_,!0),f=null),h.patchFlag===-2&&(R=!1,h.dynamicChildren=null);const{type:S,ref:H,shapeFlag:L}=h;switch(S){case vs:A(f,h,b,k);break;case Ke:T(f,h,b,k);break;case gr:f==null&&W(h,b,k,M);break;case Be:$(f,h,b,k,v,_,M,C,R);break;default:L&1?z(f,h,b,k,v,_,M,C,R):L&6?Z(f,h,b,k,v,_,M,C,R):(L&64||L&128)&&S.process(f,h,b,k,v,_,M,C,R,ze)}H!=null&&v?Fn(H,f&&f.ref,_,h||f,!h):H==null&&f&&f.ref!=null&&Fn(f.ref,null,_,f,!0)},A=(f,h,b,k)=>{if(f==null)s(h.el=a(h.children),b,k);else{const v=h.el=f.el;h.children!==f.children&&c(v,h.children)}},T=(f,h,b,k)=>{f==null?s(h.el=l(h.children||""),b,k):h.el=f.el},W=(f,h,b,k)=>{[f.el,f.anchor]=E(f.children,h,b,k,f.el,f.anchor)},K=({el:f,anchor:h},b,k)=>{let v;for(;f&&f!==h;)v=g(f),s(f,b,k),f=v;s(h,b,k)},O=({el:f,anchor:h})=>{let b;for(;f&&f!==h;)b=g(f),r(f),f=b;r(h)},z=(f,h,b,k,v,_,M,C,R)=>{h.type==="svg"?M="svg":h.type==="math"&&(M="mathml"),f==null?P(h,b,k,v,_,M,C,R):j(f,h,v,_,M,C,R)},P=(f,h,b,k,v,_,M,C)=>{let R,S;const{props:H,shapeFlag:L,transition:U,dirs:G}=f;if(R=f.el=o(f.type,_,H&&H.is,H),L&8?u(R,f.children):L&16&&re(f.children,R,null,k,v,hr(f,_),M,C),G&&nn(f,null,k,"created"),I(R,f,f.scopeId,M,k),H){for(const de in H)de!=="value"&&!Cn(de)&&i(R,de,null,H[de],_,k);"value"in H&&i(R,"value",null,H.value,_),(S=H.onVnodeBeforeMount)&&At(S,k,f)}G&&nn(f,null,k,"beforeMount");const ee=Za(v,U);ee&&U.beforeEnter(R),s(R,h,b),((S=H&&H.onVnodeMounted)||ee||G)&&nt(()=>{S&&At(S,k,f),ee&&U.enter(R),G&&nn(f,null,k,"mounted")},v)},I=(f,h,b,k,v)=>{if(b&&w(f,b),k)for(let _=0;_{for(let S=R;S{const C=h.el=f.el;let{patchFlag:R,dynamicChildren:S,dirs:H}=h;R|=f.patchFlag&16;const L=f.props||se,U=h.props||se;let G;if(b&&sn(b,!1),(G=U.onVnodeBeforeUpdate)&&At(G,b,h,f),H&&nn(h,f,b,"beforeUpdate"),b&&sn(b,!0),(L.innerHTML&&U.innerHTML==null||L.textContent&&U.textContent==null)&&u(C,""),S?te(f.dynamicChildren,S,C,b,k,hr(h,v),_):M||We(f,h,C,null,b,k,hr(h,v),_,!1),R>0){if(R&16)ue(C,L,U,b,v);else if(R&2&&L.class!==U.class&&i(C,"class",null,U.class,v),R&4&&i(C,"style",L.style,U.style,v),R&8){const ee=h.dynamicProps;for(let de=0;de{G&&At(G,b,h,f),H&&nn(h,f,b,"updated")},k)},te=(f,h,b,k,v,_,M)=>{for(let C=0;C{if(h!==b){if(h!==se)for(const _ in h)!Cn(_)&&!(_ in b)&&i(f,_,h[_],null,v,k);for(const _ in b){if(Cn(_))continue;const M=b[_],C=h[_];M!==C&&_!=="value"&&i(f,_,C,M,v,k)}"value"in b&&i(f,"value",h.value,b.value,v)}},$=(f,h,b,k,v,_,M,C,R)=>{const S=h.el=f?f.el:a(""),H=h.anchor=f?f.anchor:a("");let{patchFlag:L,dynamicChildren:U,slotScopeIds:G}=h;G&&(C=C?C.concat(G):G),f==null?(s(S,b,k),s(H,b,k),re(h.children||[],b,H,v,_,M,C,R)):L>0&&L&64&&U&&f.dynamicChildren?(te(f.dynamicChildren,U,b,v,_,M,C),(h.key!=null||v&&h===v.subTree)&&to(f,h,!0)):We(f,h,b,H,v,_,M,C,R)},Z=(f,h,b,k,v,_,M,C,R)=>{h.slotScopeIds=C,f==null?h.shapeFlag&512?v.ctx.activate(h,b,k,M,R):Y(h,b,k,v,_,M,R):B(f,h,R)},Y=(f,h,b,k,v,_,M)=>{const C=f.component=gu(f,k,v);if(ar(f)&&(C.ctx.renderer=ze),mu(C,!1,M),C.asyncDep){if(v&&v.registerDep(C,ce,M),!f.el){const R=C.subTree=Me(Ke);T(null,R,h,b),f.placeholder=R.el}}else ce(C,f,h,b,v,_,M)},B=(f,h,b)=>{const k=h.component=f.component;if(ou(f,h,b))if(k.asyncDep&&!k.asyncResolved){Se(k,h,b);return}else k.next=h,k.update();else h.el=f.el,k.vnode=h},ce=(f,h,b,k,v,_,M)=>{const C=()=>{if(f.isMounted){let{next:L,bu:U,u:G,parent:ee,vnode:de}=f;{const it=no(f);if(it){L&&(L.el=de.el,Se(f,L,M)),it.asyncDep.then(()=>{f.isUnmounted||C()});return}}let ne=L,Te;sn(f,!1),L?(L.el=de.el,Se(f,L,M)):L=de,U&&ss(U),(Te=L.props&&L.props.onVnodeBeforeUpdate)&&At(Te,ee,L,de),sn(f,!0);const Oe=ro(f),rt=f.subTree;f.subTree=Oe,m(rt,Oe,p(rt.el),le(rt),f,v,_),L.el=Oe.el,ne===null&&lu(f,Oe.el),G&&nt(G,v),(Te=L.props&&L.props.onVnodeUpdated)&&nt(()=>At(Te,ee,L,de),v)}else{let L;const{el:U,props:G}=h,{bm:ee,m:de,parent:ne,root:Te,type:Oe}=f,rt=Bn(h);sn(f,!1),ee&&ss(ee),!rt&&(L=G&&G.onVnodeBeforeMount)&&At(L,ne,h),sn(f,!0);{Te.ce&&Te.ce._def.shadowRoot!==!1&&Te.ce._injectChildStyle(Oe);const it=f.subTree=ro(f);m(null,it,b,k,f,v,_),h.el=it.el}if(de&&nt(de,v),!rt&&(L=G&&G.onVnodeMounted)){const it=h;nt(()=>At(L,ne,it),v)}(h.shapeFlag&256||ne&&Bn(ne.vnode)&&ne.vnode.shapeFlag&256)&&f.a&&nt(f.a,v),f.isMounted=!0,h=b=k=null}};f.scope.on();const R=f.effect=new ci(C);f.scope.off();const S=f.update=R.run.bind(R),H=f.job=R.runIfDirty.bind(R);H.i=f,H.id=f.uid,R.scheduler=()=>ir(H),sn(f,!0),S()},Se=(f,h,b)=>{h.component=f;const k=f.vnode.props;f.vnode=h,f.next=null,ja(f,h.props,k,b),Ga(f,h.children,b),It(),Li(f),Mt()},We=(f,h,b,k,v,_,M,C,R=!1)=>{const S=f&&f.children,H=f?f.shapeFlag:0,L=h.children,{patchFlag:U,shapeFlag:G}=h;if(U>0){if(U&128){fe(S,L,b,k,v,_,M,C,R);return}else if(U&256){xt(S,L,b,k,v,_,M,C,R);return}}G&8?(H&16&&me(S,v,_),L!==S&&u(b,L)):H&16?G&16?fe(S,L,b,k,v,_,M,C,R):me(S,v,_,!0):(H&8&&u(b,""),G&16&&re(L,b,k,v,_,M,C,R))},xt=(f,h,b,k,v,_,M,C,R)=>{f=f||pt,h=h||pt;const S=f.length,H=h.length,L=Math.min(S,H);let U;for(U=0;UH?me(f,v,_,!0,!1,L):re(h,b,k,v,_,M,C,R,L)},fe=(f,h,b,k,v,_,M,C,R)=>{let S=0;const H=h.length;let L=f.length-1,U=H-1;for(;S<=L&&S<=U;){const G=f[S],ee=h[S]=R?Kt(h[S]):Et(h[S]);if(on(G,ee))m(G,ee,b,null,v,_,M,C,R);else break;S++}for(;S<=L&&S<=U;){const G=f[L],ee=h[U]=R?Kt(h[U]):Et(h[U]);if(on(G,ee))m(G,ee,b,null,v,_,M,C,R);else break;L--,U--}if(S>L){if(S<=U){const G=U+1,ee=GU)for(;S<=L;)pe(f[S],v,_,!0),S++;else{const G=S,ee=S,de=new Map;for(S=ee;S<=U;S++){const $e=h[S]=R?Kt(h[S]):Et(h[S]);$e.key!=null&&de.set($e.key,S)}let ne,Te=0;const Oe=U-ee+1;let rt=!1,it=0;const Ft=new Array(Oe);for(S=0;S=Oe){pe($e,v,_,!0);continue}let Xe;if($e.key!=null)Xe=de.get($e.key);else for(ne=ee;ne<=U;ne++)if(Ft[ne-ee]===0&&on($e,h[ne])){Xe=ne;break}Xe===void 0?pe($e,v,_,!0):(Ft[Xe-ee]=S+1,Xe>=it?it=Xe:rt=!0,m($e,h[Xe],b,null,v,_,M,C,R),Te++)}const Qn=rt?Xa(Ft):pt;for(ne=Qn.length-1,S=Oe-1;S>=0;S--){const $e=ee+S,Xe=h[$e],ot=h[$e+1],Bt=$e+1{const{el:_,type:M,transition:C,children:R,shapeFlag:S}=f;if(S&6){N(f.component.subTree,h,b,k);return}if(S&128){f.suspense.move(h,b,k);return}if(S&64){M.move(f,h,b,ze);return}if(M===Be){s(_,h,b);for(let L=0;LC.enter(_),v);else{const{leave:L,delayLeave:U,afterLeave:G}=C,ee=()=>{f.ctx.isUnmounted?r(_):s(_,h,b)},de=()=>{L(_,()=>{ee(),G&&G()})};U?U(_,ee,de):de()}else s(_,h,b)},pe=(f,h,b,k=!1,v=!1)=>{const{type:_,props:M,ref:C,children:R,dynamicChildren:S,shapeFlag:H,patchFlag:L,dirs:U,cacheIndex:G}=f;if(L===-2&&(v=!1),C!=null&&(It(),Fn(C,null,b,f,!0),Mt()),G!=null&&(h.renderCache[G]=void 0),H&256){h.ctx.deactivate(f);return}const ee=H&1&&U,de=!Bn(f);let ne;if(de&&(ne=M&&M.onVnodeBeforeUnmount)&&At(ne,h,f),H&6)ve(f.component,b,k);else{if(H&128){f.suspense.unmount(b,k);return}ee&&nn(f,null,h,"beforeUnmount"),H&64?f.type.remove(f,h,b,ze,k):S&&!S.hasOnce&&(_!==Be||L>0&&L&64)?me(S,h,b,!1,!0):(_===Be&&L&384||!v&&H&16)&&me(R,h,b),k&&he(f)}(de&&(ne=M&&M.onVnodeUnmounted)||ee)&&nt(()=>{ne&&At(ne,h,f),ee&&nn(f,null,h,"unmounted")},b)},he=f=>{const{type:h,el:b,anchor:k,transition:v}=f;if(h===Be){ke(b,k);return}if(h===gr){O(f);return}const _=()=>{r(b),v&&!v.persisted&&v.afterLeave&&v.afterLeave()};if(f.shapeFlag&1&&v&&!v.persisted){const{leave:M,delayLeave:C}=v,R=()=>M(b,_);C?C(f.el,_,R):R()}else _()},ke=(f,h)=>{let b;for(;f!==h;)b=g(f),r(f),f=b;r(h)},ve=(f,h,b)=>{const{bum:k,scope:v,job:_,subTree:M,um:C,m:R,a:S,parent:H,slots:{__:L}}=f;so(R),so(S),k&&ss(k),H&&Q(L)&&L.forEach(U=>{H.renderCache[U]=void 0}),v.stop(),_&&(_.flags|=8,pe(M,f,h,b)),C&&nt(C,h),nt(()=>{f.isUnmounted=!0},h),h&&h.pendingBranch&&!h.isUnmounted&&f.asyncDep&&!f.asyncResolved&&f.suspenseId===h.pendingId&&(h.deps--,h.deps===0&&h.resolve())},me=(f,h,b,k=!1,v=!1,_=0)=>{for(let M=_;M{if(f.shapeFlag&6)return le(f.component.subTree);if(f.shapeFlag&128)return f.suspense.next();const h=g(f.anchor||f.el),b=h&&h[Ia];return b?g(b):h};let yt=!1;const Ct=(f,h,b)=>{f==null?h._vnode&&pe(h._vnode,null,null,!0):m(h._vnode||null,f,h,null,null,null,b),h._vnode=f,yt||(yt=!0,Li(),Oi(),yt=!1)},ze={p:m,um:pe,m:N,r:he,mt:Y,mc:re,pc:We,pbc:te,n:le,o:e};return{render:Ct,hydrate:void 0,createApp:Ha(Ct)}}function hr({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function sn({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Za(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function to(e,t,n=!1){const s=e.children,r=t.children;if(Q(s)&&Q(r))for(let i=0;i>1,e[n[a]]0&&(t[s]=n[i-1]),n[i]=s)}}for(i=n.length,o=n[i-1];i-- >0;)n[i]=o,o=t[o];return n}function no(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:no(t)}function so(e){if(e)for(let t=0;tza(Qa);function rn(e,t,n){return eu(e,t,n)}function eu(e,t,n=se){const{immediate:s,deep:r,flush:i,once:o}=n,a=ht({},n),l=t&&s||!t&&i!=="post";let c;if(Vn){if(i==="sync"){const w=Ja();c=w.__watcherHandles||(w.__watcherHandles=[])}else if(!l){const w=()=>{};return w.stop=Qt,w.resume=Qt,w.pause=Qt,w}}const u=Yt;a.call=(w,E,m)=>_t(w,u,E,m);let p=!1;i==="post"?a.scheduler=w=>{nt(w,u&&u.suspense)}:i!=="sync"&&(p=!0,a.scheduler=(w,E)=>{E?w():ir(w)}),a.augmentJob=w=>{t&&(w.flags|=4),p&&(w.flags|=2,u&&(w.id=u.uid,w.i=u))};const g=_a(e,t,a);return Vn&&(c?c.push(g):l&&g()),g}const tu=(e,t)=>t==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${Ut(t)}Modifiers`]||e[`${Jt(t)}Modifiers`];function nu(e,t,...n){if(e.isUnmounted)return;const s=e.vnode.props||se;let r=n;const i=t.startsWith("update:"),o=i&&tu(s,t.slice(7));o&&(o.trim&&(r=n.map(u=>Ce(u)?u.trim():u)),o.number&&(r=n.map(js)));let a,l=s[a=zs(t)]||s[a=zs(Ut(t))];!l&&i&&(l=s[a=zs(Jt(t))]),l&&_t(l,e,6,r);const c=s[a+"Once"];if(c){if(!e.emitted)e.emitted={};else if(e.emitted[a])return;e.emitted[a]=!0,_t(c,e,6,r)}}function su(e,t,n=!1){const s=t.emitsCache,r=s.get(e);if(r!==void 0)return r;const i=e.emits;let o={};return i?(Q(i)?i.forEach(a=>o[a]=null):ht(o,i),Ae(e)&&s.set(e,o),o):(Ae(e)&&s.set(e,null),null)}function ws(e,t){return!e||!es(t)?!1:(t=t.slice(2).replace(/Once$/,""),ge(e,t[0].toLowerCase()+t.slice(1))||ge(e,Jt(t))||ge(e,t))}function Ep(){}function ro(e){const{type:t,vnode:n,proxy:s,withProxy:r,propsOptions:[i],slots:o,attrs:a,emit:l,render:c,renderCache:u,props:p,data:g,setupState:w,ctx:E,inheritAttrs:m}=e,A=ms(e);let T,W;try{if(n.shapeFlag&4){const O=r||s,z=O;T=Et(c.call(z,O,u,p,w,g,E)),W=a}else{const O=t;T=Et(O.length>1?O(p,{attrs:a,slots:o,emit:l}):O(p,null)),W=t.props?a:ru(a)}}catch(O){Un.length=0,hs(O,e,1),T=Me(Ke)}let K=T;if(W&&m!==!1){const O=Object.keys(W),{shapeFlag:z}=K;O.length&&z&7&&(i&&O.some(Bs)&&(W=iu(W,i)),K=Gt(K,W,!1,!0))}return n.dirs&&(K=Gt(K,null,!1,!0),K.dirs=K.dirs?K.dirs.concat(n.dirs):n.dirs),n.transition&&Nn(K,n.transition),T=K,ms(A),T}const ru=e=>{let t;for(const n in e)(n==="class"||n==="style"||es(n))&&((t||(t={}))[n]=e[n]);return t},iu=(e,t)=>{const n={};for(const s in e)(!Bs(s)||!(s.slice(9)in t))&&(n[s]=e[s]);return n};function ou(e,t,n){const{props:s,children:r,component:i}=e,{props:o,children:a,patchFlag:l}=t,c=i.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&l>=0){if(l&1024)return!0;if(l&16)return s?io(s,o,c):!!o;if(l&8){const u=t.dynamicProps;for(let p=0;pe.__isSuspense;function au(e,t){t&&t.pendingBranch?Q(e)?t.effects.push(...e):t.effects.push(e):Ca(e)}const Be=Symbol.for("v-fgt"),vs=Symbol.for("v-txt"),Ke=Symbol.for("v-cmt"),gr=Symbol.for("v-stc"),Un=[];let st=null;function F(e=!1){Un.push(st=e?null:[])}function uu(){Un.pop(),st=Un[Un.length-1]||null}let jn=1;function lo(e,t=!1){jn+=e,e<0&&st&&t&&(st.hasOnce=!0)}function ao(e){return e.dynamicChildren=jn>0?st||pt:null,uu(),jn>0&&st&&st.push(e),e}function q(e,t,n,s,r,i){return ao(x(e,t,n,s,r,i,!0))}function St(e,t,n,s,r){return ao(Me(e,t,n,s,r,!0))}function _s(e){return e?e.__v_isVNode===!0:!1}function on(e,t){return e.type===t.type&&e.key===t.key}const uo=({key:e})=>e!=null?e:null,ks=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?Ce(e)||je(e)||be(e)?{i:at,r:e,k:t,f:!!n}:e:null);function x(e,t=null,n=null,s=0,r=null,i=e===Be?0:1,o=!1,a=!1){const l={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&uo(t),ref:t&&ks(t),scopeId:Di,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:i,patchFlag:s,dynamicProps:r,dynamicChildren:null,appContext:null,ctx:at};return a?(mr(l,n),i&128&&e.normalize(l)):n&&(l.shapeFlag|=Ce(n)?8:16),jn>0&&!o&&st&&(l.patchFlag>0||i&6)&&l.patchFlag!==32&&st.push(l),l}const Me=cu;function cu(e,t=null,n=null,s=0,r=null,i=!1){if((!e||e===Na)&&(e=Ke),_s(e)){const a=Gt(e,t,!0);return n&&mr(a,n),jn>0&&!i&&st&&(a.shapeFlag&6?st[st.indexOf(e)]=a:st.push(a)),a.patchFlag=-2,a}if(ku(e)&&(e=e.__vccOpts),t){t=fu(t);let{class:a,style:l}=t;a&&!Ce(a)&&(t.class=ye(a)),Ae(l)&&(sr(l)&&!Q(l)&&(l=ht({},l)),t.style=Vs(l))}const o=Ce(e)?1:oo(e)?128:Fi(e)?64:Ae(e)?4:be(e)?2:0;return x(e,t,n,s,r,o,i,!0)}function fu(e){return e?sr(e)||Yi(e)?ht({},e):e:null}function Gt(e,t,n=!1,s=!1){const{props:r,ref:i,patchFlag:o,children:a,transition:l}=e,c=t?du(r||{},t):r,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:c,key:c&&uo(c),ref:t&&t.ref?n&&i?Q(i)?i.concat(ks(t)):[i,ks(t)]:ks(t):i,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:a,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Be?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:l,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Gt(e.ssContent),ssFallback:e.ssFallback&&Gt(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return l&&s&&Nn(u,l.clone(u)),u}function Ts(e=" ",t=0){return Me(vs,null,e,t)}function Ve(e="",t=!1){return t?(F(),St(Ke,null,e)):Me(Ke,null,e)}function Et(e){return e==null||typeof e=="boolean"?Me(Ke):Q(e)?Me(Be,null,e.slice()):_s(e)?Kt(e):Me(vs,null,String(e))}function Kt(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Gt(e)}function mr(e,t){let n=0;const{shapeFlag:s}=e;if(t==null)t=null;else if(Q(t))n=16;else if(typeof t=="object")if(s&65){const r=t.default;r&&(r._c&&(r._d=!1),mr(e,r()),r._c&&(r._d=!0));return}else{n=32;const r=t._;!r&&!Yi(t)?t._ctx=at:r===3&&at&&(at.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else be(t)?(t={default:t,_ctx:at},n=32):(t=String(t),s&64?(n=16,t=[Ts(t)]):n=8);e.children=t,e.shapeFlag|=n}function du(...e){const t={};for(let n=0;nYt||at;let Ss,br;{const e=rs(),t=(n,s)=>{let r;return(r=e[n])||(r=e[n]=[]),r.push(s),i=>{r.length>1?r.forEach(o=>o(i)):r[0](i)}};Ss=t("__VUE_INSTANCE_SETTERS__",n=>Yt=n),br=t("__VUE_SSR_SETTERS__",n=>Vn=n)}const xr=e=>{const t=Yt;return Ss(e),e.scope.on(),()=>{e.scope.off(),Ss(t)}},fo=()=>{Yt&&Yt.scope.off(),Ss(null)};function po(e){return e.vnode.shapeFlag&4}let Vn=!1;function mu(e,t=!1,n=!1){t&&br(t);const{props:s,children:r}=e.vnode,i=po(e);Ua(e,s,i,t),Wa(e,r,n||t);const o=i?bu(e,t):void 0;return t&&br(!1),o}function bu(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,Fa);const{setup:s}=n;if(s){It();const r=e.setupContext=s.length>1?yu(e):null,i=xr(e),o=mn(s,e,0,[e.props,r]),a=ni(o);if(Mt(),i(),(a||e.sp)&&!Bn(e)&&$a(e),a){if(o.then(fo,fo),t)return o.then(l=>{ho(e,l)}).catch(l=>{hs(l,e,0)});e.asyncDep=o}else ho(e,o)}else go(e)}function ho(e,t,n){be(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:Ae(t)&&(e.setupState=Ci(t)),go(e)}function go(e,t,n){const s=e.type;e.render||(e.render=s.render||Qt)}const xu={get(e,t){return Ue(e,"get",""),e[t]}};function yu(e){const t=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,xu),slots:e.slots,emit:e.emit,expose:t}}function Es(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(Ci(ha(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in zn)return zn[n](e)},has(t,n){return n in t||n in zn}})):e.proxy}const wu=/(?:^|[-_])(\w)/g,vu=e=>e.replace(wu,t=>t.toUpperCase()).replace(/[-_]/g,"");function _u(e,t=!0){return be(e)?e.displayName||e.name:e.name||t&&e.__name}function mo(e,t,n=!1){let s=_u(t);if(!s&&t.__file){const r=t.__file.match(/([^/\\]+)\.\w+$/);r&&(s=r[1])}if(!s&&e&&e.parent){const r=i=>{for(const o in i)if(i[o]===t)return o};s=r(e.components||e.parent.type.components)||r(e.appContext.components)}return s?vu(s):n?"App":"Anonymous"}function ku(e){return be(e)&&"__vccOpts"in e}const Re=(e,t)=>wa(e,t,Vn);function Tu(e,t,n){const s=arguments.length;return s===2?Ae(t)&&!Q(t)?_s(t)?Me(e,null,[t]):Me(e,t):Me(e,null,t):(s>3?n=Array.prototype.slice.call(arguments,2):s===3&&_s(n)&&(n=[n]),Me(e,t,n))}const Su="3.5.18";let yr;const bo=typeof window!="undefined"&&window.trustedTypes;if(bo)try{yr=bo.createPolicy("vue",{createHTML:e=>e})}catch{}const xo=yr?e=>yr.createHTML(e):e=>e,Eu="http://www.w3.org/2000/svg",Au="http://www.w3.org/1998/Math/MathML",Dt=typeof document!="undefined"?document:null,yo=Dt&&Dt.createElement("template"),Ru={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,s)=>{const r=t==="svg"?Dt.createElementNS(Eu,e):t==="mathml"?Dt.createElementNS(Au,e):n?Dt.createElement(e,{is:n}):Dt.createElement(e);return e==="select"&&s&&s.multiple!=null&&r.setAttribute("multiple",s.multiple),r},createText:e=>Dt.createTextNode(e),createComment:e=>Dt.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Dt.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,s,r,i){const o=n?n.previousSibling:t.lastChild;if(r&&(r===i||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),n),!(r===i||!(r=r.nextSibling)););else{yo.innerHTML=xo(s==="svg"?`${e}`:s==="mathml"?`${e}`:e);const a=yo.content;if(s==="svg"||s==="mathml"){const l=a.firstChild;for(;l.firstChild;)a.appendChild(l.firstChild);a.removeChild(l)}t.insertBefore(a,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Zt="transition",qn="animation",Wn=Symbol("_vtc"),wo={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Cu=ht({},Bi,wo),Pu=(e=>(e.displayName="Transition",e.props=Cu,e))((e,{slots:t})=>Tu(Oa,Iu(e),t)),ln=(e,t=[])=>{Q(e)?e.forEach(n=>n(...t)):e&&e(...t)},vo=e=>e?Q(e)?e.some(t=>t.length>1):e.length>1:!1;function Iu(e){const t={};for(const $ in e)$ in wo||(t[$]=e[$]);if(e.css===!1)return t;const{name:n="v",type:s,duration:r,enterFromClass:i=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:a=`${n}-enter-to`,appearFromClass:l=i,appearActiveClass:c=o,appearToClass:u=a,leaveFromClass:p=`${n}-leave-from`,leaveActiveClass:g=`${n}-leave-active`,leaveToClass:w=`${n}-leave-to`}=e,E=Mu(r),m=E&&E[0],A=E&&E[1],{onBeforeEnter:T,onEnter:W,onEnterCancelled:K,onLeave:O,onLeaveCancelled:z,onBeforeAppear:P=T,onAppear:I=W,onAppearCancelled:re=K}=t,j=($,Z,Y,B)=>{$._enterCancelled=B,an($,Z?u:a),an($,Z?c:o),Y&&Y()},te=($,Z)=>{$._isLeaving=!1,an($,p),an($,w),an($,g),Z&&Z()},ue=$=>(Z,Y)=>{const B=$?I:W,ce=()=>j(Z,$,Y);ln(B,[Z,ce]),_o(()=>{an(Z,$?l:i),Nt(Z,$?u:a),vo(B)||ko(Z,s,m,ce)})};return ht(t,{onBeforeEnter($){ln(T,[$]),Nt($,i),Nt($,o)},onBeforeAppear($){ln(P,[$]),Nt($,l),Nt($,c)},onEnter:ue(!1),onAppear:ue(!0),onLeave($,Z){$._isLeaving=!0;const Y=()=>te($,Z);Nt($,p),$._enterCancelled?(Nt($,g),Eo()):(Eo(),Nt($,g)),_o(()=>{$._isLeaving&&(an($,p),Nt($,w),vo(O)||ko($,s,A,Y))}),ln(O,[$,Y])},onEnterCancelled($){j($,!1,void 0,!0),ln(K,[$])},onAppearCancelled($){j($,!0,void 0,!0),ln(re,[$])},onLeaveCancelled($){te($),ln(z,[$])}})}function Mu(e){if(e==null)return null;if(Ae(e))return[wr(e.enter),wr(e.leave)];{const t=wr(e);return[t,t]}}function wr(e){return zl(e)}function Nt(e,t){t.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[Wn]||(e[Wn]=new Set)).add(t)}function an(e,t){t.split(/\s+/).forEach(s=>s&&e.classList.remove(s));const n=e[Wn];n&&(n.delete(t),n.size||(e[Wn]=void 0))}function _o(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let Lu=0;function ko(e,t,n,s){const r=e._endId=++Lu,i=()=>{r===e._endId&&s()};if(n!=null)return setTimeout(i,n);const{type:o,timeout:a,propCount:l}=Ou(e,t);if(!o)return s();const c=o+"end";let u=0;const p=()=>{e.removeEventListener(c,g),i()},g=w=>{w.target===e&&++u>=l&&p()};setTimeout(()=>{u(n[E]||"").split(", "),r=s(`${Zt}Delay`),i=s(`${Zt}Duration`),o=To(r,i),a=s(`${qn}Delay`),l=s(`${qn}Duration`),c=To(a,l);let u=null,p=0,g=0;t===Zt?o>0&&(u=Zt,p=o,g=i.length):t===qn?c>0&&(u=qn,p=c,g=l.length):(p=Math.max(o,c),u=p>0?o>c?Zt:qn:null,g=u?u===Zt?i.length:l.length:0);const w=u===Zt&&/\b(transform|all)(,|$)/.test(s(`${Zt}Property`).toString());return{type:u,timeout:p,propCount:g,hasTransform:w}}function To(e,t){for(;e.lengthSo(n)+So(e[s])))}function So(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function Eo(){return document.body.offsetHeight}function $u(e,t,n){const s=e[Wn];s&&(t=(t?[t,...s]:[...s]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const Ao=Symbol("_vod"),Du=Symbol("_vsh"),Nu=Symbol(""),Fu=/(^|;)\s*display\s*:/;function Bu(e,t,n){const s=e.style,r=Ce(n);let i=!1;if(n&&!r){if(t)if(Ce(t))for(const o of t.split(";")){const a=o.slice(0,o.indexOf(":")).trim();n[a]==null&&As(s,a,"")}else for(const o in t)n[o]==null&&As(s,o,"");for(const o in n)o==="display"&&(i=!0),As(s,o,n[o])}else if(r){if(t!==n){const o=s[Nu];o&&(n+=";"+o),s.cssText=n,i=Fu.test(n)}}else t&&e.removeAttribute("style");Ao in e&&(e[Ao]=i?s.display:"",e[Du]&&(s.display="none"))}const Ro=/\s*!important$/;function As(e,t,n){if(Q(n))n.forEach(s=>As(e,t,s));else if(n==null&&(n=""),t.startsWith("--"))e.setProperty(t,n);else{const s=Hu(e,t);Ro.test(n)?e.setProperty(Jt(s),n.replace(Ro,""),"important"):e[s]=n}}const Co=["Webkit","Moz","ms"],vr={};function Hu(e,t){const n=vr[t];if(n)return n;let s=Ut(t);if(s!=="filter"&&s in e)return vr[t]=s;s=ii(s);for(let r=0;r_r||(Vu.then(()=>_r=0),_r=Date.now());function Wu(e,t){const n=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=n.attached)return;_t(Gu(s,n.value),t,5,[s])};return n.value=e,n.attached=qu(),n}function Gu(e,t){if(Q(t)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},t.map(s=>r=>!r._stopped&&s&&s(r))}else return t}const $o=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Ku=(e,t,n,s,r,i)=>{const o=r==="svg";t==="class"?$u(e,s,o):t==="style"?Bu(e,n,s):es(t)?Bs(t)||Uu(e,t,n,s,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Yu(e,t,s,o))?(Mo(e,t,s),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&Io(e,t,s,o,i,t!=="value")):e._isVueCE&&(/[A-Z]/.test(t)||!Ce(s))?Mo(e,Ut(t),s,i,t):(t==="true-value"?e._trueValue=s:t==="false-value"&&(e._falseValue=s),Io(e,t,s,o))};function Yu(e,t,n,s){if(s)return!!(t==="innerHTML"||t==="textContent"||t in e&&$o(t)&&be(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return $o(t)&&Ce(n)?!1:t in e}const Do=e=>{const t=e.props["onUpdate:modelValue"]||!1;return Q(t)?n=>ss(t,n):t};function Zu(e){e.target.composing=!0}function No(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const kr=Symbol("_assign"),Xu={created(e,{modifiers:{lazy:t,trim:n,number:s}},r){e[kr]=Do(r);const i=s||r.props&&r.props.type==="number";wn(e,t?"change":"input",o=>{if(o.target.composing)return;let a=e.value;n&&(a=a.trim()),i&&(a=js(a)),e[kr](a)}),n&&wn(e,"change",()=>{e.value=e.value.trim()}),t||(wn(e,"compositionstart",Zu),wn(e,"compositionend",No),wn(e,"change",No))},mounted(e,{value:t}){e.value=t==null?"":t},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:s,trim:r,number:i}},o){if(e[kr]=Do(o),e.composing)return;const a=(i||e.type==="number")&&!/^0\d/.test(e.value)?js(e.value):e.value,l=t==null?"":t;a!==l&&(document.activeElement===e&&e.type!=="range"&&(s&&t===n||r&&e.value.trim()===l)||(e.value=l))}},Qu=["ctrl","shift","alt","meta"],Ju={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>Qu.some(n=>e[`${n}Key`]&&!t.includes(n))},ct=(e,t)=>{const n=e._withMods||(e._withMods={}),s=t.join(".");return n[s]||(n[s]=(r,...i)=>{for(let o=0;o{const t=tc().createApp(...e),{mount:n}=t;return t.mount=s=>{const r=rc(s);if(!r)return;const i=t._component;!be(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent="");const o=n(r,!1,sc(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),o},t};function sc(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function rc(e){return Ce(e)?document.querySelector(e):e}const ic=["aria-pressed"],oc={key:0,viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":"true"},lc={key:1,viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",fill:"none"},ac={__name:"ChatbotToggler",props:{isOpen:{type:Boolean,required:!0}},emits:["toggle"],setup(e){return(t,n)=>(F(),q("button",{class:"fixed bottom-5 right-5 z-9999 grid h-12 w-12 appearance-none place-items-center rounded-full border border-white/20 bg-gradient-to-br from-brand-500 to-brand-600 text-white shadow-[0_20px_36px_-20px_rgba(109,79,194,0.85)] transition-all duration-250 hover:-translate-y-0.5 hover:from-brand-600 hover:to-violet-700 hover:shadow-[0_22px_40px_-22px_rgba(109,79,194,1)] focus:outline-none max-[600px]:bottom-3 max-[600px]:right-3 max-[600px]:h-13 max-[600px]:w-13",style:{"border-radius":"9999px"},"aria-pressed":e.isOpen?"true":"false",onClick:n[0]||(n[0]=s=>t.$emit("toggle"))},[e.isOpen?(F(),q("svg",lc,n[2]||(n[2]=[x("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"},null,-1)]))):(F(),q("svg",oc,n[1]||(n[1]=[x("path",{d:"M4 4h16a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H8l-4 4v-4H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z",fill:"currentColor",stroke:"currentColor","stroke-width":"2","stroke-linecap":"miter","stroke-linejoin":"miter"},null,-1)])))],8,ic))}},uc={class:"chat-header relative flex min-h-14 items-center justify-between px-4 pb-2.5 pt-3 text-white sm:px-5"},cc={class:"flex min-w-0 flex-1 items-center gap-2 sm:gap-2.5"},fc={xmlns:"http://www.w3.org/2000/svg",width:"35",height:"35",viewBox:"0 0 1024 1024",class:"h-8 w-8 shrink-0 rounded-full bg-white p-1.5 shadow-md motion-safe:animate-soft-float",style:{fill:"#6d4fc2"}},dc={class:"ml-2 flex items-center gap-1.5"},pc=["title"],hc=["title","aria-label"],gc={key:0,viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},mc={key:1,viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},bc=["title","aria-label"],xc={key:0,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},yc={key:1,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},wc={key:2,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},vc={__name:"ChatHeader",props:{windowMode:{type:String,required:!0},autoReadEnabled:{type:Boolean,required:!0},activeTtsProvider:{type:String,required:!0}},emits:["close","cycleResize","toggleAutoRead"],setup(e){const t=e,n={default:"Compact",half:"Half Screen",full:"Full Screen"},s=Re(()=>n[t.windowMode]||"Compact"),r=Re(()=>t.windowMode==="default"?"Half Screen":t.windowMode==="half"?"Full Screen":"Compact"),i=Re(()=>t.activeTtsProvider==="polly"?"TTS: Polly":t.activeTtsProvider==="browser"?"TTS: Browser":"TTS: Off"),o=Re(()=>t.activeTtsProvider==="polly"?"bg-emerald-500/45":t.activeTtsProvider==="browser"?"bg-amber-500/45":"bg-slate-500/35");return(a,l)=>(F(),q("div",uc,[x("div",cc,[(F(),q("svg",fc,l[3]||(l[3]=[x("path",{d:"M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"},null,-1)]))),l[4]||(l[4]=x("h2",{class:"truncate text-xs font-semibold tracking-[0.01em] sm:text-base text-white/95"},"ChangAI from ERPGulf",-1))]),x("div",dc,[x("span",{class:ye(["hidden rounded-full border border-white/25 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-white/95 shadow-sm backdrop-blur-sm sm:inline",o.value]),title:`TTS provider: ${i.value}`},Qe(i.value),11,pc),x("button",{class:ye(["h-8 min-w-8 appearance-none items-center justify-center rounded-md border border-white/20 px-2 text-xs font-semibold text-white/90 transition-all duration-200 focus:outline-none sm:flex",e.autoReadEnabled?"bg-white/24 shadow-sm":"hover:bg-white/15"]),style:{"border-radius":"0.375rem"},title:e.autoReadEnabled?"Auto speech on":"Auto speech off","aria-label":e.autoReadEnabled?"Turn off auto speech":"Turn on auto speech",onClick:l[0]||(l[0]=c=>a.$emit("toggleAutoRead"))},[e.autoReadEnabled?(F(),q("svg",gc,l[5]||(l[5]=[x("path",{d:"M11 5L6 9H3v6h3l5 4V5z"},null,-1),x("path",{d:"M15 9a4 4 0 0 1 0 6"},null,-1),x("path",{d:"M18 7a7 7 0 0 1 0 10"},null,-1)]))):(F(),q("svg",mc,l[6]||(l[6]=[x("path",{d:"M11 5L6 9H3v6h3l5 4V5z"},null,-1),x("path",{d:"M22 9l-6 6"},null,-1),x("path",{d:"M16 9l6 6"},null,-1)])))],10,hc),x("button",{class:ye(["flex h-8 min-w-8 appearance-none items-center justify-center rounded-md border border-white/20 px-2 text-xs font-semibold text-white/90 transition-all duration-200 focus:outline-none","bg-white/20 shadow-sm hover:bg-white/25"]),style:{"border-radius":"0.375rem"},title:`Resize mode: ${s.value} (click to ${r.value})`,"aria-label":`Resize mode ${s.value}. Click to switch to ${r.value}`,onClick:l[1]||(l[1]=c=>a.$emit("cycleResize"))},[e.windowMode==="default"?(F(),q("svg",xc,l[7]||(l[7]=[x("rect",{x:"7",y:"8",width:"10",height:"8",rx:"2"},null,-1)]))):e.windowMode==="half"?(F(),q("svg",yc,l[8]||(l[8]=[x("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"},null,-1),x("path",{d:"M12 5v14"},null,-1)]))):(F(),q("svg",wc,l[9]||(l[9]=[x("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"},null,-1),x("path",{d:"M8 8H6v2M16 8h2v2M8 16H6v-2M16 16h2v-2"},null,-1)])))],8,bc),x("button",{class:"grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border border-white/20 text-white transition-all duration-200 hover:scale-105 hover:bg-white/20 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/70",style:{"border-radius":"9999px"},"aria-label":"Close chatbot",onClick:l[2]||(l[2]=c=>a.$emit("close"))},l[10]||(l[10]=[x("svg",{xmlns:"http://www.w3.org/2000/svg",height:"24",width:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},[x("path",{d:"M6 9l6 6 6-6"})],-1)]))])]))}},_c={class:"flex gap-1.5 border-b border-slate-200/80 px-2.5 pb-2.5 pt-1"},kc=["onClick"],Tc={class:"inline-flex items-center gap-1.5"},Sc={__name:"TabBar",props:{modelValue:{type:String,required:!0},debugEnabled:{type:Boolean,default:!1}},emits:["update:modelValue"],setup(e){const t=e,n=Re(()=>{const s=[{id:"chat",label:"Chats"},{id:"debug",label:"Debug"},{id:"support",label:"Support"},{id:"settings",label:"Settings"}];return t.debugEnabled?s:s.filter(r=>r.id!=="debug")});return(s,r)=>(F(),q("div",_c,[(F(!0),q(Be,null,ys(n.value,i=>(F(),q("button",{key:i.id,class:ye(["group min-w-0 flex-1 h-9 appearance-none rounded-lg border border-transparent bg-transparent px-2 text-xs font-semibold transition-all duration-200 focus:outline-none",e.modelValue===i.id?"border-white/30 bg-linear-to-r from-violet-300/36 via-indigo-300/30 to-sky-300/28 text-white shadow-[0_4px_10px_rgba(20,24,40,0.22)]":"text-white/80 hover:border-white/25 hover:bg-white/12 hover:text-white"]),onClick:o=>s.$emit("update:modelValue",i.id)},[x("span",Tc,[x("span",{class:ye(["h-1.5 w-1.5 rounded-full transition-colors duration-200",e.modelValue===i.id?"bg-white":"bg-white/40 group-hover:bg-white/70"])},null,2),Ts(" "+Qe(i.label),1)])],10,kc))),128))]))}},Ec=(e,t)=>{const n=e.__vccOpts||e;for(const[s,r]of t)n[s]=r;return n},Ac={},Rc={xmlns:"http://www.w3.org/2000/svg",width:"50",height:"50",viewBox:"0 0 1024 1024",class:"h-7.5 w-7.5 shrink-0 self-end rounded-full bg-gradient-to-br from-brand-500 to-brand-600 p-1.5 fill-white shadow-[0_10px_18px_-12px_rgba(109,79,194,0.85)]"};function Cc(e,t){return F(),q("svg",Rc,t[0]||(t[0]=[x("path",{d:"M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"},null,-1)]))}const Bo=Ec(Ac,[["render",Cc]]),Rs={PIPELINE:"changai.changai.api.v2.text2sql_pipeline_v2.run_text2sql_pipeline",SUPPORT:"changai.changai.api.v2.text2sql_pipeline_v2.support_bot",SETTINGS:"changai.changai.api.v2.text2sql_pipeline_v2.get_frontend_settings",TTS:"changai.changai.api.v2.text2sql_pipeline_v2.synthesize_tts"};function Tr(e,t={},n="actual"){return n==="test"?Promise.resolve({Bot:`[TEST MODE] ${JSON.stringify(t)}`}):!window.frappe||!window.frappe.call?Promise.reject(new Error("Frappe API is unavailable in actual mode.")):new Promise((s,r)=>{window.frappe.call({method:e,args:t,callback(i){s(i.message)},error(i){r(i)}})})}function Pc(e,t,n="actual",s=null,r){if(n==="test")return{promise:Promise.resolve({Bot:`[TEST MODE] ${JSON.stringify({user_question:e,chat_id:t,request_id:s,sendNonErptoAI:r})}`}),cancel:()=>!1};if(!window.frappe||!window.frappe.call)return{promise:Promise.reject(new Error("Frappe API is unavailable in actual mode.")),cancel:()=>!1};let i=null,o=!1;return{promise:new Promise((c,u)=>{i=window.frappe.call({method:Rs.PIPELINE,args:{user_question:e,chat_id:t,request_id:s,sendNonErptoAI:r},callback(p){o=!0,c(p.message)},error(p){o=!0,u(p)}})}),cancel:()=>o||!i||typeof i.abort!="function"?!1:(i.abort(),o=!0,!0)}}function Ic(e,t="actual"){return Tr(Rs.SUPPORT,{message:e},t)}function Mc(e="actual"){return Tr(Rs.SETTINGS,{},e)}function Lc(e,t="Zayd",n="actual"){return Tr(Rs.TTS,{text:e,voice_id:t},n)}function Sr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var un=Sr();function Ho(e){un=e}var cn={exec:()=>null};function ie(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(r,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(qe.caret,"$1"),n=n.replace(r,o),s},getRegex:()=>new RegExp(n,t)};return s}var Oc=((e="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},$c=/^(?:[ \t]*(?:\n|$))+/,Dc=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Nc=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Gn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Fc=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Er=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zo=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Uo=ie(zo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Bc=ie(zo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ar=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Hc=/^[^\n]+/,Rr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,zc=ie(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Rr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Uc=ie(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Er).getRegex(),Cs="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Cr=/|$))/,jc=ie("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Cr).replace("tag",Cs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),jo=ie(Ar).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Cs).getRegex(),Vc=ie(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",jo).getRegex(),Pr={blockquote:Vc,code:Dc,def:zc,fences:Nc,heading:Fc,hr:Gn,html:jc,lheading:Uo,list:Uc,newline:$c,paragraph:jo,table:cn,text:Hc},Vo=ie("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Cs).getRegex(),qc={...Pr,lheading:Bc,table:Vo,paragraph:ie(Ar).replace("hr",Gn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Vo).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Cs).getRegex()},Wc={...Pr,html:ie(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Cr).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:cn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ie(Ar).replace("hr",Gn).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",Uo).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Gc=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Kc=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,qo=/^( {2,}|\\)\n(?!\s*$)/,Yc=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Oc?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Go=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,ef=ie(Go,"u").replace(/punct/g,vn).getRegex(),tf=ie(Go,"u").replace(/punct/g,Wo).getRegex(),Ko="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",nf=ie(Ko,"gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Ps).replace(/punct/g,vn).getRegex(),sf=ie(Ko,"gu").replace(/notPunctSpace/g,Qc).replace(/punctSpace/g,Xc).replace(/punct/g,Wo).getRegex(),rf=ie("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Ps).replace(/punct/g,vn).getRegex(),of=ie(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,vn).getRegex(),lf="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",af=ie(lf,"gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Ps).replace(/punct/g,vn).getRegex(),uf=ie(/\\(punct)/,"gu").replace(/punct/g,vn).getRegex(),cf=ie(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ff=ie(Cr).replace("(?:-->|$)","-->").getRegex(),df=ie("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",ff).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Is=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,pf=ie(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Is).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Yo=ie(/^!?\[(label)\]\[(ref)\]/).replace("label",Is).replace("ref",Rr).getRegex(),Zo=ie(/^!?\[(ref)\](?:\[\])?/).replace("ref",Rr).getRegex(),hf=ie("reflink|nolink(?!\\()","g").replace("reflink",Yo).replace("nolink",Zo).getRegex(),Xo=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Mr={_backpedal:cn,anyPunctuation:uf,autolink:cf,blockSkip:Jc,br:qo,code:Kc,del:cn,delLDelim:cn,delRDelim:cn,emStrongLDelim:ef,emStrongRDelimAst:nf,emStrongRDelimUnd:rf,escape:Gc,link:pf,nolink:Zo,punctuation:Zc,reflink:Yo,reflinkSearch:hf,tag:df,text:Yc,url:cn},gf={...Mr,link:ie(/^!?\[(label)\]\((.*?)\)/).replace("label",Is).getRegex(),reflink:ie(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Is).getRegex()},Lr={...Mr,emStrongRDelimAst:sf,emStrongLDelim:tf,delLDelim:of,delRDelim:af,url:ie(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Xo).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:ie(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Qo=e=>bf[e];function Rt(e,t){if(t){if(qe.escapeTest.test(e))return e.replace(qe.escapeReplace,Qo)}else if(qe.escapeTestNoEncode.test(e))return e.replace(qe.escapeReplaceNoEncode,Qo);return e}function Jo(e){try{e=encodeURI(e).replace(qe.percentDecode,"%")}catch{return null}return e}function el(e,t){var i;let n=e.replace(qe.findPipe,(o,a,l)=>{let c=!1,u=a;for(;--u>=0&&l[u]==="\\";)c=!c;return c?"|":" |"}),s=n.split(qe.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!((i=s.at(-1))!=null&&i.trim())&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length=0&&qe.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(` +`,...ka(r))}Mt(),ir=!1}function Ta(){let e=Dn[Dn.length-1];if(!e)return[];const t=[];for(;e;){const n=t[0];n&&n.vnode===e?n.recurseCount++:t.push({vnode:e,recurseCount:0});const s=e.component&&e.component.parent;e=s&&s.vnode}return t}function ka(e){const t=[];return e.forEach((n,s)=>{t.push(...s===0?[]:[` +`],...Sa(n))}),t}function Sa({vnode:e,recurseCount:t}){const n=t>0?`... (${t} recursive calls)`:"",s=e.component?e.component.parent==null:!1,r=` at <${go(e.component,e.type,s)}`,i=">"+n;return e.props?[r,...Ea(e.props),i]:[r+i]}function Ea(e){const t=[],n=Object.keys(e);return n.slice(0,3).forEach(s=>{t.push(...Ci(s,e[s]))}),n.length>3&&t.push(" ..."),t}function Ci(e,t,n){return Pe(t)?(t=JSON.stringify(t),n?t:[`${e}=${t}`]):typeof t=="number"||typeof t=="boolean"||t==null?n?t:[`${e}=${t}`]:Ve(t)?(t=Ci(e,ue(t.value),!0),n?t:[`${e}=Ref<`,t,">"]):be(t)?[`${e}=fn${t.name?`<${t.name}>`:""}`]:(t=ue(t),n?t:[`${e}=`,t])}function bn(e,t,n,s){try{return s?e(...s):e()}catch(r){gs(r,t,n)}}function Tt(e,t,n,s){if(be(e)){const r=bn(e,t,n,s);return r&&ti(r)&&r.catch(i=>{gs(i,t,n)}),r}if(Q(e)){const r=[];for(let i=0;i>>1,r=Ke[s],i=Nn(r);i=Nn(n)?Ke.push(e):Ke.splice(Ra(t),0,e),e.flags|=1,Ii()}}function Ii(){ms||(ms=Pi.then(Li))}function Ca(e){Q(e)?xn.push(...e):Wt&&e.id===-1?Wt.splice(yn+1,0,e):e.flags&1||(xn.push(e),e.flags|=1),Ii()}function Mi(e,t,n=kt+1){for(;nNn(n)-Nn(s));if(xn.length=0,Wt){Wt.push(...t);return}for(Wt=t,yn=0;yne.id==null?e.flags&2?-1:1/0:e.id;function Li(e){try{for(kt=0;kt{s._d&&oo(-1);const i=bs(t);let o;try{o=e(...r)}finally{bs(i),s._d&&oo(1)}return o};return s._n=!0,s._c=!0,s._d=!0,s}function Pa(e,t){if(ct===null)return e;const n=As(ct),s=e.dirs||(e.dirs=[]);for(let r=0;re.__isTeleport,Gt=Symbol("_leaveCb"),xs=Symbol("_enterCb");function Ma(){const e={isMounted:!1,isLeaving:!1,isUnmounting:!1,leavingVNodes:new Map};return zn(()=>{e.isMounted=!0}),ys(()=>{e.isUnmounting=!0}),e}const ft=[Function,Array],Fi={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:ft,onEnter:ft,onAfterEnter:ft,onEnterCancelled:ft,onBeforeLeave:ft,onLeave:ft,onAfterLeave:ft,onLeaveCancelled:ft,onBeforeAppear:ft,onAppear:ft,onAfterAppear:ft,onAppearCancelled:ft},Bi=e=>{const t=e.subTree;return t.component?Bi(t.component):t},Oa={name:"BaseTransition",props:Fi,setup(e,{slots:t}){const n=uo(),s=Ma();return()=>{const r=t.default&&ji(t.default(),!0);if(!r||!r.length)return;const i=Hi(r),o=ue(e),{mode:a}=o;if(s.isLeaving)return ar(i);const l=Ui(i);if(!l)return ar(i);let f=lr(l,o,s,n,d=>f=d);l.type!==Ye&&Fn(l,f);let u=n.subTree&&Ui(n.subTree);if(u&&u.type!==Ye&&!ln(l,u)&&Bi(n).type!==Ye){let d=lr(u,o,s,n);if(Fn(u,d),a==="out-in"&&l.type!==Ye)return s.isLeaving=!0,d.afterLeave=()=>{s.isLeaving=!1,n.job.flags&8||n.update(),delete d.afterLeave,u=void 0},ar(i);a==="in-out"&&l.type!==Ye?d.delayLeave=(g,y,E)=>{const x=zi(s,u);x[String(u.key)]=u,g[Gt]=()=>{y(),g[Gt]=void 0,delete f.delayedLeave,u=void 0},f.delayedLeave=()=>{E(),delete f.delayedLeave,u=void 0}}:u=void 0}else u&&(u=void 0);return i}}};function Hi(e){let t=e[0];if(e.length>1){for(const n of e)if(n.type!==Ye){t=n;break}}return t}const La=Oa;function zi(e,t){const{leavingVNodes:n}=e;let s=n.get(t.type);return s||(s=Object.create(null),n.set(t.type,s)),s}function lr(e,t,n,s,r){const{appear:i,mode:o,persisted:a=!1,onBeforeEnter:l,onEnter:f,onAfterEnter:u,onEnterCancelled:d,onBeforeLeave:g,onLeave:y,onAfterLeave:E,onLeaveCancelled:x,onBeforeAppear:M,onAppear:m,onAfterAppear:H,onAppearCancelled:Y}=t,$=String(e.key),z=zi(n,e),O=(V,se)=>{V&&Tt(V,s,9,se)},P=(V,se)=>{const fe=se[1];O(V,se),Q(V)?V.every(D=>D.length<=1)&&fe():V.length<=1&&fe()},ee={mode:o,persisted:a,beforeEnter(V){let se=l;if(!n.isMounted)if(i)se=M||l;else return;V[Gt]&&V[Gt](!0);const fe=z[$];fe&&ln(e,fe)&&fe.el[Gt]&&fe.el[Gt](),O(se,[V])},enter(V){let se=f,fe=u,D=d;if(!n.isMounted)if(i)se=m||f,fe=H||u,D=Y||d;else return;let Z=!1;const Se=V[xs]=Ue=>{Z||(Z=!0,Ue?O(D,[V]):O(fe,[V]),ee.delayedLeave&&ee.delayedLeave(),V[xs]=void 0)};se?P(se,[V,Se]):Se()},leave(V,se){const fe=String(e.key);if(V[xs]&&V[xs](!0),n.isUnmounting)return se();O(g,[V]);let D=!1;const Z=V[Gt]=Se=>{D||(D=!0,se(),Se?O(x,[V]):O(E,[V]),V[Gt]=void 0,z[fe]===e&&delete z[fe])};z[fe]=e,y?P(y,[V,Z]):Z()},clone(V){const se=lr(V,t,n,s,r);return r&&r(se),se}};return ee}function ar(e){if(ur(e))return e=Kt(e),e.children=null,e}function Ui(e){if(!ur(e))return Ni(e.type)&&e.children?Hi(e.children):e;if(e.component)return e.component.subTree;const{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&be(n.default))return n.default()}}function Fn(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Fn(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function ji(e,t=!1,n){let s=[],r=0;for(let i=0;i1)for(let i=0;iBn(E,t&&(Q(t)?t[x]:t),n,s,r));return}if(Hn(s)&&!r){s.shapeFlag&512&&s.type.__asyncResolved&&s.component.subTree.component&&Bn(e,t,n,s.component.subTree);return}const i=s.shapeFlag&4?As(s.component):s.el,o=r?null:i,{i:a,r:l}=e,f=t&&t.r,u=a.refs===oe?a.refs={}:a.refs,d=a.setupState,g=ue(d),y=d===oe?()=>!1:E=>me(g,E);if(f!=null&&f!==l&&(Pe(f)?(u[f]=null,y(f)&&(d[f]=null)):Ve(f)&&(f.value=null)),be(l))bn(l,a,12,[o,u]);else{const E=Pe(l),x=Ve(l);if(E||x){const M=()=>{if(e.f){const m=E?y(l)?d[l]:u[l]:l.value;r?Q(m)&&Jr(m,i):Q(m)?m.includes(i)||m.push(i):E?(u[l]=[i],y(l)&&(d[l]=u[l])):(l.value=[i],e.k&&(u[e.k]=l.value))}else E?(u[l]=o,y(l)&&(d[l]=o)):x&&(l.value=o,e.k&&(u[e.k]=o))};o?(M.id=-1,rt(M,n)):M()}}}is().requestIdleCallback,is().cancelIdleCallback;const Hn=e=>!!e.type.__asyncLoader,ur=e=>e.type.__isKeepAlive;function Da(e,t,n=Zt,s=!1){if(n){const r=n[e]||(n[e]=[]),i=t.__weh||(t.__weh=(...o)=>{It();const a=yr(n),l=Tt(t,n,e,o);return a(),Mt(),l});return s?r.unshift(i):r.push(i),i}}const Vi=e=>(t,n=Zt)=>{(!qn||e==="sp")&&Da(e,(...s)=>t(...s),n)},zn=Vi("m"),ys=Vi("bum"),Na=Symbol.for("v-ndc");function ws(e,t,n,s){let r;const i=n,o=Q(e);if(o||Pe(e)){const a=o&&mn(e);let l=!1,f=!1;a&&(l=!ut(e),f=qt(e),e=os(e)),r=new Array(e.length);for(let u=0,d=e.length;ut(a,l,void 0,i));else{const a=Object.keys(e);r=new Array(a.length);for(let l=0,f=a.length;le?fo(e)?As(e):cr(e.parent):null,Un=bt(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>cr(e.parent),$root:e=>cr(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>e.type,$forceUpdate:e=>e.f||(e.f=()=>{or(e.update)}),$nextTick:e=>e.n||(e.n=St.bind(e.proxy)),$watch:e=>Jt}),fr=(e,t)=>e!==oe&&!e.__isScriptSetup&&me(e,t),Fa={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:n,setupState:s,data:r,props:i,accessCache:o,type:a,appContext:l}=e;let f;if(t[0]!=="$"){const y=o[t];if(y!==void 0)switch(y){case 1:return s[t];case 2:return r[t];case 4:return n[t];case 3:return i[t]}else{if(fr(s,t))return o[t]=1,s[t];if(r!==oe&&me(r,t))return o[t]=2,r[t];if((f=e.propsOptions[0])&&me(f,t))return o[t]=3,i[t];if(n!==oe&&me(n,t))return o[t]=4,n[t];o[t]=0}}const u=Un[t];let d,g;if(u)return t==="$attrs"&&je(e.attrs,"get",""),u(e);if((d=a.__cssModules)&&(d=d[t]))return d;if(n!==oe&&me(n,t))return o[t]=4,n[t];if(g=l.config.globalProperties,me(g,t))return g[t]},set({_:e},t,n){const{data:s,setupState:r,ctx:i}=e;return fr(r,t)?(r[t]=n,!0):s!==oe&&me(s,t)?(s[t]=n,!0):me(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(i[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:s,appContext:r,propsOptions:i}},o){let a;return!!n[o]||e!==oe&&me(e,o)||fr(t,o)||(a=i[0])&&me(a,o)||me(s,o)||me(Un,o)||me(r.config.globalProperties,o)},defineProperty(e,t,n){return n.get!=null?e._.accessCache[t]=0:me(n,"value")&&this.set(e,t,n.value,null),Reflect.defineProperty(e,t,n)}};function qi(){return{app:null,config:{isNativeTag:Dl,performance:!1,globalProperties:{},optionMergeStrategies:{},errorHandler:void 0,warnHandler:void 0,compilerOptions:{}},mixins:[],components:{},directives:{},provides:Object.create(null),optionsCache:new WeakMap,propsCache:new WeakMap,emitsCache:new WeakMap}}let Ba=0;function Ha(e,t){return function(s,r=null){be(s)||(s=bt({},s)),r!=null&&!Re(r)&&(r=null);const i=qi(),o=new WeakSet,a=[];let l=!1;const f=i.app={_uid:Ba++,_component:s,_props:r,_container:null,_context:i,_instance:null,version:Su,get config(){return i.config},set config(u){},use(u,...d){return o.has(u)||(u&&be(u.install)?(o.add(u),u.install(f,...d)):be(u)&&(o.add(u),u(f,...d))),f},mixin(u){return f},component(u,d){return d?(i.components[u]=d,f):i.components[u]},directive(u,d){return d?(i.directives[u]=d,f):i.directives[u]},mount(u,d,g){if(!l){const y=f._ceVNode||Oe(s,r);return y.appContext=i,g===!0?g="svg":g===!1&&(g=void 0),e(y,u,g),l=!0,f._container=u,u.__vue_app__=f,As(y.component)}},onUnmount(u){a.push(u)},unmount(){l&&(Tt(a,f._instance,16),e(null,f._container),delete f._container.__vue_app__)},provide(u,d){return i.provides[u]=d,f},runWithContext(u){const d=wn;wn=f;try{return u()}finally{wn=d}}};return f}}let wn=null;function za(e,t,n=!1){const s=uo();if(s||wn){let r=wn?wn._context.provides:s?s.parent==null||s.ce?s.vnode.appContext&&s.vnode.appContext.provides:s.parent.provides:void 0;if(r&&e in r)return r[e];if(arguments.length>1)return n&&be(t)?t.call(s&&s.proxy):t}}const Wi={},Gi=()=>Object.create(Wi),Ki=e=>Object.getPrototypeOf(e)===Wi;function Ua(e,t,n,s=!1){const r={},i=Gi();e.propsDefaults=Object.create(null),Yi(e,t,r,i);for(const o in e.propsOptions[0])o in r||(r[o]=void 0);n?e.props=s?r:da(r):e.type.props?e.props=r:e.props=i,e.attrs=i}function ja(e,t,n,s){const{props:r,attrs:i,vnode:{patchFlag:o}}=e,a=ue(r),[l]=e.propsOptions;let f=!1;if((s||o>0)&&!(o&16)){if(o&8){const u=e.vnode.dynamicProps;for(let d=0;de==="_"||e==="__"||e==="_ctx"||e==="$stable",hr=e=>Q(e)?e.map(At):[At(e)],qa=(e,t,n)=>{if(t._n)return t;const s=Di((...r)=>hr(t(...r)),n);return s._c=!1,s},Xi=(e,t,n)=>{const s=e._ctx;for(const r in e){if(dr(r))continue;const i=e[r];if(be(i))t[r]=qa(r,i,s);else if(i!=null){const o=hr(i);t[r]=()=>o}}},Qi=(e,t)=>{const n=hr(t);e.slots.default=()=>n},Ji=(e,t,n)=>{for(const s in t)(n||!dr(s))&&(e[s]=t[s])},Wa=(e,t,n)=>{const s=e.slots=Gi();if(e.vnode.shapeFlag&32){const r=t.__;r&&js(s,"__",r,!0);const i=t._;i?(Ji(s,t,n),n&&js(s,"_",i,!0)):Xi(t,s)}else t&&Qi(e,t)},Ga=(e,t,n)=>{const{vnode:s,slots:r}=e;let i=!0,o=oe;if(s.shapeFlag&32){const a=t._;a?n&&a===1?i=!1:Ji(r,t,n):(i=!t.$stable,Xi(t,r)),o=t}else t&&(Qi(e,t),o={default:1});if(i)for(const a in r)!dr(a)&&o[a]==null&&delete r[a]},rt=au;function Ka(e){return Ya(e)}function Ya(e,t){const n=is();n.__VUE__=!0;const{insert:s,remove:r,patchProp:i,createElement:o,createText:a,createComment:l,setText:f,setElementText:u,parentNode:d,nextSibling:g,setScopeId:y=Jt,insertStaticContent:E}=e,x=(c,h,b,k=null,v=null,_=null,I=void 0,R=null,A=!!h.dynamicChildren)=>{if(c===h)return;c&&!ln(c,h)&&(k=ye(c),de(c,v,_,!0),c=null),h.patchFlag===-2&&(A=!1,h.dynamicChildren=null);const{type:S,ref:U,shapeFlag:L}=h;switch(S){case _s:M(c,h,b,k);break;case Ye:m(c,h,b,k);break;case mr:c==null&&H(h,b,k,I);break;case He:D(c,h,b,k,v,_,I,R,A);break;default:L&1?z(c,h,b,k,v,_,I,R,A):L&6?Z(c,h,b,k,v,_,I,R,A):(L&64||L&128)&&S.process(c,h,b,k,v,_,I,R,A,Ce)}U!=null&&v?Bn(U,c&&c.ref,_,h||c,!h):U==null&&c&&c.ref!=null&&Bn(c.ref,null,_,c,!0)},M=(c,h,b,k)=>{if(c==null)s(h.el=a(h.children),b,k);else{const v=h.el=c.el;h.children!==c.children&&f(v,h.children)}},m=(c,h,b,k)=>{c==null?s(h.el=l(h.children||""),b,k):h.el=c.el},H=(c,h,b,k)=>{[c.el,c.anchor]=E(c.children,h,b,k,c.el,c.anchor)},Y=({el:c,anchor:h},b,k)=>{let v;for(;c&&c!==h;)v=g(c),s(c,b,k),c=v;s(h,b,k)},$=({el:c,anchor:h})=>{let b;for(;c&&c!==h;)b=g(c),r(c),c=b;r(h)},z=(c,h,b,k,v,_,I,R,A)=>{h.type==="svg"?I="svg":h.type==="math"&&(I="mathml"),c==null?O(h,b,k,v,_,I,R,A):V(c,h,v,_,I,R,A)},O=(c,h,b,k,v,_,I,R)=>{let A,S;const{props:U,shapeFlag:L,transition:j,dirs:K}=c;if(A=c.el=o(c.type,_,U&&U.is,U),L&8?u(A,c.children):L&16&&ee(c.children,A,null,k,v,gr(c,_),I,R),K&&sn(c,null,k,"created"),P(A,c,c.scopeId,I,k),U){for(const he in U)he!=="value"&&!Pn(he)&&i(A,he,null,U[he],_,k);"value"in U&&i(A,"value",null,U.value,_),(S=U.onVnodeBeforeMount)&&Rt(S,k,c)}K&&sn(c,null,k,"beforeMount");const ne=Za(v,j);ne&&j.beforeEnter(A),s(A,h,b),((S=U&&U.onVnodeMounted)||ne||K)&&rt(()=>{S&&Rt(S,k,c),ne&&j.enter(A),K&&sn(c,null,k,"mounted")},v)},P=(c,h,b,k,v)=>{if(b&&y(c,b),k)for(let _=0;_{for(let S=A;S{const R=h.el=c.el;let{patchFlag:A,dynamicChildren:S,dirs:U}=h;A|=c.patchFlag&16;const L=c.props||oe,j=h.props||oe;let K;if(b&&rn(b,!1),(K=j.onVnodeBeforeUpdate)&&Rt(K,b,h,c),U&&sn(h,c,b,"beforeUpdate"),b&&rn(b,!0),(L.innerHTML&&j.innerHTML==null||L.textContent&&j.textContent==null)&&u(R,""),S?se(c.dynamicChildren,S,R,b,k,gr(h,v),_):I||pe(c,h,R,null,b,k,gr(h,v),_,!1),A>0){if(A&16)fe(R,L,j,b,v);else if(A&2&&L.class!==j.class&&i(R,"class",null,j.class,v),A&4&&i(R,"style",L.style,j.style,v),A&8){const ne=h.dynamicProps;for(let he=0;he{K&&Rt(K,b,h,c),U&&sn(h,c,b,"updated")},k)},se=(c,h,b,k,v,_,I)=>{for(let R=0;R{if(h!==b){if(h!==oe)for(const _ in h)!Pn(_)&&!(_ in b)&&i(c,_,h[_],null,v,k);for(const _ in b){if(Pn(_))continue;const I=b[_],R=h[_];I!==R&&_!=="value"&&i(c,_,R,I,v,k)}"value"in b&&i(c,"value",h.value,b.value,v)}},D=(c,h,b,k,v,_,I,R,A)=>{const S=h.el=c?c.el:a(""),U=h.anchor=c?c.anchor:a("");let{patchFlag:L,dynamicChildren:j,slotScopeIds:K}=h;K&&(R=R?R.concat(K):K),c==null?(s(S,b,k),s(U,b,k),ee(h.children||[],b,U,v,_,I,R,A)):L>0&&L&64&&j&&c.dynamicChildren?(se(c.dynamicChildren,j,b,v,_,I,R),(h.key!=null||v&&h===v.subTree)&&eo(c,h,!0)):pe(c,h,b,U,v,_,I,R,A)},Z=(c,h,b,k,v,_,I,R,A)=>{h.slotScopeIds=R,c==null?h.shapeFlag&512?v.ctx.activate(h,b,k,I,A):Se(h,b,k,v,_,I,A):Ue(c,h,A)},Se=(c,h,b,k,v,_,I)=>{const R=c.component=gu(c,k,v);if(ur(c)&&(R.ctx.renderer=Ce),mu(R,!1,I),R.asyncDep){if(v&&v.registerDep(R,te,I),!c.el){const A=R.subTree=Oe(Ye);m(null,A,h,b),c.placeholder=A.el}}else te(R,c,h,b,v,_,I)},Ue=(c,h,b)=>{const k=h.component=c.component;if(ou(c,h,b))if(k.asyncDep&&!k.asyncResolved){C(k,h,b);return}else k.next=h,k.update();else h.el=c.el,k.vnode=h},te=(c,h,b,k,v,_,I)=>{const R=()=>{if(c.isMounted){let{next:L,bu:j,u:K,parent:ne,vnode:he}=c;{const lt=to(c);if(lt){L&&(L.el=he.el,C(c,L,I)),lt.asyncDep.then(()=>{c.isUnmounted||R()});return}}let ie=L,ke;rn(c,!1),L?(L.el=he.el,C(c,L,I)):L=he,j&&rs(j),(ke=L.props&&L.props.onVnodeBeforeUpdate)&&Rt(ke,ne,L,he),rn(c,!0);const $e=so(c),ot=c.subTree;c.subTree=$e,x(ot,$e,d(ot.el),ye(ot),c,v,_),L.el=$e.el,ie===null&&lu(c,$e.el),K&&rt(K,v),(ke=L.props&&L.props.onVnodeUpdated)&&rt(()=>Rt(ke,ne,L,he),v)}else{let L;const{el:j,props:K}=h,{bm:ne,m:he,parent:ie,root:ke,type:$e}=c,ot=Hn(h);rn(c,!1),ne&&rs(ne),!ot&&(L=K&&K.onVnodeBeforeMount)&&Rt(L,ie,h),rn(c,!0);{ke.ce&&ke.ce._def.shadowRoot!==!1&&ke.ce._injectChildStyle($e);const lt=c.subTree=so(c);x(null,lt,b,k,c,v,_),h.el=lt.el}if(he&&rt(he,v),!ot&&(L=K&&K.onVnodeMounted)){const lt=h;rt(()=>Rt(L,ie,lt),v)}(h.shapeFlag&256||ie&&Hn(ie.vnode)&&ie.vnode.shapeFlag&256)&&c.a&&rt(c.a,v),c.isMounted=!0,h=b=k=null}};c.scope.on();const A=c.effect=new ui(R);c.scope.off();const S=c.update=A.run.bind(A),U=c.job=A.runIfDirty.bind(A);U.i=c,U.id=c.uid,A.scheduler=()=>or(U),rn(c,!0),S()},C=(c,h,b)=>{h.component=c;const k=c.vnode.props;c.vnode=h,c.next=null,ja(c,h.props,k,b),Ga(c,h.children,b),It(),Mi(c),Mt()},pe=(c,h,b,k,v,_,I,R,A=!1)=>{const S=c&&c.children,U=c?c.shapeFlag:0,L=h.children,{patchFlag:j,shapeFlag:K}=h;if(j>0){if(j&128){re(S,L,b,k,v,_,I,R,A);return}else if(j&256){Ge(S,L,b,k,v,_,I,R,A);return}}K&8?(U&16&&nt(S,v,_),L!==S&&u(b,L)):U&16?K&16?re(S,L,b,k,v,_,I,R,A):nt(S,v,_,!0):(U&8&&u(b,""),K&16&&ee(L,b,k,v,_,I,R,A))},Ge=(c,h,b,k,v,_,I,R,A)=>{c=c||mt,h=h||mt;const S=c.length,U=h.length,L=Math.min(S,U);let j;for(j=0;jU?nt(c,v,_,!0,!1,L):ee(h,b,k,v,_,I,R,A,L)},re=(c,h,b,k,v,_,I,R,A)=>{let S=0;const U=h.length;let L=c.length-1,j=U-1;for(;S<=L&&S<=j;){const K=c[S],ne=h[S]=A?Yt(h[S]):At(h[S]);if(ln(K,ne))x(K,ne,b,null,v,_,I,R,A);else break;S++}for(;S<=L&&S<=j;){const K=c[L],ne=h[j]=A?Yt(h[j]):At(h[j]);if(ln(K,ne))x(K,ne,b,null,v,_,I,R,A);else break;L--,j--}if(S>L){if(S<=j){const K=j+1,ne=Kj)for(;S<=L;)de(c[S],v,_,!0),S++;else{const K=S,ne=S,he=new Map;for(S=ne;S<=j;S++){const De=h[S]=A?Yt(h[S]):At(h[S]);De.key!=null&&he.set(De.key,S)}let ie,ke=0;const $e=j-ne+1;let ot=!1,lt=0;const Bt=new Array($e);for(S=0;S<$e;S++)Bt[S]=0;for(S=K;S<=L;S++){const De=c[S];if(ke>=$e){de(De,v,_,!0);continue}let Qe;if(De.key!=null)Qe=he.get(De.key);else for(ie=ne;ie<=j;ie++)if(Bt[ie-ne]===0&&ln(De,h[ie])){Qe=ie;break}Qe===void 0?de(De,v,_,!0):(Bt[Qe-ne]=S+1,Qe>=lt?lt=Qe:ot=!0,x(De,h[Qe],b,null,v,_,I,R,A),ke++)}const Jn=ot?Xa(Bt):mt;for(ie=Jn.length-1,S=$e-1;S>=0;S--){const De=ne+S,Qe=h[De],at=h[De+1],Ht=De+1{const{el:_,type:I,transition:R,children:A,shapeFlag:S}=c;if(S&6){B(c.component.subTree,h,b,k);return}if(S&128){c.suspense.move(h,b,k);return}if(S&64){I.move(c,h,b,Ce);return}if(I===He){s(_,h,b);for(let L=0;LR.enter(_),v);else{const{leave:L,delayLeave:j,afterLeave:K}=R,ne=()=>{c.ctx.isUnmounted?r(_):s(_,h,b)},he=()=>{L(_,()=>{ne(),K&&K()})};j?j(_,ne,he):he()}else s(_,h,b)},de=(c,h,b,k=!1,v=!1)=>{const{type:_,props:I,ref:R,children:A,dynamicChildren:S,shapeFlag:U,patchFlag:L,dirs:j,cacheIndex:K}=c;if(L===-2&&(v=!1),R!=null&&(It(),Bn(R,null,b,c,!0),Mt()),K!=null&&(h.renderCache[K]=void 0),U&256){h.ctx.deactivate(c);return}const ne=U&1&&j,he=!Hn(c);let ie;if(he&&(ie=I&&I.onVnodeBeforeUnmount)&&Rt(ie,h,c),U&6)ge(c.component,b,k);else{if(U&128){c.suspense.unmount(b,k);return}ne&&sn(c,null,h,"beforeUnmount"),U&64?c.type.remove(c,h,b,Ce,k):S&&!S.hasOnce&&(_!==He||L>0&&L&64)?nt(S,h,b,!1,!0):(_===He&&L&384||!v&&U&16)&&nt(A,h,b),k&&ae(c)}(he&&(ie=I&&I.onVnodeUnmounted)||ne)&&rt(()=>{ie&&Rt(ie,h,c),ne&&sn(c,null,h,"unmounted")},b)},ae=c=>{const{type:h,el:b,anchor:k,transition:v}=c;if(h===He){ve(b,k);return}if(h===mr){$(c);return}const _=()=>{r(b),v&&!v.persisted&&v.afterLeave&&v.afterLeave()};if(c.shapeFlag&1&&v&&!v.persisted){const{leave:I,delayLeave:R}=v,A=()=>I(b,_);R?R(c.el,_,A):A()}else _()},ve=(c,h)=>{let b;for(;c!==h;)b=g(c),r(c),c=b;r(h)},ge=(c,h,b)=>{const{bum:k,scope:v,job:_,subTree:I,um:R,m:A,a:S,parent:U,slots:{__:L}}=c;no(A),no(S),k&&rs(k),U&&Q(L)&&L.forEach(j=>{U.renderCache[j]=void 0}),v.stop(),_&&(_.flags|=8,de(I,c,h,b)),R&&rt(R,h),rt(()=>{c.isUnmounted=!0},h),h&&h.pendingBranch&&!h.isUnmounted&&c.asyncDep&&!c.asyncResolved&&c.suspenseId===h.pendingId&&(h.deps--,h.deps===0&&h.resolve())},nt=(c,h,b,k=!1,v=!1,_=0)=>{for(let I=_;I{if(c.shapeFlag&6)return ye(c.component.subTree);if(c.shapeFlag&128)return c.suspense.next();const h=g(c.anchor||c.el),b=h&&h[Ia];return b?g(b):h};let ht=!1;const G=(c,h,b)=>{c==null?h._vnode&&de(h._vnode,null,null,!0):x(h._vnode||null,c,h,null,null,null,b),h._vnode=c,ht||(ht=!0,Mi(),Oi(),ht=!1)},Ce={p:x,um:de,m:B,r:ae,mt:Se,mc:ee,pc:pe,pbc:se,n:ye,o:e};return{render:G,hydrate:void 0,createApp:Ha(G)}}function gr({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function rn({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Za(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function eo(e,t,n=!1){const s=e.children,r=t.children;if(Q(s)&&Q(r))for(let i=0;i>1,e[n[a]]0&&(t[s]=n[i-1]),n[i]=s)}}for(i=n.length,o=n[i-1];i-- >0;)n[i]=o,o=t[o];return n}function to(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:to(t)}function no(e){if(e)for(let t=0;tza(Qa);function on(e,t,n){return eu(e,t,n)}function eu(e,t,n=oe){const{immediate:s,deep:r,flush:i,once:o}=n,a=bt({},n),l=t&&s||!t&&i!=="post";let f;if(qn){if(i==="sync"){const y=Ja();f=y.__watcherHandles||(y.__watcherHandles=[])}else if(!l){const y=()=>{};return y.stop=Jt,y.resume=Jt,y.pause=Jt,y}}const u=Zt;a.call=(y,E,x)=>Tt(y,u,E,x);let d=!1;i==="post"?a.scheduler=y=>{rt(y,u&&u.suspense)}:i!=="sync"&&(d=!0,a.scheduler=(y,E)=>{E?y():or(y)}),a.augmentJob=y=>{t&&(y.flags|=4),d&&(y.flags|=2,u&&(y.id=u.uid,y.i=u))};const g=_a(e,t,a);return qn&&(f?f.push(g):l&&g()),g}const tu=(e,t)=>t==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${jt(t)}Modifiers`]||e[`${en(t)}Modifiers`];function nu(e,t,...n){if(e.isUnmounted)return;const s=e.vnode.props||oe;let r=n;const i=t.startsWith("update:"),o=i&&tu(s,t.slice(7));o&&(o.trim&&(r=n.map(u=>Pe(u)?u.trim():u)),o.number&&(r=n.map(Vs)));let a,l=s[a=Us(t)]||s[a=Us(jt(t))];!l&&i&&(l=s[a=Us(en(t))]),l&&Tt(l,e,6,r);const f=s[a+"Once"];if(f){if(!e.emitted)e.emitted={};else if(e.emitted[a])return;e.emitted[a]=!0,Tt(f,e,6,r)}}function su(e,t,n=!1){const s=t.emitsCache,r=s.get(e);if(r!==void 0)return r;const i=e.emits;let o={};return i?(Q(i)?i.forEach(a=>o[a]=null):bt(o,i),Re(e)&&s.set(e,o),o):(Re(e)&&s.set(e,null),null)}function vs(e,t){return!e||!ts(t)?!1:(t=t.slice(2).replace(/Once$/,""),me(e,t[0].toLowerCase()+t.slice(1))||me(e,en(t))||me(e,t))}function Ed(){}function so(e){const{type:t,vnode:n,proxy:s,withProxy:r,propsOptions:[i],slots:o,attrs:a,emit:l,render:f,renderCache:u,props:d,data:g,setupState:y,ctx:E,inheritAttrs:x}=e,M=bs(e);let m,H;try{if(n.shapeFlag&4){const $=r||s,z=$;m=At(f.call(z,$,u,d,y,g,E)),H=a}else{const $=t;m=At($.length>1?$(d,{attrs:a,slots:o,emit:l}):$(d,null)),H=t.props?a:ru(a)}}catch($){jn.length=0,gs($,e,1),m=Oe(Ye)}let Y=m;if(H&&x!==!1){const $=Object.keys(H),{shapeFlag:z}=Y;$.length&&z&7&&(i&&$.some(Hs)&&(H=iu(H,i)),Y=Kt(Y,H,!1,!0))}return n.dirs&&(Y=Kt(Y,null,!1,!0),Y.dirs=Y.dirs?Y.dirs.concat(n.dirs):n.dirs),n.transition&&Fn(Y,n.transition),m=Y,bs(M),m}const ru=e=>{let t;for(const n in e)(n==="class"||n==="style"||ts(n))&&((t||(t={}))[n]=e[n]);return t},iu=(e,t)=>{const n={};for(const s in e)(!Hs(s)||!(s.slice(9)in t))&&(n[s]=e[s]);return n};function ou(e,t,n){const{props:s,children:r,component:i}=e,{props:o,children:a,patchFlag:l}=t,f=i.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&l>=0){if(l&1024)return!0;if(l&16)return s?ro(s,o,f):!!o;if(l&8){const u=t.dynamicProps;for(let d=0;de.__isSuspense;function au(e,t){t&&t.pendingBranch?Q(e)?t.effects.push(...e):t.effects.push(e):Ca(e)}const He=Symbol.for("v-fgt"),_s=Symbol.for("v-txt"),Ye=Symbol.for("v-cmt"),mr=Symbol.for("v-stc"),jn=[];let it=null;function F(e=!1){jn.push(it=e?null:[])}function uu(){jn.pop(),it=jn[jn.length-1]||null}let Vn=1;function oo(e,t=!1){Vn+=e,e<0&&it&&t&&(it.hasOnce=!0)}function lo(e){return e.dynamicChildren=Vn>0?it||mt:null,uu(),Vn>0&&it&&it.push(e),e}function W(e,t,n,s,r,i){return lo(w(e,t,n,s,r,i,!0))}function Et(e,t,n,s,r){return lo(Oe(e,t,n,s,r,!0))}function Ts(e){return e?e.__v_isVNode===!0:!1}function ln(e,t){return e.type===t.type&&e.key===t.key}const ao=({key:e})=>e!=null?e:null,ks=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?Pe(e)||Ve(e)||be(e)?{i:ct,r:e,k:t,f:!!n}:e:null);function w(e,t=null,n=null,s=0,r=null,i=e===He?0:1,o=!1,a=!1){const l={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&ao(t),ref:t&&ks(t),scopeId:$i,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:i,patchFlag:s,dynamicProps:r,dynamicChildren:null,appContext:null,ctx:ct};return a?(br(l,n),i&128&&e.normalize(l)):n&&(l.shapeFlag|=Pe(n)?8:16),Vn>0&&!o&&it&&(l.patchFlag>0||i&6)&&l.patchFlag!==32&&it.push(l),l}const Oe=cu;function cu(e,t=null,n=null,s=0,r=null,i=!1){if((!e||e===Na)&&(e=Ye),Ts(e)){const a=Kt(e,t,!0);return n&&br(a,n),Vn>0&&!i&&it&&(a.shapeFlag&6?it[it.indexOf(e)]=a:it.push(a)),a.patchFlag=-2,a}if(Tu(e)&&(e=e.__vccOpts),t){t=fu(t);let{class:a,style:l}=t;a&&!Pe(a)&&(t.class=we(a)),Re(l)&&(rr(l)&&!Q(l)&&(l=bt({},l)),t.style=qs(l))}const o=Pe(e)?1:io(e)?128:Ni(e)?64:Re(e)?4:be(e)?2:0;return w(e,t,n,s,r,o,i,!0)}function fu(e){return e?rr(e)||Ki(e)?bt({},e):e:null}function Kt(e,t,n=!1,s=!1){const{props:r,ref:i,patchFlag:o,children:a,transition:l}=e,f=t?pu(r||{},t):r,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:f,key:f&&ao(f),ref:t&&t.ref?n&&i?Q(i)?i.concat(ks(t)):[i,ks(t)]:ks(t):i,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:a,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==He?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:l,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Kt(e.ssContent),ssFallback:e.ssFallback&&Kt(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return l&&s&&Fn(u,l.clone(u)),u}function Ss(e=" ",t=0){return Oe(_s,null,e,t)}function qe(e="",t=!1){return t?(F(),Et(Ye,null,e)):Oe(Ye,null,e)}function At(e){return e==null||typeof e=="boolean"?Oe(Ye):Q(e)?Oe(He,null,e.slice()):Ts(e)?Yt(e):Oe(_s,null,String(e))}function Yt(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Kt(e)}function br(e,t){let n=0;const{shapeFlag:s}=e;if(t==null)t=null;else if(Q(t))n=16;else if(typeof t=="object")if(s&65){const r=t.default;r&&(r._c&&(r._d=!1),br(e,r()),r._c&&(r._d=!0));return}else{n=32;const r=t._;!r&&!Ki(t)?t._ctx=ct:r===3&&ct&&(ct.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else be(t)?(t={default:t,_ctx:ct},n=32):(t=String(t),s&64?(n=16,t=[Ss(t)]):n=8);e.children=t,e.shapeFlag|=n}function pu(...e){const t={};for(let n=0;nZt||ct;let Es,xr;{const e=is(),t=(n,s)=>{let r;return(r=e[n])||(r=e[n]=[]),r.push(s),i=>{r.length>1?r.forEach(o=>o(i)):r[0](i)}};Es=t("__VUE_INSTANCE_SETTERS__",n=>Zt=n),xr=t("__VUE_SSR_SETTERS__",n=>qn=n)}const yr=e=>{const t=Zt;return Es(e),e.scope.on(),()=>{e.scope.off(),Es(t)}},co=()=>{Zt&&Zt.scope.off(),Es(null)};function fo(e){return e.vnode.shapeFlag&4}let qn=!1;function mu(e,t=!1,n=!1){t&&xr(t);const{props:s,children:r}=e.vnode,i=fo(e);Ua(e,s,i,t),Wa(e,r,n||t);const o=i?bu(e,t):void 0;return t&&xr(!1),o}function bu(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,Fa);const{setup:s}=n;if(s){It();const r=e.setupContext=s.length>1?yu(e):null,i=yr(e),o=bn(s,e,0,[e.props,r]),a=ti(o);if(Mt(),i(),(a||e.sp)&&!Hn(e)&&$a(e),a){if(o.then(co,co),t)return o.then(l=>{po(e,l)}).catch(l=>{gs(l,e,0)});e.asyncDep=o}else po(e,o)}else ho(e)}function po(e,t,n){be(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:Re(t)&&(e.setupState=Ri(t)),ho(e)}function ho(e,t,n){const s=e.type;e.render||(e.render=s.render||Jt)}const xu={get(e,t){return je(e,"get",""),e[t]}};function yu(e){const t=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,xu),slots:e.slots,emit:e.emit,expose:t}}function As(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(Ri(ha(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Un)return Un[n](e)},has(t,n){return n in t||n in Un}})):e.proxy}const wu=/(?:^|[-_])(\w)/g,vu=e=>e.replace(wu,t=>t.toUpperCase()).replace(/[-_]/g,"");function _u(e,t=!0){return be(e)?e.displayName||e.name:e.name||t&&e.__name}function go(e,t,n=!1){let s=_u(t);if(!s&&t.__file){const r=t.__file.match(/([^/\\]+)\.\w+$/);r&&(s=r[1])}if(!s&&e&&e.parent){const r=i=>{for(const o in i)if(i[o]===t)return o};s=r(e.components||e.parent.type.components)||r(e.appContext.components)}return s?vu(s):n?"App":"Anonymous"}function Tu(e){return be(e)&&"__vccOpts"in e}const Ee=(e,t)=>wa(e,t,qn);function ku(e,t,n){const s=arguments.length;return s===2?Re(t)&&!Q(t)?Ts(t)?Oe(e,null,[t]):Oe(e,t):Oe(e,null,t):(s>3?n=Array.prototype.slice.call(arguments,2):s===3&&Ts(n)&&(n=[n]),Oe(e,t,n))}const Su="3.5.18";let wr;const mo=typeof window!="undefined"&&window.trustedTypes;if(mo)try{wr=mo.createPolicy("vue",{createHTML:e=>e})}catch{}const bo=wr?e=>wr.createHTML(e):e=>e,Eu="http://www.w3.org/2000/svg",Au="http://www.w3.org/1998/Math/MathML",Dt=typeof document!="undefined"?document:null,xo=Dt&&Dt.createElement("template"),Ru={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,s)=>{const r=t==="svg"?Dt.createElementNS(Eu,e):t==="mathml"?Dt.createElementNS(Au,e):n?Dt.createElement(e,{is:n}):Dt.createElement(e);return e==="select"&&s&&s.multiple!=null&&r.setAttribute("multiple",s.multiple),r},createText:e=>Dt.createTextNode(e),createComment:e=>Dt.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Dt.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,s,r,i){const o=n?n.previousSibling:t.lastChild;if(r&&(r===i||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),n),!(r===i||!(r=r.nextSibling)););else{xo.innerHTML=bo(s==="svg"?`${e}`:s==="mathml"?`${e}`:e);const a=xo.content;if(s==="svg"||s==="mathml"){const l=a.firstChild;for(;l.firstChild;)a.appendChild(l.firstChild);a.removeChild(l)}t.insertBefore(a,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Xt="transition",Wn="animation",Gn=Symbol("_vtc"),yo={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Cu=bt({},Fi,yo),Pu=(e=>(e.displayName="Transition",e.props=Cu,e))((e,{slots:t})=>ku(La,Iu(e),t)),an=(e,t=[])=>{Q(e)?e.forEach(n=>n(...t)):e&&e(...t)},wo=e=>e?Q(e)?e.some(t=>t.length>1):e.length>1:!1;function Iu(e){const t={};for(const D in e)D in yo||(t[D]=e[D]);if(e.css===!1)return t;const{name:n="v",type:s,duration:r,enterFromClass:i=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:a=`${n}-enter-to`,appearFromClass:l=i,appearActiveClass:f=o,appearToClass:u=a,leaveFromClass:d=`${n}-leave-from`,leaveActiveClass:g=`${n}-leave-active`,leaveToClass:y=`${n}-leave-to`}=e,E=Mu(r),x=E&&E[0],M=E&&E[1],{onBeforeEnter:m,onEnter:H,onEnterCancelled:Y,onLeave:$,onLeaveCancelled:z,onBeforeAppear:O=m,onAppear:P=H,onAppearCancelled:ee=Y}=t,V=(D,Z,Se,Ue)=>{D._enterCancelled=Ue,un(D,Z?u:a),un(D,Z?f:o),Se&&Se()},se=(D,Z)=>{D._isLeaving=!1,un(D,d),un(D,y),un(D,g),Z&&Z()},fe=D=>(Z,Se)=>{const Ue=D?P:H,te=()=>V(Z,D,Se);an(Ue,[Z,te]),vo(()=>{un(Z,D?l:i),Nt(Z,D?u:a),wo(Ue)||_o(Z,s,x,te)})};return bt(t,{onBeforeEnter(D){an(m,[D]),Nt(D,i),Nt(D,o)},onBeforeAppear(D){an(O,[D]),Nt(D,l),Nt(D,f)},onEnter:fe(!1),onAppear:fe(!0),onLeave(D,Z){D._isLeaving=!0;const Se=()=>se(D,Z);Nt(D,d),D._enterCancelled?(Nt(D,g),So()):(So(),Nt(D,g)),vo(()=>{D._isLeaving&&(un(D,d),Nt(D,y),wo($)||_o(D,s,M,Se))}),an($,[D,Se])},onEnterCancelled(D){V(D,!1,void 0,!0),an(Y,[D])},onAppearCancelled(D){V(D,!0,void 0,!0),an(ee,[D])},onLeaveCancelled(D){se(D),an(z,[D])}})}function Mu(e){if(e==null)return null;if(Re(e))return[vr(e.enter),vr(e.leave)];{const t=vr(e);return[t,t]}}function vr(e){return zl(e)}function Nt(e,t){t.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[Gn]||(e[Gn]=new Set)).add(t)}function un(e,t){t.split(/\s+/).forEach(s=>s&&e.classList.remove(s));const n=e[Gn];n&&(n.delete(t),n.size||(e[Gn]=void 0))}function vo(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let Ou=0;function _o(e,t,n,s){const r=e._endId=++Ou,i=()=>{r===e._endId&&s()};if(n!=null)return setTimeout(i,n);const{type:o,timeout:a,propCount:l}=Lu(e,t);if(!o)return s();const f=o+"end";let u=0;const d=()=>{e.removeEventListener(f,g),i()},g=y=>{y.target===e&&++u>=l&&d()};setTimeout(()=>{u(n[E]||"").split(", "),r=s(`${Xt}Delay`),i=s(`${Xt}Duration`),o=To(r,i),a=s(`${Wn}Delay`),l=s(`${Wn}Duration`),f=To(a,l);let u=null,d=0,g=0;t===Xt?o>0&&(u=Xt,d=o,g=i.length):t===Wn?f>0&&(u=Wn,d=f,g=l.length):(d=Math.max(o,f),u=d>0?o>f?Xt:Wn:null,g=u?u===Xt?i.length:l.length:0);const y=u===Xt&&/\b(transform|all)(,|$)/.test(s(`${Xt}Property`).toString());return{type:u,timeout:d,propCount:g,hasTransform:y}}function To(e,t){for(;e.lengthko(n)+ko(e[s])))}function ko(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function So(){return document.body.offsetHeight}function $u(e,t,n){const s=e[Gn];s&&(t=(t?[t,...s]:[...s]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const Eo=Symbol("_vod"),Du=Symbol("_vsh"),Nu=Symbol(""),Fu=/(^|;)\s*display\s*:/;function Bu(e,t,n){const s=e.style,r=Pe(n);let i=!1;if(n&&!r){if(t)if(Pe(t))for(const o of t.split(";")){const a=o.slice(0,o.indexOf(":")).trim();n[a]==null&&Rs(s,a,"")}else for(const o in t)n[o]==null&&Rs(s,o,"");for(const o in n)o==="display"&&(i=!0),Rs(s,o,n[o])}else if(r){if(t!==n){const o=s[Nu];o&&(n+=";"+o),s.cssText=n,i=Fu.test(n)}}else t&&e.removeAttribute("style");Eo in e&&(e[Eo]=i?s.display:"",e[Du]&&(s.display="none"))}const Ao=/\s*!important$/;function Rs(e,t,n){if(Q(n))n.forEach(s=>Rs(e,t,s));else if(n==null&&(n=""),t.startsWith("--"))e.setProperty(t,n);else{const s=Hu(e,t);Ao.test(n)?e.setProperty(en(s),n.replace(Ao,""),"important"):e[s]=n}}const Ro=["Webkit","Moz","ms"],_r={};function Hu(e,t){const n=_r[t];if(n)return n;let s=jt(t);if(s!=="filter"&&s in e)return _r[t]=s;s=ri(s);for(let r=0;rTr||(Vu.then(()=>Tr=0),Tr=Date.now());function Wu(e,t){const n=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=n.attached)return;Tt(Gu(s,n.value),t,5,[s])};return n.value=e,n.attached=qu(),n}function Gu(e,t){if(Q(t)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},t.map(s=>r=>!r._stopped&&s&&s(r))}else return t}const Lo=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Ku=(e,t,n,s,r,i)=>{const o=r==="svg";t==="class"?$u(e,s,o):t==="style"?Bu(e,n,s):ts(t)?Hs(t)||Uu(e,t,n,s,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Yu(e,t,s,o))?(Io(e,t,s),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&Po(e,t,s,o,i,t!=="value")):e._isVueCE&&(/[A-Z]/.test(t)||!Pe(s))?Io(e,jt(t),s,i,t):(t==="true-value"?e._trueValue=s:t==="false-value"&&(e._falseValue=s),Po(e,t,s,o))};function Yu(e,t,n,s){if(s)return!!(t==="innerHTML"||t==="textContent"||t in e&&Lo(t)&&be(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return Lo(t)&&Pe(n)?!1:t in e}const $o=e=>{const t=e.props["onUpdate:modelValue"]||!1;return Q(t)?n=>rs(t,n):t};function Zu(e){e.target.composing=!0}function Do(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const kr=Symbol("_assign"),Xu={created(e,{modifiers:{lazy:t,trim:n,number:s}},r){e[kr]=$o(r);const i=s||r.props&&r.props.type==="number";vn(e,t?"change":"input",o=>{if(o.target.composing)return;let a=e.value;n&&(a=a.trim()),i&&(a=Vs(a)),e[kr](a)}),n&&vn(e,"change",()=>{e.value=e.value.trim()}),t||(vn(e,"compositionstart",Zu),vn(e,"compositionend",Do),vn(e,"change",Do))},mounted(e,{value:t}){e.value=t==null?"":t},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:s,trim:r,number:i}},o){if(e[kr]=$o(o),e.composing)return;const a=(i||e.type==="number")&&!/^0\d/.test(e.value)?Vs(e.value):e.value,l=t==null?"":t;a!==l&&(document.activeElement===e&&e.type!=="range"&&(s&&t===n||r&&e.value.trim()===l)||(e.value=l))}},Qu=["ctrl","shift","alt","meta"],Ju={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>Qu.some(n=>e[`${n}Key`]&&!t.includes(n))},pt=(e,t)=>{const n=e._withMods||(e._withMods={}),s=t.join(".");return n[s]||(n[s]=(r,...i)=>{for(let o=0;o{const t=tc().createApp(...e),{mount:n}=t;return t.mount=s=>{const r=rc(s);if(!r)return;const i=t._component;!be(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent="");const o=n(r,!1,sc(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),o},t};function sc(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function rc(e){return Pe(e)?document.querySelector(e):e}const ic=["aria-pressed"],oc={key:0,viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":"true"},lc={key:1,viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",fill:"none"},ac={__name:"ChatbotToggler",props:{isOpen:{type:Boolean,required:!0}},emits:["toggle"],setup(e){return(t,n)=>(F(),W("button",{class:"fixed bottom-5 right-5 z-9999 grid h-12 w-12 appearance-none place-items-center rounded-full border border-white/20 bg-gradient-to-br from-brand-500 to-brand-600 text-white shadow-[0_20px_36px_-20px_rgba(109,79,194,0.85)] transition-all duration-250 hover:-translate-y-0.5 hover:from-brand-600 hover:to-violet-700 hover:shadow-[0_22px_40px_-22px_rgba(109,79,194,1)] focus:outline-none max-[600px]:bottom-3 max-[600px]:right-3 max-[600px]:h-13 max-[600px]:w-13",style:{"border-radius":"9999px"},"aria-pressed":e.isOpen?"true":"false",onClick:n[0]||(n[0]=s=>t.$emit("toggle"))},[e.isOpen?(F(),W("svg",lc,n[2]||(n[2]=[w("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"},null,-1)]))):(F(),W("svg",oc,n[1]||(n[1]=[w("path",{d:"M4 4h16a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H8l-4 4v-4H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z",fill:"currentColor",stroke:"currentColor","stroke-width":"2","stroke-linecap":"miter","stroke-linejoin":"miter"},null,-1)])))],8,ic))}},uc={class:"chat-header relative flex min-h-14 items-center justify-between px-4 pb-2.5 pt-3 text-white sm:px-5"},cc={class:"flex min-w-0 flex-1 items-center gap-2 sm:gap-2.5"},fc={xmlns:"http://www.w3.org/2000/svg",width:"35",height:"35",viewBox:"0 0 1024 1024",class:"h-8 w-8 shrink-0 rounded-full bg-white p-1.5 shadow-md motion-safe:animate-soft-float",style:{fill:"#6d4fc2"}},pc={class:"ml-2 flex items-center gap-1.5"},dc=["title"],hc=["title","aria-label"],gc={key:0,viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},mc={key:1,viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},bc=["title","aria-label"],xc={key:0,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},yc={key:1,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},wc={key:2,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},vc={__name:"ChatHeader",props:{windowMode:{type:String,required:!0},autoReadEnabled:{type:Boolean,required:!0},activeTtsProvider:{type:String,required:!0}},emits:["close","cycleResize","toggleAutoRead"],setup(e){const t=e,n={default:"Compact",half:"Half Screen",full:"Full Screen"},s=Ee(()=>n[t.windowMode]||"Compact"),r=Ee(()=>t.windowMode==="default"?"Half Screen":t.windowMode==="half"?"Full Screen":"Compact"),i=Ee(()=>t.activeTtsProvider==="polly"?"TTS: Polly":t.activeTtsProvider==="browser"?"TTS: Browser":"TTS: Off"),o=Ee(()=>t.activeTtsProvider==="polly"?"bg-emerald-500/45":t.activeTtsProvider==="browser"?"bg-amber-500/45":"bg-slate-500/35");return(a,l)=>(F(),W("div",uc,[w("div",cc,[(F(),W("svg",fc,l[3]||(l[3]=[w("path",{d:"M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"},null,-1)]))),l[4]||(l[4]=w("h2",{class:"truncate text-xs font-semibold tracking-[0.01em] sm:text-base text-white/95"},"ChangAI from ERPGulf",-1))]),w("div",pc,[w("span",{class:we(["hidden rounded-full border border-white/25 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-white/95 shadow-sm backdrop-blur-sm sm:inline",o.value]),title:`TTS provider: ${i.value}`},Je(i.value),11,dc),w("button",{class:we(["h-8 min-w-8 appearance-none items-center justify-center rounded-md border border-white/20 px-2 text-xs font-semibold text-white/90 transition-all duration-200 focus:outline-none sm:flex",e.autoReadEnabled?"bg-white/24 shadow-sm":"hover:bg-white/15"]),style:{"border-radius":"0.375rem"},title:e.autoReadEnabled?"Auto speech on":"Auto speech off","aria-label":e.autoReadEnabled?"Turn off auto speech":"Turn on auto speech",onClick:l[0]||(l[0]=f=>a.$emit("toggleAutoRead"))},[e.autoReadEnabled?(F(),W("svg",gc,l[5]||(l[5]=[w("path",{d:"M11 5L6 9H3v6h3l5 4V5z"},null,-1),w("path",{d:"M15 9a4 4 0 0 1 0 6"},null,-1),w("path",{d:"M18 7a7 7 0 0 1 0 10"},null,-1)]))):(F(),W("svg",mc,l[6]||(l[6]=[w("path",{d:"M11 5L6 9H3v6h3l5 4V5z"},null,-1),w("path",{d:"M22 9l-6 6"},null,-1),w("path",{d:"M16 9l6 6"},null,-1)])))],10,hc),w("button",{class:we(["flex h-8 min-w-8 appearance-none items-center justify-center rounded-md border border-white/20 px-2 text-xs font-semibold text-white/90 transition-all duration-200 focus:outline-none","bg-white/20 shadow-sm hover:bg-white/25"]),style:{"border-radius":"0.375rem"},title:`Resize mode: ${s.value} (click to ${r.value})`,"aria-label":`Resize mode ${s.value}. Click to switch to ${r.value}`,onClick:l[1]||(l[1]=f=>a.$emit("cycleResize"))},[e.windowMode==="default"?(F(),W("svg",xc,l[7]||(l[7]=[w("rect",{x:"7",y:"8",width:"10",height:"8",rx:"2"},null,-1)]))):e.windowMode==="half"?(F(),W("svg",yc,l[8]||(l[8]=[w("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"},null,-1),w("path",{d:"M12 5v14"},null,-1)]))):(F(),W("svg",wc,l[9]||(l[9]=[w("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"},null,-1),w("path",{d:"M8 8H6v2M16 8h2v2M8 16H6v-2M16 16h2v-2"},null,-1)])))],8,bc),w("button",{class:"grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border border-white/20 text-white transition-all duration-200 hover:scale-105 hover:bg-white/20 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/70",style:{"border-radius":"9999px"},"aria-label":"Close chatbot",onClick:l[2]||(l[2]=f=>a.$emit("close"))},l[10]||(l[10]=[w("svg",{xmlns:"http://www.w3.org/2000/svg",height:"24",width:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},[w("path",{d:"M6 9l6 6 6-6"})],-1)]))])]))}},_c={class:"flex gap-1.5 border-b border-slate-200/80 px-2.5 pb-2.5 pt-1"},Tc=["onClick"],kc={class:"inline-flex items-center gap-1.5"},Sc={__name:"TabBar",props:{modelValue:{type:String,required:!0},debugEnabled:{type:Boolean,default:!1}},emits:["update:modelValue"],setup(e){const t=e,n=Ee(()=>{const s=[{id:"chat",label:"Chats"},{id:"debug",label:"Debug"},{id:"support",label:"Support"},{id:"settings",label:"Settings"}];return t.debugEnabled?s:s.filter(r=>r.id!=="debug")});return(s,r)=>(F(),W("div",_c,[(F(!0),W(He,null,ws(n.value,i=>(F(),W("button",{key:i.id,class:we(["group min-w-0 flex-1 h-9 appearance-none rounded-lg border border-transparent bg-transparent px-2 text-xs font-semibold transition-all duration-200 focus:outline-none",e.modelValue===i.id?"border-white/30 bg-linear-to-r from-violet-300/36 via-indigo-300/30 to-sky-300/28 text-white shadow-[0_4px_10px_rgba(20,24,40,0.22)]":"text-white/80 hover:border-white/25 hover:bg-white/12 hover:text-white"]),onClick:o=>s.$emit("update:modelValue",i.id)},[w("span",kc,[w("span",{class:we(["h-1.5 w-1.5 rounded-full transition-colors duration-200",e.modelValue===i.id?"bg-white":"bg-white/40 group-hover:bg-white/70"])},null,2),Ss(" "+Je(i.label),1)])],10,Tc))),128))]))}},Ec=(e,t)=>{const n=e.__vccOpts||e;for(const[s,r]of t)n[s]=r;return n},Ac={},Rc={xmlns:"http://www.w3.org/2000/svg",width:"50",height:"50",viewBox:"0 0 1024 1024",class:"h-7.5 w-7.5 shrink-0 self-end rounded-full bg-gradient-to-br from-brand-500 to-brand-600 p-1.5 fill-white shadow-[0_10px_18px_-12px_rgba(109,79,194,0.85)]"};function Cc(e,t){return F(),W("svg",Rc,t[0]||(t[0]=[w("path",{d:"M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"},null,-1)]))}const Fo=Ec(Ac,[["render",Cc]]),Cs={PIPELINE:"changai.changai.api.v2.text2sql_pipeline_v2.run_text2sql_pipeline",SUPPORT:"changai.changai.api.v2.text2sql_pipeline_v2.support_bot",SETTINGS:"changai.changai.api.v2.text2sql_pipeline_v2.get_frontend_settings",TTS:"changai.changai.api.v2.text2sql_pipeline_v2.synthesize_tts"};function Bo(e,t={},n="actual"){return n==="test"?Promise.resolve({Bot:`[TEST MODE] ${JSON.stringify(t)}`}):!window.frappe||!window.frappe.call?Promise.reject(new Error("Frappe API is unavailable in actual mode.")):new Promise((s,r)=>{window.frappe.call({method:e,args:t,callback(i){s(i.message)},error(i){r(i)}})})}function Pc(e,t,n="actual",s=null,r){if(n==="test")return{promise:Promise.resolve({Bot:`[TEST MODE] ${JSON.stringify({user_question:e,chat_id:t,request_id:s,sendNonErptoAI:r})}`}),cancel:()=>!1};if(!window.frappe||!window.frappe.call)return{promise:Promise.reject(new Error("Frappe API is unavailable in actual mode.")),cancel:()=>!1};let i=null,o=!1;return{promise:new Promise((f,u)=>{i=window.frappe.call({method:Cs.PIPELINE,args:{user_question:e,chat_id:t,request_id:s,sendNonErptoAI:r},callback(d){o=!0,f(d.message)},error(d){o=!0,u(d)}})}),cancel:()=>o||!i||typeof i.abort!="function"?!1:(i.abort(),o=!0,!0)}}function Ic(e,t="actual"){if(t==="test")return{promise:Promise.resolve(`[TEST MODE] ${JSON.stringify({message:e})}`),cancel:()=>!1};if(!window.frappe||!window.frappe.call)return{promise:Promise.reject(new Error("Frappe API is unavailable in actual mode.")),cancel:()=>!1};let n=null,s=!1;return{promise:new Promise((o,a)=>{n=window.frappe.call({method:Cs.SUPPORT,args:{message:e},callback(l){s=!0,o(l.message)},error(l){s=!0,a(l)}})}),cancel:()=>s||!n||typeof n.abort!="function"?!1:(n.abort(),s=!0,!0)}}function Mc(e="actual"){return Bo(Cs.SETTINGS,{},e)}function Oc(e,t="Zayd",n="actual"){return Bo(Cs.TTS,{text:e,voice_id:t},n)}function Sr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var cn=Sr();function Ho(e){cn=e}var fn={exec:()=>null};function le(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(r,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(We.caret,"$1"),n=n.replace(r,o),s},getRegex:()=>new RegExp(n,t)};return s}var Lc=((e="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},$c=/^(?:[ \t]*(?:\n|$))+/,Dc=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Nc=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Kn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Fc=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Er=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zo=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Uo=le(zo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Bc=le(zo).replace(/bull/g,Er).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ar=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Hc=/^[^\n]+/,Rr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,zc=le(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Rr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Uc=le(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Er).getRegex(),Ps="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Cr=/|$))/,jc=le("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Cr).replace("tag",Ps).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),jo=le(Ar).replace("hr",Kn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Ps).getRegex(),Vc=le(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",jo).getRegex(),Pr={blockquote:Vc,code:Dc,def:zc,fences:Nc,heading:Fc,hr:Kn,html:jc,lheading:Uo,list:Uc,newline:$c,paragraph:jo,table:fn,text:Hc},Vo=le("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Kn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Ps).getRegex(),qc={...Pr,lheading:Bc,table:Vo,paragraph:le(Ar).replace("hr",Kn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Vo).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Ps).getRegex()},Wc={...Pr,html:le(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Cr).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:fn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:le(Ar).replace("hr",Kn).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",Uo).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Gc=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Kc=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,qo=/^( {2,}|\\)\n(?!\s*$)/,Yc=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Lc?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Go=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,ef=le(Go,"u").replace(/punct/g,_n).getRegex(),tf=le(Go,"u").replace(/punct/g,Wo).getRegex(),Ko="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",nf=le(Ko,"gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Is).replace(/punct/g,_n).getRegex(),sf=le(Ko,"gu").replace(/notPunctSpace/g,Qc).replace(/punctSpace/g,Xc).replace(/punct/g,Wo).getRegex(),rf=le("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Is).replace(/punct/g,_n).getRegex(),of=le(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,_n).getRegex(),lf="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",af=le(lf,"gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Is).replace(/punct/g,_n).getRegex(),uf=le(/\\(punct)/,"gu").replace(/punct/g,_n).getRegex(),cf=le(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ff=le(Cr).replace("(?:-->|$)","-->").getRegex(),pf=le("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",ff).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ms=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,df=le(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Ms).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Yo=le(/^!?\[(label)\]\[(ref)\]/).replace("label",Ms).replace("ref",Rr).getRegex(),Zo=le(/^!?\[(ref)\](?:\[\])?/).replace("ref",Rr).getRegex(),hf=le("reflink|nolink(?!\\()","g").replace("reflink",Yo).replace("nolink",Zo).getRegex(),Xo=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Mr={_backpedal:fn,anyPunctuation:uf,autolink:cf,blockSkip:Jc,br:qo,code:Kc,del:fn,delLDelim:fn,delRDelim:fn,emStrongLDelim:ef,emStrongRDelimAst:nf,emStrongRDelimUnd:rf,escape:Gc,link:df,nolink:Zo,punctuation:Zc,reflink:Yo,reflinkSearch:hf,tag:pf,text:Yc,url:fn},gf={...Mr,link:le(/^!?\[(label)\]\((.*?)\)/).replace("label",Ms).getRegex(),reflink:le(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ms).getRegex()},Or={...Mr,emStrongRDelimAst:sf,emStrongLDelim:tf,delLDelim:of,delRDelim:af,url:le(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Xo).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:le(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Qo=e=>bf[e];function Ct(e,t){if(t){if(We.escapeTest.test(e))return e.replace(We.escapeReplace,Qo)}else if(We.escapeTestNoEncode.test(e))return e.replace(We.escapeReplaceNoEncode,Qo);return e}function Jo(e){try{e=encodeURI(e).replace(We.percentDecode,"%")}catch{return null}return e}function el(e,t){var i;let n=e.replace(We.findPipe,(o,a,l)=>{let f=!1,u=a;for(;--u>=0&&l[u]==="\\";)f=!f;return f?"|":" |"}),s=n.split(We.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!((i=s.at(-1))!=null&&i.trim())&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length=0&&We.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(` `)}function xf(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let s=0;s0?-2:-1}function yf(e,t=0){let n=t,s="";for(let r of e)if(r===" "){let i=4-n%4;s+=" ".repeat(i),n+=i}else s+=r,n++;return s}function nl(e,t,n,s,r){let i=t.href,o=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,l}function wf(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(` `).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[a]=o;return a.length>=r.length?i.slice(r.length):i}).join(` -`)}var Ls=class{constructor(e){we(this,"options");we(this,"rules");we(this,"lexer");this.options=e||un}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:tl(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=wf(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=Xt(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:Xt(t[0],` -`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Xt(t[0],` -`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Xt(t[0],` +`)}var Ls=class{constructor(e){_e(this,"options");_e(this,"rules");_e(this,"lexer");this.options=e||cn}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:tl(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=wf(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=Qt(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:Qt(t[0],` +`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Qt(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Qt(t[0],` `).split(` -`),s="",r="",i=[];for(;n.length>0;){let o=!1,a=[],l;for(l=0;l0;){let o=!1,a=[],l;for(l=0;l1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let l=!1,c="",u="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let p=yf(t[2].split(` +`),x=this.list(E);i[i.length-1]=x,s=s.substring(0,s.length-g.raw.length)+x.raw,r=r.substring(0,r.length-y.raw.length)+x.raw,n=E.substring(i.at(-1).raw.length).split(` +`);continue}}return{type:"blockquote",raw:s,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let l=!1,f="",u="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;f=t[0],e=e.substring(f.length);let d=yf(t[2].split(` `,1)[0],t[1].length),g=e.split(` -`,1)[0],w=!p.trim(),E=0;if(this.options.pedantic?(E=2,u=p.trimStart()):w?E=t[1].length+1:(E=p.search(this.rules.other.nonSpaceChar),E=E>4?1:E,u=p.slice(E),E+=t[1].length),w&&this.rules.other.blankLine.test(g)&&(c+=g+` -`,e=e.substring(g.length+1),l=!0),!l){let m=this.rules.other.nextBulletRegex(E),A=this.rules.other.hrRegex(E),T=this.rules.other.fencesBeginRegex(E),W=this.rules.other.headingBeginRegex(E),K=this.rules.other.htmlBeginRegex(E),O=this.rules.other.blockquoteBeginRegex(E);for(;e;){let z=e.split(` -`,1)[0],P;if(g=z,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),P=g):P=g.replace(this.rules.other.tabCharGlobal," "),T.test(g)||W.test(g)||K.test(g)||O.test(g)||m.test(g)||A.test(g))break;if(P.search(this.rules.other.nonSpaceChar)>=E||!g.trim())u+=` -`+P.slice(E);else{if(w||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||T.test(p)||W.test(p)||A.test(p))break;u+=` -`+g}w=!g.trim(),c+=z+` -`,e=e.substring(z.length+1),p=P.slice(E)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=c}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let l of r.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&((c==null?void 0:c.type)==="text"||(c==null?void 0:c.type)==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=p.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=p.raw+l.tokens[0].raw,l.tokens[0].text=p.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(p)):l.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):l.tokens.unshift(p)}}else l.task&&(l.task=!1);if(!r.loose){let u=l.tokens.filter(g=>g.type==="space"),p=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=p}}if(r.loose)for(let l of r.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=tl(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:Xt(t[0],` +`,1)[0],y=!d.trim(),E=0;if(this.options.pedantic?(E=2,u=d.trimStart()):y?E=t[1].length+1:(E=d.search(this.rules.other.nonSpaceChar),E=E>4?1:E,u=d.slice(E),E+=t[1].length),y&&this.rules.other.blankLine.test(g)&&(f+=g+` +`,e=e.substring(g.length+1),l=!0),!l){let x=this.rules.other.nextBulletRegex(E),M=this.rules.other.hrRegex(E),m=this.rules.other.fencesBeginRegex(E),H=this.rules.other.headingBeginRegex(E),Y=this.rules.other.htmlBeginRegex(E),$=this.rules.other.blockquoteBeginRegex(E);for(;e;){let z=e.split(` +`,1)[0],O;if(g=z,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),O=g):O=g.replace(this.rules.other.tabCharGlobal," "),m.test(g)||H.test(g)||Y.test(g)||$.test(g)||x.test(g)||M.test(g))break;if(O.search(this.rules.other.nonSpaceChar)>=E||!g.trim())u+=` +`+O.slice(E);else{if(y||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||m.test(d)||H.test(d)||M.test(d))break;u+=` +`+g}y=!g.trim(),f+=z+` +`,e=e.substring(z.length+1),d=O.slice(E)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(f)&&(o=!0)),r.items.push({type:"list_item",raw:f,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=f}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let l of r.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let f=l.tokens[0];if(l.task&&((f==null?void 0:f.type)==="text"||(f==null?void 0:f.type)==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),f.raw=f.raw.replace(this.rules.other.listReplaceTask,""),f.text=f.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=d.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1);if(!r.loose){let u=l.tokens.filter(g=>g.type==="space"),d=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=d}}if(r.loose)for(let l of r.items){l.loose=!0;for(let f of l.tokens)f.type==="text"&&(f.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=tl(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:Qt(t[0],` `),href:s,title:r}}}table(e){var o;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=el(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=(o=t[3])!=null&&o.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` -`):[],i={type:"table",raw:Xt(t[0],` -`),header:[],align:[],rows:[]};if(n.length===s.length){for(let a of s)this.rules.other.tableAlignRight.test(a)?i.align.push("right"):this.rules.other.tableAlignCenter.test(a)?i.align.push("center"):this.rules.other.tableAlignLeft.test(a)?i.align.push("left"):i.align.push(null);for(let a=0;a({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[c]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:Xt(t[0],` +`):[],i={type:"table",raw:Qt(t[0],` +`),header:[],align:[],rows:[]};if(n.length===s.length){for(let a of s)this.rules.other.tableAlignRight.test(a)?i.align.push("right"):this.rules.other.tableAlignCenter.test(a)?i.align.push("center"):this.rules.other.tableAlignLeft.test(a)?i.align.push("left"):i.align.push(null);for(let a=0;a({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[f]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:Qt(t[0],` `),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` -`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Xt(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=xf(t[2],"()");if(i===-2)return;if(i>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),nl(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return nl(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,a=r,l=0,c=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(o=[...i].length,s[3]||s[4]){a+=o;continue}else if((s[5]||s[6])&&r%3&&!((r+o)%3)){l+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a+l);let u=[...s[0]][0].length,p=e.slice(0,r+s.index+u+o);if(Math.min(r,o)%2){let w=p.slice(1,-1);return{type:"em",raw:p,text:w,tokens:this.lexer.inlineTokens(w)}}let g=p.slice(2,-2);return{type:"strong",raw:p,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,a=r,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+r);(s=l.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(o=[...i].length,o!==r))continue;if(s[3]||s[4]){a+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a);let c=[...s[0]][0].length,u=e.slice(0,r+s.index+c+o),p=u.slice(r,-r);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,s;let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let o;do o=t[0],t[0]=(s=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?s:"";while(o!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},mt=class Qr{constructor(t){we(this,"tokens");we(this,"options");we(this,"state");we(this,"inlineQueue");we(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||un,this.options.tokenizer=this.options.tokenizer||new Ls,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:qe,block:Ms.normal,inline:Kn.normal};this.options.pedantic?(n.block=Ms.pedantic,n.inline=Kn.pedantic):this.options.gfm&&(n.block=Ms.gfm,this.options.breaks?n.inline=Kn.breaks:n.inline=Kn.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ms,inline:Kn}}static lex(t,n){return new Qr(n).lex(t)}static lexInline(t,n){return new Qr(n).inlineTokens(t)}lex(t){t=t.replace(qe.carriageReturn,` -`),this.blockTokens(t,this.tokens);for(let n=0;n(l=u.call({lexer:this},t,n))?(t=t.substring(l.raw.length),n.push(l),!0):!1))continue;if(l=this.tokenizer.space(t)){t=t.substring(l.raw.length);let u=n.at(-1);l.raw.length===1&&u!==void 0?u.raw+=` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Qt(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=xf(t[2],"()");if(i===-2)return;if(i>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),nl(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return nl(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,a=r,l=0,f=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+r);(s=f.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(o=[...i].length,s[3]||s[4]){a+=o;continue}else if((s[5]||s[6])&&r%3&&!((r+o)%3)){l+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a+l);let u=[...s[0]][0].length,d=e.slice(0,r+s.index+u+o);if(Math.min(r,o)%2){let y=d.slice(1,-1);return{type:"em",raw:d,text:y,tokens:this.lexer.inlineTokens(y)}}let g=d.slice(2,-2);return{type:"strong",raw:d,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,a=r,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+r);(s=l.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(o=[...i].length,o!==r))continue;if(s[3]||s[4]){a+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a);let f=[...s[0]][0].length,u=e.slice(0,r+s.index+f+o),d=u.slice(r,-r);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,s;let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let o;do o=t[0],t[0]=(s=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?s:"";while(o!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},yt=class Xr{constructor(t){_e(this,"tokens");_e(this,"options");_e(this,"state");_e(this,"inlineQueue");_e(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||cn,this.options.tokenizer=this.options.tokenizer||new Ls,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:We,block:Os.normal,inline:Yn.normal};this.options.pedantic?(n.block=Os.pedantic,n.inline=Yn.pedantic):this.options.gfm&&(n.block=Os.gfm,this.options.breaks?n.inline=Yn.breaks:n.inline=Yn.gfm),this.tokenizer.rules=n}static get rules(){return{block:Os,inline:Yn}}static lex(t,n){return new Xr(n).lex(t)}static lexInline(t,n){return new Xr(n).inlineTokens(t)}lex(t){t=t.replace(We.carriageReturn,` +`),this.blockTokens(t,this.tokens);for(let n=0;n(l=u.call({lexer:this},t,n))?(t=t.substring(l.raw.length),n.push(l),!0):!1))continue;if(l=this.tokenizer.space(t)){t=t.substring(l.raw.length);let u=n.at(-1);l.raw.length===1&&u!==void 0?u.raw+=` `:n.push(l);continue}if(l=this.tokenizer.code(t)){t=t.substring(l.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` `)?"":` `)+l.raw,u.text+=` `+l.text,this.inlineQueue.at(-1).src=u.text):n.push(l);continue}if(l=this.tokenizer.fences(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.heading(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.hr(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.blockquote(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.list(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.html(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.def(t)){t=t.substring(l.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` `)?"":` `)+l.raw,u.text+=` -`+l.raw,this.inlineQueue.at(-1).src=u.text):this.tokens.links[l.tag]||(this.tokens.links[l.tag]={href:l.href,title:l.title},n.push(l));continue}if(l=this.tokenizer.table(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.lheading(t)){t=t.substring(l.raw.length),n.push(l);continue}let c=t;if((a=this.options.extensions)!=null&&a.startBlock){let u=1/0,p=t.slice(1),g;this.options.extensions.startBlock.forEach(w=>{g=w.call({lexer:this},p),typeof g=="number"&&g>=0&&(u=Math.min(u,g))}),u<1/0&&u>=0&&(c=t.substring(0,u+1))}if(this.state.top&&(l=this.tokenizer.paragraph(c))){let u=n.at(-1);s&&(u==null?void 0:u.type)==="paragraph"?(u.raw+=(u.raw.endsWith(` +`+l.raw,this.inlineQueue.at(-1).src=u.text):this.tokens.links[l.tag]||(this.tokens.links[l.tag]={href:l.href,title:l.title},n.push(l));continue}if(l=this.tokenizer.table(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.lheading(t)){t=t.substring(l.raw.length),n.push(l);continue}let f=t;if((a=this.options.extensions)!=null&&a.startBlock){let u=1/0,d=t.slice(1),g;this.options.extensions.startBlock.forEach(y=>{g=y.call({lexer:this},d),typeof g=="number"&&g>=0&&(u=Math.min(u,g))}),u<1/0&&u>=0&&(f=t.substring(0,u+1))}if(this.state.top&&(l=this.tokenizer.paragraph(f))){let u=n.at(-1);s&&(u==null?void 0:u.type)==="paragraph"?(u.raw+=(u.raw.endsWith(` `)?"":` `)+l.raw,u.text+=` -`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(l),s=c.length!==t.length,t=t.substring(l.raw.length);continue}if(l=this.tokenizer.text(t)){t=t.substring(l.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` +`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(l),s=f.length!==t.length,t=t.substring(l.raw.length);continue}if(l=this.tokenizer.text(t)){t=t.substring(l.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` `)?"":` `)+l.raw,u.text+=` -`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(l);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var c,u,p,g,w,E;this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let m=Object.keys(this.tokens.links);if(m.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)m.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)i=r[2]?r[2].length:0,s=s.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=(p=(u=(c=this.options.hooks)==null?void 0:c.emStrongMask)==null?void 0:u.call({lexer:this},s))!=null?p:s;let o=!1,a="",l=1/0;for(;t;){if(t.length(m=T.call({lexer:this},t,n))?(t=t.substring(m.raw.length),n.push(m),!0):!1))continue;if(m=this.tokenizer.escape(t)){t=t.substring(m.raw.length),n.push(m);continue}if(m=this.tokenizer.tag(t)){t=t.substring(m.raw.length),n.push(m);continue}if(m=this.tokenizer.link(t)){t=t.substring(m.raw.length),n.push(m);continue}if(m=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(m.raw.length);let T=n.at(-1);m.type==="text"&&(T==null?void 0:T.type)==="text"?(T.raw+=m.raw,T.text+=m.text):n.push(m);continue}if(m=this.tokenizer.emStrong(t,s,a)){t=t.substring(m.raw.length),n.push(m);continue}if(m=this.tokenizer.codespan(t)){t=t.substring(m.raw.length),n.push(m);continue}if(m=this.tokenizer.br(t)){t=t.substring(m.raw.length),n.push(m);continue}if(m=this.tokenizer.del(t,s,a)){t=t.substring(m.raw.length),n.push(m);continue}if(m=this.tokenizer.autolink(t)){t=t.substring(m.raw.length),n.push(m);continue}if(!this.state.inLink&&(m=this.tokenizer.url(t))){t=t.substring(m.raw.length),n.push(m);continue}let A=t;if((E=this.options.extensions)!=null&&E.startInline){let T=1/0,W=t.slice(1),K;this.options.extensions.startInline.forEach(O=>{K=O.call({lexer:this},W),typeof K=="number"&&K>=0&&(T=Math.min(T,K))}),T<1/0&&T>=0&&(A=t.substring(0,T+1))}if(m=this.tokenizer.inlineText(A)){t=t.substring(m.raw.length),m.raw.slice(-1)!=="_"&&(a=m.raw.slice(-1)),o=!0;let T=n.at(-1);(T==null?void 0:T.type)==="text"?(T.raw+=m.raw,T.text+=m.text):n.push(m);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(!this.options.silent)throw new Error(n)}},Os=class{constructor(e){we(this,"options");we(this,"parser");this.options=e||un}space(e){return""}code({text:e,lang:t,escaped:n}){var i;let s=(i=(t||"").match(qe.notSpaceStart))==null?void 0:i[0],r=e.replace(qe.endingNewline,"")+` -`;return s?'
'+(n?r:Rt(r,!0))+`
-`:"
"+(n?r:Rt(r,!0))+`
+`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(l);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var f,u,d,g,y,E;this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let x=Object.keys(this.tokens.links);if(x.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)x.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)i=r[2]?r[2].length:0,s=s.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=(d=(u=(f=this.options.hooks)==null?void 0:f.emStrongMask)==null?void 0:u.call({lexer:this},s))!=null?d:s;let o=!1,a="",l=1/0;for(;t;){if(t.length(x=m.call({lexer:this},t,n))?(t=t.substring(x.raw.length),n.push(x),!0):!1))continue;if(x=this.tokenizer.escape(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.tag(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.link(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(x.raw.length);let m=n.at(-1);x.type==="text"&&(m==null?void 0:m.type)==="text"?(m.raw+=x.raw,m.text+=x.text):n.push(x);continue}if(x=this.tokenizer.emStrong(t,s,a)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.codespan(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.br(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.del(t,s,a)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.autolink(t)){t=t.substring(x.raw.length),n.push(x);continue}if(!this.state.inLink&&(x=this.tokenizer.url(t))){t=t.substring(x.raw.length),n.push(x);continue}let M=t;if((E=this.options.extensions)!=null&&E.startInline){let m=1/0,H=t.slice(1),Y;this.options.extensions.startInline.forEach($=>{Y=$.call({lexer:this},H),typeof Y=="number"&&Y>=0&&(m=Math.min(m,Y))}),m<1/0&&m>=0&&(M=t.substring(0,m+1))}if(x=this.tokenizer.inlineText(M)){t=t.substring(x.raw.length),x.raw.slice(-1)!=="_"&&(a=x.raw.slice(-1)),o=!0;let m=n.at(-1);(m==null?void 0:m.type)==="text"?(m.raw+=x.raw,m.text+=x.text):n.push(x);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(!this.options.silent)throw new Error(n)}},$s=class{constructor(e){_e(this,"options");_e(this,"parser");this.options=e||cn}space(e){return""}code({text:e,lang:t,escaped:n}){var i;let s=(i=(t||"").match(We.notSpaceStart))==null?void 0:i[0],r=e.replace(We.endingNewline,"")+` +`;return s?'
'+(n?r:Ct(r,!0))+`
+`:"
"+(n?r:Ct(r,!0))+`
`}blockquote({tokens:e}){return`
${this.parser.parse(e)}
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} @@ -63,7 +63,7 @@ ${this.parser.parse(e)} `}tablerow({text:e}){return` ${e} `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` -`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${Rt(e,!0)}`}br(e){return"
"}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=Jo(e);if(r===null)return s;e=r;let i='
",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Jo(e);if(r===null)return Rt(n);e=r;let i=`${Rt(n)}{let l=o[a].flat(1/0);n=n.concat(this.walkTokens(l,t))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let a=r.renderer.apply(this,o);return a===!1&&(a=i.apply(this,o)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new Os(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,a=n.renderer[o],l=r[o];r[o]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new Ls(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,a=n.tokenizer[o],l=r[o];r[o]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new Yn;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,a=n.hooks[o],l=r[o];Yn.passThroughHooks.has(i)?r[o]=c=>{if(this.defaults.async&&Yn.passThroughHooksRespectAsync.has(i))return(async()=>{let p=await a.call(r,c);return l.call(r,p)})();let u=a.call(r,c);return l.call(r,u)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let p=await a.apply(r,c);return p===!1&&(p=await l.apply(r,c)),p})();let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(i.call(this,o)),r&&(a=a.concat(r.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return mt.lex(e,t!=null?t:this.defaults)}parser(e,t){return bt.parse(e,t!=null?t:this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},r={...this.defaults,...s},i=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?mt.lex:mt.lexInline)(o,r),l=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(e):e?bt.parse:bt.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(i);try{r.hooks&&(t=r.hooks.preprocess(t));let o=(r.hooks?r.hooks.provideLexer(e):e?mt.lex:mt.lexInline)(t,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?bt.parse:bt.parseInline)(o,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(o){return i(o)}}}onError(e,t){return n=>{if(n.message+=` -Please report this to https://github.com/markedjs/marked.`,e){let s="

An error occurred:

"+Rt(n.message+"",!0)+"
";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},fn=new vf;function xe(e,t){return fn.parse(e,t)}xe.options=xe.setOptions=function(e){return fn.setOptions(e),xe.defaults=fn.defaults,Ho(xe.defaults),xe},xe.getDefaults=Sr,xe.defaults=un,xe.use=function(...e){return fn.use(...e),xe.defaults=fn.defaults,Ho(xe.defaults),xe},xe.walkTokens=function(e,t){return fn.walkTokens(e,t)},xe.parseInline=fn.parseInline,xe.Parser=bt,xe.parser=bt.parse,xe.Renderer=Os,xe.TextRenderer=Or,xe.Lexer=mt,xe.lexer=mt.lex,xe.Tokenizer=Ls,xe.Hooks=Yn,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,bt.parse,mt.lex;function sl(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,s=Array(t);n2?s-2:0),i=2;i1?n-1:0),r=1;r1?n-1:0),r=1;r2&&arguments[2]!==void 0?arguments[2]:Zn;if(il&&il(e,null),!Ze(t))return e;let s=t.length;for(;s--;){let r=t[s];if(typeof r=="string"){const i=n(r);i!==r&&(Af(t)||(t[s]=i),r=i)}e[r]=!0}return e}function Df(e){for(let t=0;t/g),jf=ft(/\${[\w\W]*/g),Vf=ft(/^data-[\-\w.\u00B7-\uFFFF]+$/),qf=ft(/^aria-[\-\w]+$/),ml=ft(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Wf=ft(/^(?:\w+script|data):/i),Gf=ft(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Kf=ft(/^html$/i),Yf=ft(/^[a-z][.\w]*(-[.\w]+)+$/i),An={element:1,text:3,progressingInstruction:7,comment:8,document:9},Zf=function(){return typeof window=="undefined"?null:window},Xf=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const r="data-tt-policy-suffix";n&&n.hasAttribute(r)&&(s=n.getAttribute(r));const i="dompurify"+(s?"#"+s:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return null}},bl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function xl(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Zf();const t=V=>xl(V);if(t.version="3.4.3",t.removed=[],!e||!e.document||e.document.nodeType!==An.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const s=n,r=s.currentScript,i=e.DocumentFragment,o=e.HTMLTemplateElement,a=e.Node,l=e.Element,c=e.NodeFilter,u=e.NamedNodeMap,p=u===void 0?e.NamedNodeMap||e.MozNamedAttrMap:u,g=e.HTMLFormElement,w=e.DOMParser,E=e.trustedTypes,m=l.prototype,A=En(m,"cloneNode"),T=En(m,"remove"),W=En(m,"nextSibling"),K=En(m,"childNodes"),O=En(m,"parentNode");if(typeof o=="function"){const V=n.createElement("template");V.content&&V.content.ownerDocument&&(n=V.content.ownerDocument)}let z,P="";const I=n,re=I.implementation,j=I.createNodeIterator,te=I.createDocumentFragment,ue=I.getElementsByTagName,$=s.importNode;let Z=bl();t.isSupported=typeof rl=="function"&&typeof O=="function"&&re&&re.createHTMLDocument!==void 0;const Y=zf,B=Uf,ce=jf,Se=Vf,We=qf,xt=Wf,fe=Gf,N=Yf;let pe=ml,he=null;const ke=X({},[...dl,...Fr,...Br,...Hr,...pl]);let ve=null;const me=X({},[...hl,...zr,...gl,...Ds]);let le=Object.seal(_n(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),yt=null,Ct=null;const ze=Object.seal(_n(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ur=!0,f=!0,h=!1,b=!0,k=!1,v=!0,_=!1,M=!1,C=!1,R=!1,S=!1,H=!1,L=!0,U=!1;const G="user-content-";let ee=!0,de=!1,ne={},Te=null;const Oe=X({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let rt=null;const it=X({},["audio","video","img","source","image","track"]);let Ft=null;const Qn=X({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),$e="http://www.w3.org/1998/Math/MathML",Xe="http://www.w3.org/2000/svg",ot="http://www.w3.org/1999/xhtml";let Bt=ot,jr=!1,Vr=null;const hp=X({},[$e,Xe,ot],Nr);let qr=X({},["mi","mo","mn","ms","mtext"]),Wr=X({},["annotation-xml"]);const gp=X({},["title","style","font","a","script"]);let Jn=null;const mp=["application/xhtml+xml","text/html"],bp="text/html";let Le=null,Rn=null;const xp=n.createElement("form"),Sl=function(d){return d instanceof RegExp||d instanceof Function},Gr=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Rn&&Rn===d)return;(!d||typeof d!="object")&&(d={}),d=et(d),Jn=mp.indexOf(d.PARSER_MEDIA_TYPE)===-1?bp:d.PARSER_MEDIA_TYPE,Le=Jn==="application/xhtml+xml"?Nr:Zn,he=Ee(d,"ALLOWED_TAGS")&&Ze(d.ALLOWED_TAGS)?X({},d.ALLOWED_TAGS,Le):ke,ve=Ee(d,"ALLOWED_ATTR")&&Ze(d.ALLOWED_ATTR)?X({},d.ALLOWED_ATTR,Le):me,Vr=Ee(d,"ALLOWED_NAMESPACES")&&Ze(d.ALLOWED_NAMESPACES)?X({},d.ALLOWED_NAMESPACES,Nr):hp,Ft=Ee(d,"ADD_URI_SAFE_ATTR")&&Ze(d.ADD_URI_SAFE_ATTR)?X(et(Qn),d.ADD_URI_SAFE_ATTR,Le):Qn,rt=Ee(d,"ADD_DATA_URI_TAGS")&&Ze(d.ADD_DATA_URI_TAGS)?X(et(it),d.ADD_DATA_URI_TAGS,Le):it,Te=Ee(d,"FORBID_CONTENTS")&&Ze(d.FORBID_CONTENTS)?X({},d.FORBID_CONTENTS,Le):Oe,yt=Ee(d,"FORBID_TAGS")&&Ze(d.FORBID_TAGS)?X({},d.FORBID_TAGS,Le):et({}),Ct=Ee(d,"FORBID_ATTR")&&Ze(d.FORBID_ATTR)?X({},d.FORBID_ATTR,Le):et({}),ne=Ee(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?et(d.USE_PROFILES):d.USE_PROFILES:!1,Ur=d.ALLOW_ARIA_ATTR!==!1,f=d.ALLOW_DATA_ATTR!==!1,h=d.ALLOW_UNKNOWN_PROTOCOLS||!1,b=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,k=d.SAFE_FOR_TEMPLATES||!1,v=d.SAFE_FOR_XML!==!1,_=d.WHOLE_DOCUMENT||!1,R=d.RETURN_DOM||!1,S=d.RETURN_DOM_FRAGMENT||!1,H=d.RETURN_TRUSTED_TYPE||!1,C=d.FORCE_BODY||!1,L=d.SANITIZE_DOM!==!1,U=d.SANITIZE_NAMED_PROPS||!1,ee=d.KEEP_CONTENT!==!1,de=d.IN_PLACE||!1,pe=Ff(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:ml,Bt=typeof d.NAMESPACE=="string"?d.NAMESPACE:ot,qr=Ee(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?et(d.MATHML_TEXT_INTEGRATION_POINTS):X({},["mi","mo","mn","ms","mtext"]),Wr=Ee(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?et(d.HTML_INTEGRATION_POINTS):X({},["annotation-xml"]);const y=Ee(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?et(d.CUSTOM_ELEMENT_HANDLING):_n(null);if(le=_n(null),Ee(y,"tagNameCheck")&&Sl(y.tagNameCheck)&&(le.tagNameCheck=y.tagNameCheck),Ee(y,"attributeNameCheck")&&Sl(y.attributeNameCheck)&&(le.attributeNameCheck=y.attributeNameCheck),Ee(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(le.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),k&&(f=!1),S&&(R=!0),ne&&(he=X({},pl),ve=_n(null),ne.html===!0&&(X(he,dl),X(ve,hl)),ne.svg===!0&&(X(he,Fr),X(ve,zr),X(ve,Ds)),ne.svgFilters===!0&&(X(he,Br),X(ve,zr),X(ve,Ds)),ne.mathMl===!0&&(X(he,Hr),X(ve,gl),X(ve,Ds))),ze.tagCheck=null,ze.attributeCheck=null,Ee(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?ze.tagCheck=d.ADD_TAGS:Ze(d.ADD_TAGS)&&(he===ke&&(he=et(he)),X(he,d.ADD_TAGS,Le))),Ee(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?ze.attributeCheck=d.ADD_ATTR:Ze(d.ADD_ATTR)&&(ve===me&&(ve=et(ve)),X(ve,d.ADD_ATTR,Le))),Ee(d,"ADD_URI_SAFE_ATTR")&&Ze(d.ADD_URI_SAFE_ATTR)&&X(Ft,d.ADD_URI_SAFE_ATTR,Le),Ee(d,"FORBID_CONTENTS")&&Ze(d.FORBID_CONTENTS)&&(Te===Oe&&(Te=et(Te)),X(Te,d.FORBID_CONTENTS,Le)),Ee(d,"ADD_FORBID_CONTENTS")&&Ze(d.ADD_FORBID_CONTENTS)&&(Te===Oe&&(Te=et(Te)),X(Te,d.ADD_FORBID_CONTENTS,Le)),ee&&(he["#text"]=!0),_&&X(he,["html","head","body"]),he.table&&(X(he,["tbody"]),delete yt.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw $s('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw $s('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');z=d.TRUSTED_TYPES_POLICY,P=z.createHTML("")}else z===void 0&&(z=Xf(E,r)),z!==null&&typeof P=="string"&&(P=z.createHTML(""));Ye&&Ye(d),Rn=d},El=X({},[...Fr,...Br,...Bf]),Al=X({},[...Hr,...Hf]),yp=function(d){let y=O(d);(!y||!y.tagName)&&(y={namespaceURI:Bt,tagName:"template"});const D=Zn(d.tagName),ae=Zn(y.tagName);return Vr[d.namespaceURI]?d.namespaceURI===Xe?y.namespaceURI===ot?D==="svg":y.namespaceURI===$e?D==="svg"&&(ae==="annotation-xml"||qr[ae]):!!El[D]:d.namespaceURI===$e?y.namespaceURI===ot?D==="math":y.namespaceURI===Xe?D==="math"&&Wr[ae]:!!Al[D]:d.namespaceURI===ot?y.namespaceURI===Xe&&!Wr[ae]||y.namespaceURI===$e&&!qr[ae]?!1:!Al[D]&&(gp[D]||!El[D]):!!(Jn==="application/xhtml+xml"&&Vr[d.namespaceURI]):!1},wt=function(d){Tn(t.removed,{element:d});try{O(d).removeChild(d)}catch{T(d)}},dn=function(d,y){try{Tn(t.removed,{attribute:y.getAttributeNode(d),from:y})}catch{Tn(t.removed,{attribute:null,from:y})}if(y.removeAttribute(d),d==="is")if(R||S)try{wt(y)}catch{}else try{y.setAttribute(d,"")}catch{}},Rl=function(d){let y=null,D=null;if(C)d=""+d;else{const Ie=al(d,/^[\r\n\t ]+/);D=Ie&&Ie[0]}Jn==="application/xhtml+xml"&&Bt===ot&&(d=''+d+"");const ae=z?z.createHTML(d):d;if(Bt===ot)try{y=new w().parseFromString(ae,Jn)}catch{}if(!y||!y.documentElement){y=re.createDocument(Bt,"template",null);try{y.documentElement.innerHTML=jr?P:ae}catch{}}const De=y.body||y.documentElement;return d&&D&&De.insertBefore(n.createTextNode(D),De.childNodes[0]||null),Bt===ot?ue.call(y,_?"html":"body")[0]:_?y.documentElement:De},Cl=function(d){return j.call(d.ownerDocument||d,d,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Kr=function(d){return d instanceof g&&(typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||!(d.attributes instanceof p)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function")},Yr=function(d){return typeof a=="function"&&d instanceof a};function Ht(V,d,y){kn(V,D=>{D.call(t,d,y,Rn)})}const Pl=function(d){let y=null;if(Ht(Z.beforeSanitizeElements,d,null),Kr(d))return wt(d),!0;const D=Le(d.nodeName);if(Ht(Z.uponSanitizeElement,d,{tagName:D,allowedTags:he}),v&&d.hasChildNodes()&&!Yr(d.firstElementChild)&&He(/<[/\w!]/g,d.innerHTML)&&He(/<[/\w!]/g,d.textContent)||v&&d.namespaceURI===ot&&D==="style"&&Yr(d.firstElementChild)||d.nodeType===An.progressingInstruction||v&&d.nodeType===An.comment&&He(/<[/\w]/g,d.data))return wt(d),!0;if(yt[D]||!(ze.tagCheck instanceof Function&&ze.tagCheck(D))&&!he[D]){if(!yt[D]&&Ml(D)&&(le.tagNameCheck instanceof RegExp&&He(le.tagNameCheck,D)||le.tagNameCheck instanceof Function&&le.tagNameCheck(D)))return!1;if(ee&&!Te[D]){const ae=O(d)||d.parentNode,De=K(d)||d.childNodes;if(De&&ae){const Ie=De.length;for(let tt=Ie-1;tt>=0;--tt){const dt=A(De[tt],!0);ae.insertBefore(dt,W(d))}}}return wt(d),!0}return d instanceof l&&!yp(d)||(D==="noscript"||D==="noembed"||D==="noframes")&&He(/<\/no(script|embed|frames)/i,d.innerHTML)?(wt(d),!0):(k&&d.nodeType===An.text&&(y=d.textContent,kn([Y,B,ce],ae=>{y=Sn(y,ae," ")}),d.textContent!==y&&(Tn(t.removed,{element:d.cloneNode()}),d.textContent=y)),Ht(Z.afterSanitizeElements,d,null),!1)},Il=function(d,y,D){if(Ct[y]||L&&(y==="id"||y==="name")&&(D in n||D in xp))return!1;const ae=ve[y]||ze.attributeCheck instanceof Function&&ze.attributeCheck(y,d);if(!(f&&!Ct[y]&&He(Se,y))){if(!(Ur&&He(We,y))){if(!ae||Ct[y]){if(!(Ml(d)&&(le.tagNameCheck instanceof RegExp&&He(le.tagNameCheck,d)||le.tagNameCheck instanceof Function&&le.tagNameCheck(d))&&(le.attributeNameCheck instanceof RegExp&&He(le.attributeNameCheck,y)||le.attributeNameCheck instanceof Function&&le.attributeNameCheck(y,d))||y==="is"&&le.allowCustomizedBuiltInElements&&(le.tagNameCheck instanceof RegExp&&He(le.tagNameCheck,D)||le.tagNameCheck instanceof Function&&le.tagNameCheck(D))))return!1}else if(!Ft[y]){if(!He(pe,Sn(D,fe,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&d!=="script"&&ul(D,"data:")===0&&rt[d])){if(!(h&&!He(xt,Sn(D,fe,"")))){if(D)return!1}}}}}}return!0},wp=X({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Ml=function(d){return!wp[Zn(d)]&&He(N,d)},Ll=function(d){Ht(Z.beforeSanitizeAttributes,d,null);const y=d.attributes;if(!y||Kr(d))return;const D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ve,forceKeepAttr:void 0};let ae=y.length;for(;ae--;){const De=y[ae],Ie=De.name,tt=De.namespaceURI,dt=De.value,vt=Le(Ie),Xr=dt;let Ne=Ie==="value"?Xr:Mf(Xr);if(D.attrName=vt,D.attrValue=Ne,D.keepAttr=!0,D.forceKeepAttr=void 0,Ht(Z.uponSanitizeAttribute,d,D),Ne=D.attrValue,U&&(vt==="id"||vt==="name")&&ul(Ne,G)!==0&&(dn(Ie,d),Ne=G+Ne),v&&He(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ne)){dn(Ie,d);continue}if(vt==="attributename"&&al(Ne,"href")){dn(Ie,d);continue}if(D.forceKeepAttr)continue;if(!D.keepAttr){dn(Ie,d);continue}if(!b&&He(/\/>/i,Ne)){dn(Ie,d);continue}k&&kn([Y,B,ce],$l=>{Ne=Sn(Ne,$l," ")});const Ol=Le(d.nodeName);if(!Il(Ol,vt,Ne)){dn(Ie,d);continue}if(z&&typeof E=="object"&&typeof E.getAttributeType=="function"&&!tt)switch(E.getAttributeType(Ol,vt)){case"TrustedHTML":{Ne=z.createHTML(Ne);break}case"TrustedScriptURL":{Ne=z.createScriptURL(Ne);break}}if(Ne!==Xr)try{tt?d.setAttributeNS(tt,Ie,Ne):d.setAttribute(Ie,Ne),Kr(d)?wt(d):ll(t.removed)}catch{dn(Ie,d)}}Ht(Z.afterSanitizeAttributes,d,null)},Zr=function(d){let y=null;const D=Cl(d);for(Ht(Z.beforeSanitizeShadowDOM,d,null);y=D.nextNode();)Ht(Z.uponSanitizeShadowNode,y,null),Pl(y),Ll(y),y.content instanceof i&&Zr(y.content);Ht(Z.afterSanitizeShadowDOM,d,null)},Fs=function(d){if(d.nodeType===An.element&&d.shadowRoot instanceof i){const ae=d.shadowRoot;Fs(ae),Zr(ae)}const y=d.childNodes;if(!y)return;const D=[];kn(y,ae=>{Tn(D,ae)});for(const ae of D)Fs(ae)};return t.sanitize=function(V){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,D=null,ae=null,De=null;if(jr=!V,jr&&(V=""),typeof V!="string"&&!Yr(V)&&(V=Nf(V),typeof V!="string"))throw $s("dirty is not a string, aborting");if(!t.isSupported)return V;if(M||Gr(d),t.removed=[],typeof V=="string"&&(de=!1),de){const dt=V.nodeName;if(typeof dt=="string"){const vt=Le(dt);if(!he[vt]||yt[vt])throw $s("root node is forbidden and cannot be sanitized in-place")}Fs(V)}else if(V instanceof a)y=Rl(""),D=y.ownerDocument.importNode(V,!0),D.nodeType===An.element&&D.nodeName==="BODY"||D.nodeName==="HTML"?y=D:y.appendChild(D),Fs(D);else{if(!R&&!k&&!_&&V.indexOf("<")===-1)return z&&H?z.createHTML(V):V;if(y=Rl(V),!y)return R?null:H?P:""}y&&C&&wt(y.firstChild);const Ie=Cl(de?V:y);for(;ae=Ie.nextNode();)Pl(ae),Ll(ae),ae.content instanceof i&&Zr(ae.content);if(de)return V;if(R){if(k){y.normalize();let dt=y.innerHTML;kn([Y,B,ce],vt=>{dt=Sn(dt,vt," ")}),y.innerHTML=dt}if(S)for(De=te.call(y.ownerDocument);y.firstChild;)De.appendChild(y.firstChild);else De=y;return(ve.shadowroot||ve.shadowrootmode)&&(De=$.call(s,De,!0)),De}let tt=_?y.outerHTML:y.innerHTML;return _&&he["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&He(Kf,y.ownerDocument.doctype.name)&&(tt=" -`+tt),k&&kn([Y,B,ce],dt=>{tt=Sn(tt,dt," ")}),z&&H?z.createHTML(tt):tt},t.setConfig=function(){let V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Gr(V),M=!0},t.clearConfig=function(){Rn=null,M=!1},t.isValidAttribute=function(V,d,y){Rn||Gr({});const D=Le(V),ae=Le(d);return Il(D,ae,y)},t.addHook=function(V,d){typeof d=="function"&&Tn(Z[V],d)},t.removeHook=function(V,d){if(d!==void 0){const y=Pf(Z[V],d);return y===-1?void 0:If(Z[V],y,1)[0]}return ll(Z[V])},t.removeHooks=function(V){Z[V]=[]},t.removeAllHooks=function(){Z=bl()},t}var Qf=xl();const Jf={key:1,class:"flex min-w-0 max-w-[calc(100%-2.5rem)] flex-1 flex-col max-[600px]:max-w-[calc(100%-2.25rem)]"},ed={key:0,class:"flex w-fit flex-col items-start gap-1"},td=["aria-label"],nd={class:"inline-flex items-center gap-1.5"},sd={class:"text-[8px] font-semibold tracking-[0.12em] uppercase text-[#3a67c9]"},rd={key:1,class:"flex w-fit max-w-full flex-col items-start gap-2"},id={class:"chat-card relative w-fit max-w-full whitespace-pre-line rounded-[10px_10px_10px_3px] px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900"},od=["innerHTML"],ld={key:0,class:"pointer-events-none absolute inset-x-0 bottom-0 h-14 rounded-b-[10px] bg-linear-to-t from-white via-white/92 to-white/0","aria-hidden":"true"},ad={key:0,class:"flex flex-wrap items-center gap-2"},ud=["title","aria-label"],cd={key:1,class:"flex flex-wrap items-center"},fd=["title","aria-label"],dd={viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},pd=["innerHTML"],yl={__name:"ChatMessage",props:{message:{type:Object,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,default:()=>({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd"})}},setup(e){const t=e,n=J(!1),s=J(null),r=J(!1),i=J(!1),o=Re(()=>typeof window!="undefined"&&"speechSynthesis"in window&&"SpeechSynthesisUtterance"in window);function a(P){typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("changai-tts-provider",{detail:{provider:P}}))}function l(P){if(typeof P!="string")return"";const I=P.replace(/[\u{1F000}-\u{1FFFF}]/gu,"").replace(/[\u{2600}-\u{26FF}]/gu,"").replace(/[\u{2700}-\u{27BF}]/gu,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/#{1,6}\s+/g,"").replace(/[-*+]\s+/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\s+/g," ");return I.includes("<")?(new DOMParser().parseFromString(P,"text/html").body.textContent||"").replace(/\s+/g," ").trim():I.trim()}function c(){o.value&&window.speechSynthesis.cancel(),s.value&&(s.value.pause(),s.value.src="",s.value=null),n.value=!1}function u(){var P,I,re;if(i.value=!i.value,i.value)c();else{const j=A.value;if(!t.autoReadEnabled||!((P=t.ttsConfig)!=null&&P.enableVoiceChat)||!j||E())return;if((I=t.ttsConfig)!=null&&I.pollyAvailable&&((re=t.ttsConfig)!=null&&re.usePolly)){g(j).catch(te=>{p(j)});return}p(j)}}function p(P){if(!o.value||!P)return;window.dispatchEvent(new CustomEvent("changai-tts-stop")),window.speechSynthesis.cancel();const I=new SpeechSynthesisUtterance(P);I.rate=1,I.pitch=1,I.onend=()=>{n.value=!1},I.onerror=()=>{n.value=!1},n.value=!0,a("browser"),window.speechSynthesis.speak(I)}async function g(P){var ue;const I=await Lc(P,((ue=t.ttsConfig)==null?void 0:ue.voiceId)||"Zayd");if(!(I!=null&&I.ok)||!(I!=null&&I.audio_base64))throw new Error((I==null?void 0:I.error)||"Polly synthesis failed");window.dispatchEvent(new CustomEvent("changai-tts-stop")),c();const re=(I==null?void 0:I.mime_type)||"audio/mpeg",j=new Audio(`data:${re};base64,${I.audio_base64}`);s.value=j,n.value=!0;let te=!1;j.onplay=()=>{te=!0,a("polly")},j.onended=()=>{s.value===j&&(s.value=null),n.value=!1},j.onerror=()=>{s.value===j&&(s.value=null),n.value=!1},await j.play(),te||a("polly")}function w(){c()}function E(){var P;return!!((P=t.message)!=null&&P.isStatus)}function m(P){const I=P.target.closest("a");!I||!I.href||(P.preventDefault(),P.stopPropagation(),window.open(I.href,"_blank","noopener,noreferrer"))}const A=Re(()=>{var P;return l(((P=t.message)==null?void 0:P.text)||"")}),T=Re(()=>{var P;return((P=t.message)==null?void 0:P.role)!=="user"&&E()}),W=Re(()=>{var P;return(P=t.message)!=null&&P.isStatus?t.message.statusType==="support"?"Sending to support":A.value||"Thinking":""}),K=Re(()=>{var re;if(((re=t.message)==null?void 0:re.role)==="user"||T.value)return!1;const P=A.value,I=P.split(/\n+/).filter(Boolean).length;return P.length>520||I>8}),O=Re(()=>{var P,I;return((P=t.message)==null?void 0:P.role)!=="user"&&!T.value&&((I=t.ttsConfig)==null?void 0:I.enableVoiceChat)}),z=Re(()=>{var I;const P=((I=t.message)==null?void 0:I.text)||"";return Qf.sanitize(xe.parse(P))});return rn(()=>t.message.text,async(P,I)=>{var te,ue,$;if(!t.autoReadEnabled||t.message.role==="user"||i.value)return;if(!((te=t.ttsConfig)!=null&&te.enableVoiceChat)){a("off");return}const re=l(P);if(!re||E())return;const j=l(I||"");if(re!==j){if((ue=t.ttsConfig)!=null&&ue.pollyAvailable&&(($=t.ttsConfig)!=null&&$.usePolly))try{await g(re);return}catch{}p(re)}}),rn(()=>t.message.text,()=>{r.value=!1,i.value=!1}),Hn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-stop",w)}),xs(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-stop",w),n.value&&c()}),(P,I)=>(F(),q("div",{class:ye(["motion-safe:animate-fade-rise flex w-full gap-1.5",e.message.role==="user"?"flex-col items-end":"items-start"])},[e.message.role!=="user"?(F(),St(Bo,{key:0})):Ve("",!0),e.message.role!=="user"?(F(),q("div",Jf,[T.value?(F(),q("div",ed,[x("div",{class:"chat-card inline-flex w-fit rounded-[10px_10px_10px_3px] px-3 py-2",role:"status","aria-live":"polite","aria-label":W.value},[x("div",nd,[I[1]||(I[1]=x("span",{class:"relative inline-flex h-4 w-4 shrink-0 items-center justify-center"},[x("span",{class:"absolute inset-0 rounded-full border border-transparent border-t-[#4b89ff] border-r-[#4b89ff]/70 animate-gemini-arc"}),x("svg",{viewBox:"0 0 24 24",class:"relative h-3 w-3 text-[#4b89ff] animate-gemini-spark","aria-hidden":"true"},[x("path",{fill:"currentColor",d:"M12 2.8c.52 3.22 1.6 5.66 3.22 7.28 1.62 1.62 4.06 2.7 7.28 3.22-3.22.52-5.66 1.6-7.28 3.22-1.62 1.62-2.7 4.06-3.22 7.28-.52-3.22-1.6-5.66-3.22-7.28-1.62-1.62-4.06-2.7-7.28-3.22 3.22-.52 5.66-1.6 7.28-3.22 1.62-1.62 2.7-4.06 3.22-7.28Z"})])],-1)),x("span",sd,Qe(W.value),1)])],8,td)])):(F(),q("div",rd,[x("div",id,[x("div",{class:ye(["overflow-x-auto",K.value&&!r.value?"max-h-48 overflow-y-hidden":""]),innerHTML:z.value,onClick:m},null,10,od),K.value&&!r.value?(F(),q("div",ld)):Ve("",!0)]),K.value?(F(),q("div",ad,[x("button",{type:"button",class:"inline-flex items-center rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-600 transition-colors duration-200 hover:border-brand-200 hover:text-brand-600",title:r.value?"Collapse response":"Expand response","aria-label":r.value?"Collapse response":"Expand response",onClick:I[0]||(I[0]=re=>r.value=!r.value)},Qe(r.value?"Collapse":"Expand"),9,ud)])):Ve("",!0),O.value?(F(),q("div",cd,[x("button",{type:"button",class:ye(["inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors duration-200",i.value?"border-red-200 bg-red-50 text-red-600 hover:border-red-300 hover:bg-red-100":"border-green-200 bg-green-50 text-green-600 hover:border-green-300 hover:bg-green-100"]),title:i.value?"Unmute voice playback":"Mute voice playback","aria-label":i.value?"Unmute voice playback":"Mute voice playback",onClick:u},[(F(),q("svg",dd,[I[6]||(I[6]=x("path",{d:"M11 5L6 9H3v6h3l5 4V5Z"},null,-1)),i.value?(F(),q(Be,{key:0},[I[2]||(I[2]=x("path",{d:"M15 9l4 6"},null,-1)),I[3]||(I[3]=x("path",{d:"M19 9l-4 6"},null,-1))],64)):(F(),q(Be,{key:1},[I[4]||(I[4]=x("path",{d:"M15 10a3 3 0 0 1 0 4"},null,-1)),I[5]||(I[5]=x("path",{d:"M17.5 7.5a6 6 0 0 1 0 9"},null,-1))],64))]))],10,fd)])):Ve("",!0)]))])):(F(),q("div",{key:2,class:"w-fit max-w-[85%] whitespace-pre-line rounded-[13px_13px_3px_13px] bg-linear-to-br from-brand-500 to-brand-600 px-4 py-3 text-[11px] leading-relaxed wrap-anywhere text-white shadow-[0_14px_30px_-18px_rgba(109,79,194,0.85)] max-[600px]:max-w-[88%]",innerHTML:z.value},null,8,pd))],2))}},hd={class:"flex flex-col gap-4 sm:gap-5"},gd={class:"motion-safe:animate-fade-rise flex w-full items-start gap-1.5"},md={__name:"ChatTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(F(),q("div",hd,[x("div",gd,[Me(Bo),n[0]||(n[0]=x("p",{class:"w-fit max-w-[calc(100%-2.5rem)] whitespace-pre-line rounded-[10px_10px_10px_3px] bg-brand-50 px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900 max-[600px]:max-w-[calc(100%-2.25rem)]"},[Ts(" Hello there 👋 I am ChangAI from "),x("a",{target:"_blank",href:"https://erpgulf.com",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ERPGulf.com"),Ts(", your ERP assistant."),x("br"),x("a",{target:"_blank",href:"https://app.erpgulf.com/en/articles/chang-ai-quick-start-guide",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ChangAI Quick Start Guide - Click here.")],-1))]),(F(!0),q(Be,null,ys(e.messages,(s,r)=>(F(),St(yl,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}};function wl(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function vl(e){var t,n;return(e==null?void 0:e.message)||((t=e==null?void 0:e.responseJSON)==null?void 0:t.exception)||((n=e==null?void 0:e.responseJSON)==null?void 0:n.message)||(e==null?void 0:e.responseText)||String(e)}function bd(e){return typeof e=="string"?e:e&&typeof e=="object"?e.error?`⚠️ ${e.error}`:e.answer||e.text||"":""}const xd={key:0,class:"rounded-lg bg-brand-50 px-4 py-3 text-xs text-black"},yd={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},wd={key:1,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-brand-50 p-2 text-[11px]"},vd={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},_d={__name:"DebugTab",props:{logs:{type:Array,required:!0},currentDebug:{type:Object,default:null}},setup(e){const t=new Set(["gemini_json_content","private_key","private_key_id","client_secret","client_id","aws_access_key","aws_secret_key","api_key","token","access_token","refresh_token","password","secret","authorization","embed_version_id","llm_version_id","entity_retriever","retriever","deploy_url","support_api_url","get_ticket_details_url"]);function n(r,i=0){if(i>10||r===null||r===void 0||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(Array.isArray(r))return r.map(o=>n(o,i+1));if(typeof r=="object"){const o={};for(const[a,l]of Object.entries(r))t.has(a.toLowerCase())||(o[a]=n(l,i+1));return o}return r}function s(r){return wl(n(r))}return(r,i)=>(F(),q("div",null,[e.logs.length===0?(F(),q("p",xd,"No debug data yet.")):Ve("",!0),(F(!0),q(Be,null,ys(e.logs,(o,a)=>(F(),q("div",{key:a,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-gray-100 p-2 text-[11px]"},[x("pre",yd,Qe(s(o)),1)]))),128)),e.currentDebug?(F(),q("div",wd,[x("pre",vd,Qe(s(e.currentDebug)),1)])):Ve("",!0)]))}},kd={class:"flex flex-col gap-4 sm:gap-5"},Td={key:0,class:"chat-card motion-safe:animate-fade-rise rounded-lg px-4 py-3 text-xs text-slate-900"},Sd={__name:"SupportTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(F(),q("div",kd,[e.messages.length===0?(F(),q("p",Td,"Send a message to Support.")):Ve("",!0),(F(!0),q(Be,null,ys(e.messages,(s,r)=>(F(),St(yl,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}},Ed={class:"flex flex-col gap-4"},Ad={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Rd={class:"flex items-start justify-between gap-4"},Cd=["aria-pressed","title"],Pd={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Id={class:"flex items-start justify-between gap-4"},Md={class:"mt-2 text-[11px] text-slate-500"},Ld={key:0,class:"mt-1 text-[11px] text-slate-500"},Od={key:1,class:"mt-1 text-[11px] text-slate-500"},$d=["aria-pressed","disabled"],Dd={key:0,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},Nd={key:1,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},Fd={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Bd={class:"flex items-start justify-between gap-4"},Hd=["aria-pressed","title"],zd={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Ud={class:"flex items-start justify-between gap-4"},jd=["aria-pressed","title"],Vd={__name:"SettingsTab",props:{autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},settings:{type:Object,default:null},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1}},emits:["toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e){const t=e,n=Re(()=>{var s,r;return(s=t.ttsConfig)!=null&&s.enableVoiceChat?(r=t.ttsConfig)!=null&&r.pollyAvailable?"Available":"Unavailable":"Voice disabled on server"});return(s,r)=>{var i,o,a,l,c,u,p,g,w,E,m,A,T,W,K;return F(),q("div",Ed,[r[10]||(r[10]=x("div",{class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4 text-slate-900"},[x("h3",{class:"text-sm font-semibold tracking-[0.01em]"},"Speech Settings"),x("p",{class:"mt-1 text-xs leading-relaxed text-slate-600"},"These controls apply only inside this chatbot box for the current browser session.")],-1)),x("div",Ad,[x("div",Rd,[r[4]||(r[4]=x("div",null,[x("p",{class:"text-sm font-semibold text-slate-900"},"Auto Read Replies"),x("p",{class:"mt-1 text-xs text-slate-600"},"Automatically read bot replies aloud.")],-1)),x("button",{class:ye(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.autoReadEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.autoReadEnabled?"true":"false",title:e.autoReadEnabled?"Disable auto read":"Enable auto read",onClick:r[0]||(r[0]=O=>s.$emit("toggleAutoRead"))},[x("span",{class:ye(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.autoReadEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,Cd)]),x("p",{class:ye(["mt-3 text-[11px] font-medium",e.autoReadEnabled?"text-emerald-700":"text-slate-500"])},Qe(e.autoReadEnabled?"Auto read is active.":"Auto read is currently off."),3)]),x("div",Pd,[x("div",Id,[x("div",null,[r[5]||(r[5]=x("p",{class:"text-sm font-semibold text-slate-900"},"Use Amazon Polly",-1)),r[6]||(r[6]=x("p",{class:"mt-1 text-xs text-slate-600"},"Use Polly when available; otherwise browser speech is used automatically.",-1)),x("p",Md,"Availability: "+Qe(n.value),1),(i=e.settings)!=null&&i.aws_region?(F(),q("p",Ld,"Region: "+Qe(e.settings.aws_region),1)):Ve("",!0),(o=e.ttsConfig)!=null&&o.voiceId?(F(),q("p",Od,"Voice: "+Qe(e.ttsConfig.voiceId),1)):Ve("",!0)]),x("button",{class:ye(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-55",(a=e.ttsConfig)!=null&&a.usePolly&&((l=e.ttsConfig)!=null&&l.enableVoiceChat)&&((c=e.ttsConfig)!=null&&c.pollyAvailable)?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":(u=e.ttsConfig)!=null&&u.usePolly&&((p=e.ttsConfig)!=null&&p.enableVoiceChat)&&((g=e.ttsConfig)!=null&&g.pollyAvailable)?"true":"false",disabled:!((w=e.ttsConfig)!=null&&w.pollyAvailable)||!((E=e.ttsConfig)!=null&&E.enableVoiceChat),onClick:r[1]||(r[1]=O=>s.$emit("togglePollyPreference"))},[x("span",{class:ye(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",(m=e.ttsConfig)!=null&&m.usePolly&&((A=e.ttsConfig)!=null&&A.enableVoiceChat)&&((T=e.ttsConfig)!=null&&T.pollyAvailable)?"left-[1.45rem]":"left-0.5"])},null,2)],10,$d)]),(W=e.ttsConfig)!=null&&W.enableVoiceChat?(K=e.ttsConfig)!=null&&K.pollyAvailable?Ve("",!0):(F(),q("p",Nd,"Polly is not available for this site. Browser speech will be used.")):(F(),q("p",Dd,"Voice chat is disabled in ChangAI Settings."))]),x("div",Fd,[x("div",Bd,[x("div",null,[r[7]||(r[7]=x("p",{class:"text-sm font-semibold text-slate-900"},"Enable Debug Tab",-1)),r[8]||(r[8]=x("p",{class:"mt-1 text-xs text-slate-600"}," Show or hide the Debug tab inside this chatbot. ",-1)),x("p",{class:ye(["mt-2 text-[11px] font-medium",e.debugEnabled?"text-emerald-700":"text-slate-500"])},Qe(e.debugEnabled?"Debug tab is active.":"Debug tab is currently off."),3)]),x("button",{type:"button",class:ye(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.debugEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.debugEnabled?"true":"false",title:e.debugEnabled?"Disable debug tab":"Enable debug tab",onClick:r[2]||(r[2]=O=>s.$emit("toggleDebug"))},[x("span",{class:ye(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.debugEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,Hd)])]),x("div",zd,[x("div",Ud,[r[9]||(r[9]=x("div",null,[x("p",{class:"text-sm font-semibold text-slate-900"},"Send non-ERP questions directly to AI"),x("p",{class:"mt-1 text-xs text-slate-600"},"Questions unrelated to your ERP will skip the system and go straight to AI")],-1)),x("button",{class:ye(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.sendNonERPtoaiEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.sendNonERPtoaiEnabled?"true":"false",title:e.sendNonERPtoaiEnabled?"Non-ERP questions are being sent directly to AI":"Enable direct AI reply for non-ERP questions",onClick:r[3]||(r[3]=O=>s.$emit("toggleSendNonERP"))},[x("span",{class:ye(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.sendNonERPtoaiEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,jd)]),x("p",{class:ye(["mt-3 text-[11px] font-medium",e.sendNonERPtoaiEnabled?"text-emerald-700":"text-slate-500"])},Qe(e.sendNonERPtoaiEnabled?"Non-ERP questions are now routed directly to AI":"Direct AI routing is currently off"),3)])])}}},qd={key:0,class:"pointer-events-none absolute -top-14 left-0 right-0 z-20 flex justify-center px-2",role:"status","aria-live":"polite"},Wd={__name:"StatusToast",props:{visible:{type:Boolean,required:!0},message:{type:String,default:""},type:{type:String,default:"info"},dismissible:{type:Boolean,default:!0}},emits:["close"],setup(e){const t=e,n=Re(()=>t.type==="error"?"bg-red-50 text-red-700 ring-red-200":(t.type==="listening","bg-blue-50 text-blue-700 ring-blue-200")),s=Re(()=>t.type==="error"?"bg-red-500":t.type==="listening"?"bg-blue-500 animate-pulse":"bg-blue-500");return(r,i)=>(F(),St(Pu,{"enter-active-class":"transition duration-200 ease-out","enter-from-class":"translate-y-1 opacity-0","enter-to-class":"translate-y-0 opacity-100","leave-active-class":"transition duration-150 ease-in","leave-from-class":"translate-y-0 opacity-100","leave-to-class":"translate-y-1 opacity-0"},{default:Ni(()=>[e.visible?(F(),q("div",qd,[x("div",{class:ye(["pointer-events-auto flex max-w-[92%] items-start gap-2 rounded-lg px-3 py-2 text-xs shadow-lg ring-1",n.value])},[x("span",{class:ye(["mt-0.5 h-2 w-2 shrink-0 rounded-full",s.value])},null,2),x("span",null,Qe(e.message),1),e.dismissible?(F(),q("button",{key:0,type:"button",class:"ml-1 appearance-none border-0 text-current/80 transition hover:text-current focus:outline-none","aria-label":"Dismiss notification",onClick:i[0]||(i[0]=o=>r.$emit("close"))}," × ")):Ve("",!0)],2)])):Ve("",!0)]),_:1}))}},Gd={class:"relative w-full"},Kd=["placeholder","disabled"],Yd=["title","aria-label","disabled"],Zd={key:0,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},Xd={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},Qd={key:2,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true",class:"animate-spin"},Jd=["title","aria-label","disabled"],ep={key:0,viewBox:"0 0 24 24",width:"18",height:"18",fill:"none","aria-hidden":"true",class:"text-rose-600 motion-safe:animate-stop-button-pulse"},tp={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},np={__name:"ChatForm",props:{placeholder:{type:String,default:"Message..."},disabled:{type:Boolean,default:!1},isAwaitingResponse:{type:Boolean,default:!1}},emits:["submit","cancel"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=J(""),o=J(null),a=J(!1),l=J(!1),c=J(!1),u=J(!1),p=J(!1),g=J(!1),w=J(!1),E=J(""),m=J("info"),A=J("Voice input is unavailable in this browser/context.");let T=null,W=null,K=null;const O=J(""),z=J(!1),P=Re(()=>c.value?"Requesting microphone permission...":u.value?"Starting voice input...":p.value?"Stopping voice input...":l.value?a.value?"Stop voice input":"Start voice input":"Voice input is unavailable in this browser/context"),I=Re(()=>s.isAwaitingResponse?"Stop response":"Send"),re=Re(()=>s.isAwaitingResponse?!1:s.disabled||!i.value.trim()),j=Re(()=>s.isAwaitingResponse?"bg-white border border-rose-100 shadow-[0_8px_20px_-12px_rgba(159,18,57,0.35)] hover:bg-rose-50":"bg-linear-to-br from-brand-500 to-brand-600 text-white shadow-[0_10px_24px_-16px_rgba(109,79,194,0.85)] hover:from-brand-600 hover:to-violet-700");function te(){return typeof window=="undefined"?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}function ue(){var he;const fe=te(),N=typeof window!="undefined"?window.isSecureContext:!1,pe=typeof navigator!="undefined"&&!!((he=navigator.mediaDevices)!=null&&he.getUserMedia);l.value=!!(fe&&N&&pe),N?(!pe||!fe)&&(A.value="Voice input is not supported in this browser."):A.value="Voice input requires HTTPS (or localhost).",fe&&l.value&&(T=new fe,T.continuous=!0,T.interimResults=!0,T.lang=typeof navigator!="undefined"&&navigator.language||"en-US",T.onstart=()=>{a.value=!0,u.value=!1,p.value=!1,$(),Se("Listening... Tap mic to stop","listening",{persistent:!0,key:"listening"})},T.onend=()=>{a.value=!1,u.value=!1,p.value=!1,$(),O.value==="listening"&&We(),z.value&&(z.value=!1,xt())},T.onerror=ke=>{if(a.value=!1,u.value=!1,p.value=!1,$(),z.value=!1,(ke==null?void 0:ke.error)==="not-allowed"||(ke==null?void 0:ke.error)==="service-not-allowed"){Se("Microphone permission denied. Please allow microphone access in browser settings.","error");return}if((ke==null?void 0:ke.error)==="audio-capture"){Se("No microphone detected. Please connect a microphone and try again.","error");return}if((ke==null?void 0:ke.error)==="no-speech"){Se("No speech detected. Try speaking a bit louder.","info");return}Se("Voice input failed. Please try again.","error")},T.onresult=ke=>{let ve="";for(let me=ke.resultIndex;me{if(T&&!(!a.value&&!p.value))try{T.abort()}catch{p.value=!1,z.value=!1}},1200)}}function Y(){if(!l.value||!T){Se(A.value,"error");return}if(a.value||u.value||p.value){Z({submitAfterStop:a.value});return}ce()}async function B(){var fe;if(g.value)return!0;if(!((fe=navigator.mediaDevices)!=null&&fe.getUserMedia))return Se("Microphone API is unavailable in this browser.","error"),!1;c.value=!0,Se("Requesting microphone permission...","info",{persistent:!0,key:"requesting"});try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(pe=>pe.stop()),g.value=!0,!0}catch(N){return(N==null?void 0:N.name)==="NotAllowedError"||(N==null?void 0:N.name)==="SecurityError"?Se("Microphone permission denied. Please allow it and try again.","error"):(N==null?void 0:N.name)==="NotFoundError"?Se("No microphone found on this device.","error"):Se("Unable to access microphone. Please check browser permissions.","error"),!1}finally{c.value=!1,O.value==="requesting"&&We()}}async function ce(){var N;if(!(!T||a.value||u.value||p.value||!await B()||!T)){z.value=!1,(N=o.value)==null||N.focus(),u.value=!0;try{T.start()}catch(pe){u.value=!1,p.value=!1,(pe==null?void 0:pe.name)!=="InvalidStateError"&&Se("Unable to start voice input. Please try again.","error")}}}function Se(fe,N="info",pe={}){const{duration:he=4200,persistent:ke=!1,key:ve=""}=pe;E.value=fe,m.value=N,O.value=ve,w.value=!0,W&&clearTimeout(W),ke||(W=setTimeout(()=>{w.value=!1,O.value=""},he))}function We(){w.value=!1,O.value="",W&&(clearTimeout(W),W=null)}function xt(){if(s.isAwaitingResponse){r("cancel");return}const fe=i.value.trim();fe&&((a.value||u.value||p.value)&&T&&Z({submitAfterStop:!1}),r("submit",fe),i.value="")}return t({focus:()=>{var fe;return(fe=o.value)==null?void 0:fe.focus()}}),Hn(()=>{ue()}),xs(()=>{if(T&&(a.value||u.value||p.value)){z.value=!1,$();try{T.abort()}catch{}}$(),We()}),(fe,N)=>(F(),q("div",Gd,[x("form",{class:"group flex min-h-11 items-center gap-2 rounded-full border border-slate-200/90 bg-white/95 px-3 shadow-[0_12px_26px_-20px_rgba(15,23,42,0.7)] transition-all duration-250 focus-within:-translate-y-0.5 focus-within:border-brand-200 focus-within:shadow-[0_18px_30px_-20px_rgba(13,110,253,0.5)] focus-within:ring-2 focus-within:ring-brand-500/25",style:{"border-radius":"9999px"},autocomplete:"off",onSubmit:ct(xt,["prevent"]),onClick:N[5]||(N[5]=ct(()=>{},["stop"])),onMousedown:N[6]||(N[6]=ct(()=>{},["stop"])),onKeydown:N[7]||(N[7]=ct(()=>{},["stop"])),onKeyup:N[8]||(N[8]=ct(()=>{},["stop"]))},[Pa(x("input",{ref_key:"inputRef",ref:o,type:"text","onUpdate:modelValue":N[0]||(N[0]=pe=>i.value=pe),class:"h-11 w-full border-none bg-transparent text-sm font-medium text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:e.disabled?"Waiting for response...":e.placeholder,disabled:e.disabled,required:"",onKeydown:N[1]||(N[1]=ct(()=>{},["stop"])),onKeyup:N[2]||(N[2]=ct(()=>{},["stop"])),onKeypress:N[3]||(N[3]=ct(()=>{},["stop"])),onInput:N[4]||(N[4]=ct(()=>{},["stop"]))},null,40,Kd),[[Xu,i.value]]),x("button",{type:"button",class:ye(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border border-transparent text-slate-600 transition-all duration-200 hover:-translate-y-0.5 hover:border-slate-200 hover:bg-slate-100 hover:text-slate-900 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",a.value?"border-red-200 bg-red-100 text-red-600 shadow-[0_10px_20px_-18px_rgba(220,38,38,0.9)] hover:bg-red-100 hover:text-red-600":""]),style:{"border-radius":"9999px"},title:P.value,"aria-label":P.value,disabled:e.disabled||!l.value||c.value||u.value||p.value,onClick:Y},[a.value&&!c.value?(F(),q("svg",Zd,N[9]||(N[9]=[x("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"},null,-1)]))):c.value?(F(),q("svg",Qd,N[11]||(N[11]=[x("circle",{cx:"12",cy:"12",r:"9",opacity:"0.3"},null,-1),x("path",{d:"M21 12a9 9 0 0 1-9 9"},null,-1)]))):(F(),q("svg",Xd,N[10]||(N[10]=[x("path",{d:"M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"},null,-1),x("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"},null,-1),x("path",{d:"M12 19v3"},null,-1)])))],10,Yd),x("button",{type:"submit",title:I.value,"aria-label":I.value,class:ye(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border-0 transition-all duration-200 hover:-translate-y-0.5 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",j.value]),style:{"border-radius":"9999px"},disabled:re.value},[e.isAwaitingResponse?(F(),q("svg",ep,N[12]||(N[12]=[x("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor","stroke-width":"2.1",class:"opacity-95"},null,-1),x("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.35",fill:"currentColor"},null,-1)]))):(F(),q("svg",tp,N[13]||(N[13]=[x("path",{d:"M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z"},null,-1)])))],10,Jd)],32),Me(Wd,{visible:w.value,message:E.value,type:m.value,dismissible:m.value!=="listening",onClose:We},null,8,["visible","message","type","dismissible"])]))}},sp={class:"relative overflow-hidden bg-linear-to-br from-brand-600 via-brand-500 to-violet-400"},rp={class:"min-w-0"},ip={key:1,class:"border-t border-slate-200/80 bg-white/90 px-3 py-3 pb-[calc(12px+env(safe-area-inset-bottom))] backdrop-blur-sm sm:px-4 sm:py-4"},op=56,lp={__name:"ChatbotPopup",props:{isOpen:{type:Boolean,required:!0},activeTab:{type:String,required:!0},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1},chatHistory:{type:Array,required:!0},debugLogs:{type:Array,required:!0},currentDebug:{type:Object,default:null},supportHistory:{type:Array,required:!0},autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},activeTtsProvider:{type:String,required:!0},settings:{type:Object,default:null},isAwaitingResponse:{type:Boolean,default:!1}},emits:["close","submit","cancelResponse","update:activeTab","toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=J(null),o=J(null),a=J(s.activeTab),l=J("default"),c=J(!1);function u(){const m=i.value;if(!s.isOpen||!m){c.value=!1;return}const A=m.scrollHeight-m.clientHeight;if(A<=4){c.value=!1;return}const T=A-m.scrollTop;c.value=T>op}function p(){const m=i.value;m&&(m.scrollTo({top:m.scrollHeight,behavior:"smooth"}),setTimeout(()=>{u()},220))}function g(){Tt(()=>{u()})}function w(){if(l.value==="default"){l.value="half";return}if(l.value==="half"){l.value="full";return}l.value="default"}const E=Re(()=>{const m="chat-shell fixed z-[9999] flex min-h-0 flex-col overflow-hidden border border-slate-200/80 shadow-[0_32px_80px_-44px_rgba(2,6,23,0.7),0_18px_40px_-24px_rgba(15,23,42,0.45)] transition-all duration-300 ease-out origin-bottom-right",A=s.isOpen?"pointer-events-auto opacity-100 translate-x-0 translate-y-0 scale-100 motion-safe:animate-surface-in":"pointer-events-none opacity-0 translate-x-1/5 translate-y-8 scale-95";return l.value==="full"?[m,A,"inset-0 h-screen w-screen max-h-screen max-w-screen rounded-none origin-center"]:l.value==="half"?[m,A,"bottom-[74px] right-5 h-[min(86vh,860px)] w-[min(50vw,860px)] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(86vh,760px)] max-[900px]:w-[min(70vw,760px)] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]:[m,A,"bottom-[74px] right-5 h-[min(560px,72vh)] w-[min(360px,calc(100vw-40px))] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(70vh,540px)] max-[900px]:w-[min(360px,calc(100vw-24px))] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]});return rn(()=>s.activeTab,m=>{a.value=m,g()}),rn(()=>s.isOpen,m=>{m&&a.value!=="settings"&&Tt(()=>{var A;return(A=o.value)==null?void 0:A.focus()}),g()}),rn(a,m=>{r("update:activeTab",m),g()}),rn(()=>[s.chatHistory.length,s.supportHistory.length,s.debugLogs.length,s.currentDebug],()=>{g()}),rn(()=>s.debugEnabled,m=>{!m&&a.value==="debug"&&(a.value="chat"),g()}),Hn(()=>{g()}),t({scrollToBottom(){Tt(()=>{p()})}}),(m,A)=>(F(),q("div",{class:ye(E.value),onKeydown:A[9]||(A[9]=ct(()=>{},["stop"])),onKeyup:A[10]||(A[10]=ct(()=>{},["stop"])),onKeypress:A[11]||(A[11]=ct(()=>{},["stop"]))},[A[14]||(A[14]=x("div",{class:"pointer-events-none absolute -right-14 -top-14 h-36 w-36 rounded-full bg-brand-500/15 blur-2xl"},null,-1)),A[15]||(A[15]=x("div",{class:"pointer-events-none absolute -bottom-14 -left-12 h-32 w-32 rounded-full bg-violet-400/15 blur-2xl"},null,-1)),x("div",sp,[A[12]||(A[12]=x("div",{class:"pointer-events-none absolute inset-0 opacity-45",style:{background:"linear-gradient(120deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.02) 52%, rgba(255,255,255,0.12) 100%)"}},null,-1)),Me(vc,{windowMode:l.value,autoReadEnabled:e.autoReadEnabled,activeTtsProvider:e.activeTtsProvider,onClose:A[0]||(A[0]=T=>m.$emit("close")),onCycleResize:w,onToggleAutoRead:A[1]||(A[1]=T=>m.$emit("toggleAutoRead"))},null,8,["windowMode","autoReadEnabled","activeTtsProvider"]),Me(Sc,{modelValue:a.value,"onUpdate:modelValue":A[2]||(A[2]=T=>a.value=T),debugEnabled:e.debugEnabled},null,8,["modelValue","debugEnabled"])]),x("div",{class:"chat-scrollbar min-h-0 flex-1 overflow-x-hidden overflow-y-scroll bg-slate-50/60 px-4 py-4 max-[900px]:px-3.5 max-[900px]:py-3.5 max-[600px]:px-3 max-[600px]:py-3",ref_key:"chatBodyRef",ref:i,onScrollPassive:u},[x("div",rp,[a.value==="chat"?(F(),St(md,{key:0,messages:e.chatHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="debug"&&e.debugEnabled?(F(),St(_d,{key:1,logs:e.debugLogs,currentDebug:e.currentDebug},null,8,["logs","currentDebug"])):a.value==="support"?(F(),St(Sd,{key:2,messages:e.supportHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="settings"?(F(),St(Vd,{key:3,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig,settings:e.settings,debugEnabled:e.debugEnabled,sendNonERPtoaiEnabled:e.sendNonERPtoaiEnabled,onToggleAutoRead:A[3]||(A[3]=T=>m.$emit("toggleAutoRead")),onTogglePollyPreference:A[4]||(A[4]=T=>m.$emit("togglePollyPreference")),onToggleDebug:A[5]||(A[5]=T=>m.$emit("toggleDebug")),onToggleSendNonERP:A[6]||(A[6]=T=>m.$emit("toggleSendNonERP"))},null,8,["autoReadEnabled","ttsConfig","settings","debugEnabled","sendNonERPtoaiEnabled"])):Ve("",!0)])],544),c.value?(F(),q("button",{key:0,type:"button",class:ye(["absolute right-4 z-20 grid h-9 w-9 place-items-center rounded-full border border-brand-200/70 bg-white/95 text-brand-600 shadow-[0_14px_26px_-16px_rgba(15,23,42,0.65)] transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-300 hover:text-brand-700 focus:outline-none",a.value!=="settings"?"bottom-[calc(90px+env(safe-area-inset-bottom))] sm:bottom-[96px]":"bottom-4 sm:bottom-5"]),title:"Scroll to bottom","aria-label":"Scroll to bottom",onClick:p},A[13]||(A[13]=[x("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},[x("path",{d:"M7 10l5 5 5-5"})],-1)]),2)):Ve("",!0),a.value!=="settings"?(F(),q("div",ip,[Me(np,{ref_key:"chatFormRef",ref:o,placeholder:a.value==="support"?"Message Support...":"Message...",disabled:a.value==="chat"&&e.isAwaitingResponse,isAwaitingResponse:a.value==="chat"&&e.isAwaitingResponse,onSubmit:A[7]||(A[7]=T=>m.$emit("submit",T)),onCancel:A[8]||(A[8]=T=>m.$emit("cancelResponse"))},null,8,["placeholder","disabled","isAwaitingResponse"])])):Ve("",!0)],34))}},_l="changai_chat_id",kl="changai_polly_enabled";function ap(){let e=sessionStorage.getItem(_l);return e||(e=`session_${Date.now()}_${crypto.randomUUID()}`,sessionStorage.setItem(_l,e)),e}function up(){const e=localStorage.getItem(kl);return e===null?!0:e==="true"}function cp(e){localStorage.setItem(kl,String(!!e))}const fp={__name:"App",setup(e){const t=J(!1),n=J("chat"),s=J([]),r=J([]),i=J(!1),o=J([]),a=J(null),l=J("actual"),c=J(!0),u=J(null),p=J(!1),g=J(null),w=J(!1),E=J({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd",enable_changai:!1}),m=J("off"),A=J(null),T=Re(()=>A.value!==null);function W(){if(!E.value.enableVoiceChat){m.value="off";return}m.value=E.value.usePolly?"polly":"browser"}function K(Y){var ce;const B=(ce=Y==null?void 0:Y.detail)==null?void 0:ce.provider;(B==="polly"||B==="browser"||B==="off")&&(m.value=B)}async function O(){var ce,Se,We,xt,fe;if(!(p.value||u.value)){p.value=!0;try{u.value=await Mc(l.value),E.value={enableVoiceChat:!!((ce=u.value)!=null&&ce.enable_voice_chat),pollyAvailable:!!((Se=u.value)!=null&&Se.polly_enabled),usePolly:!!((We=u.value)!=null&&We.polly_enabled)&&up(),voiceId:((xt=u.value)==null?void 0:xt.polly_voice_id)||"Zayd",enable_changai:!!((fe=u.value)!=null&&fe.enable_changai)},W(),r.value.push({type:"settings",settings:u.value})}catch(N){const pe=vl(N);r.value.push({type:"settings",error:pe})}finally{p.value=!1}}}function z(){t.value=!t.value}function P(){var Y;(Y=a.value)==null||Y.scrollToBottom()}function I(){c.value=!c.value}function re(){const Y=!E.value.usePolly;E.value={...E.value,usePolly:Y&&E.value.pollyAvailable},cp(E.value.usePolly),W()}function j(){w.value=!w.value}async function te(Y){n.value==="support"?await Z(Y):await ue(Y)}async function ue(Y){var ve;g.value=null,l.value==="actual"&&await O(),s.value.push({role:"user",text:Y}),await Tt(),P();const B=us({role:"model",text:"Thinking...",cancelable:!0,isStatus:!0,statusType:"thinking"});s.value.push(B),await Tt(),P();let ce=!1;const Se=ap(),We=`${Se}_${Date.now()}`,xt=w.value,fe=Pc(Y,Se,l.value,We,w.value),N=`debug_${We}`;let pe=Date.now();const he=[],ke=me=>{var ze;const le=Date.now(),yt=((le-pe)/1e3).toFixed(2);pe=le;const Ct=`${me.message} (${yt}s)`;if(me.message&&(he.push(Ct),g.value=Ct),!me.done&&me.message&&(B.text=me.message,B.statusType="pipeline"),me.done){B.cancelable=!1,me.error?(B.text=`⚠️ ${me.message||"Something failed"}`,B.isStatus=!1,B.statusType=null):(ze=me.data)!=null&&ze.answer&&(B.text=me.data.answer,B.isStatus=!1,B.statusType=null),frappe.realtime.off(N),g.value=null;return}};frappe.realtime.on(N,ke),A.value=()=>{ce||(ce=!0,fe.cancel(),frappe.realtime.off(N),B.isStatus=!1,B.statusType=null,B.text="Cancelled by user.",r.value.push({type:"cancelled",user:Y,steps:[...he]}),g.value=null,B.cancelable=!1,A.value=null)};try{const me=await fe.promise;if(ce)return;B.cancelable=!1;const le=((ve=bd(me==null?void 0:me.Bot))==null?void 0:ve.trim())||"No response.";B.isStatus=!1,B.statusType=null,B.text=le,r.value.push({type:"success",user:Y,steps:[...he],final_response:me}),g.value=null}catch(me){if(ce)return;frappe.realtime.off(N),B.cancelable=!1,B.isStatus=!1,B.statusType=null;const le=vl(me);g.value=null,r.value.push({type:"failed",user:Y,steps:[...he],error:le}),error==="ERR_NETWORK_CHANGED"&&(B.isStatus=!1,B.statusType=null,B.text="⚠️ Network error. Please check your connection and try again."),B.isStatus=!1,B.statusType=null,B.text="⚠️ Something went wrong. Please try again."}finally{frappe.realtime.off(N),ce||(A.value=null)}await Tt(),P()}function $(){var Y;(Y=A.value)==null||Y.call(A)}async function Z(Y){o.value.push({role:"user",text:Y}),await Tt(),P();const B=us({role:"model",text:"Sending to support...",isStatus:!0,statusType:"support"});o.value.push(B),await Tt(),P();try{const ce=await Ic(Y,l.value);B.text=ce?wl(ce):"Support request sent successfully."}catch{B.text="⚠️ Failed to reach support. Please try again."}await Tt(),P()}return Hn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-provider",K),l.value==="actual"&&O()}),xs(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-provider",K)}),(Y,B)=>(F(),q(Be,null,[E.value.enable_changai?(F(),St(ac,{key:0,isOpen:t.value,onToggle:z},null,8,["isOpen"])):Ve("",!0),Me(lp,{ref_key:"popupRef",ref:a,isOpen:t.value,activeTab:n.value,"onUpdate:activeTab":B[0]||(B[0]=ce=>n.value=ce),chatHistory:s.value,debugLogs:r.value,currentDebug:g.value,supportHistory:o.value,autoReadEnabled:c.value,ttsConfig:E.value,activeTtsProvider:m.value,settings:u.value,isAwaitingResponse:T.value,debugEnabled:i.value,sendNonERPtoaiEnabled:w.value,onToggleDebug:B[1]||(B[1]=ce=>i.value=!i.value),onClose:B[2]||(B[2]=ce=>t.value=!1),onSubmit:te,onCancelResponse:$,onToggleAutoRead:I,onTogglePollyPreference:re,onToggleSendNonERP:j},null,8,["isOpen","activeTab","chatHistory","debugLogs","currentDebug","supportHistory","autoReadEnabled","ttsConfig","activeTtsProvider","settings","isAwaitingResponse","debugEnabled","sendNonERPtoaiEnabled"])],64))}};function dp(){const e=document.querySelector('link[href*="/assets/changai/dist/changai-chatbot.css"]');if(e!=null&&e.href)return e.href;const t=Array.from(document.scripts).find(n=>{var s;return(s=n.src)==null?void 0:s.includes("/assets/changai/dist/changai-chatbot.js")});return t!=null&&t.src?t.src.replace(/changai-chatbot\.js(\?.*)?$/,"changai-chatbot.css$1"):null}function pp(e){const t=dp();if(!t){const n=Array.from(document.querySelectorAll("style[data-vite-dev-id]"));return n.length&&n.forEach(s=>{const r=document.createElement("style");r.dataset.changaiShadowDevStyle="1",r.textContent=s.textContent||"",e.appendChild(r)}),Promise.resolve()}return e.querySelector('link[data-changai-shadow-style="1"]')?Promise.resolve():new Promise(n=>{const s=document.createElement("link");s.rel="stylesheet",s.href=t,s.dataset.changaiShadowStyle="1",s.onload=()=>n(),s.onerror=()=>n(),e.appendChild(s),setTimeout(n,1200)})}async function Tl(){if(document.getElementById("changai-chatbot-host"))return;const e=document.createElement("div");e.id="changai-chatbot-host",document.body.appendChild(e);const t=e.attachShadow({mode:"open"});await pp(t);const n=document.createElement("div");n.id="changai-chatbot-root",t.appendChild(n),nc(fp).mount(n);function s(r){r.stopPropagation()}n.addEventListener("keydown",s),n.addEventListener("keyup",s),n.addEventListener("keypress",s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Tl):Tl()})(); +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${Ct(e,!0)}`}br(e){return"
"}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=Jo(e);if(r===null)return s;e=r;let i='
",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Jo(e);if(r===null)return Ct(n);e=r;let i=`${Ct(n)}{let l=o[a].flat(1/0);n=n.concat(this.walkTokens(l,t))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let a=r.renderer.apply(this,o);return a===!1&&(a=i.apply(this,o)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new $s(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,a=n.renderer[o],l=r[o];r[o]=(...f)=>{let u=a.apply(r,f);return u===!1&&(u=l.apply(r,f)),u||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new Ls(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,a=n.tokenizer[o],l=r[o];r[o]=(...f)=>{let u=a.apply(r,f);return u===!1&&(u=l.apply(r,f)),u}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new Zn;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,a=n.hooks[o],l=r[o];Zn.passThroughHooks.has(i)?r[o]=f=>{if(this.defaults.async&&Zn.passThroughHooksRespectAsync.has(i))return(async()=>{let d=await a.call(r,f);return l.call(r,d)})();let u=a.call(r,f);return l.call(r,u)}:r[o]=(...f)=>{if(this.defaults.async)return(async()=>{let d=await a.apply(r,f);return d===!1&&(d=await l.apply(r,f)),d})();let u=a.apply(r,f);return u===!1&&(u=l.apply(r,f)),u}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(i.call(this,o)),r&&(a=a.concat(r.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return yt.lex(e,t!=null?t:this.defaults)}parser(e,t){return wt.parse(e,t!=null?t:this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},r={...this.defaults,...s},i=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?yt.lex:yt.lexInline)(o,r),l=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let f=await(r.hooks?await r.hooks.provideParser(e):e?wt.parse:wt.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(f):f})().catch(i);try{r.hooks&&(t=r.hooks.preprocess(t));let o=(r.hooks?r.hooks.provideLexer(e):e?yt.lex:yt.lexInline)(t,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?wt.parse:wt.parseInline)(o,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(o){return i(o)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s="

An error occurred:

"+Ct(n.message+"",!0)+"
";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},pn=new vf;function xe(e,t){return pn.parse(e,t)}xe.options=xe.setOptions=function(e){return pn.setOptions(e),xe.defaults=pn.defaults,Ho(xe.defaults),xe},xe.getDefaults=Sr,xe.defaults=cn,xe.use=function(...e){return pn.use(...e),xe.defaults=pn.defaults,Ho(xe.defaults),xe},xe.walkTokens=function(e,t){return pn.walkTokens(e,t)},xe.parseInline=pn.parseInline,xe.Parser=wt,xe.parser=wt.parse,xe.Renderer=$s,xe.TextRenderer=Lr,xe.Lexer=yt,xe.lexer=yt.lex,xe.Tokenizer=Ls,xe.Hooks=Zn,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,wt.parse,yt.lex;function sl(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,s=Array(t);n2?s-2:0),i=2;i1?n-1:0),r=1;r1?n-1:0),r=1;r2&&arguments[2]!==void 0?arguments[2]:Xn;if(il&&il(e,null),!Xe(t))return e;let s=t.length;for(;s--;){let r=t[s];if(typeof r=="string"){const i=n(r);i!==r&&(Af(t)||(t[s]=i),r=i)}e[r]=!0}return e}function Df(e){for(let t=0;t/g),jf=dt(/\${[\w\W]*/g),Vf=dt(/^data-[\-\w.\u00B7-\uFFFF]+$/),qf=dt(/^aria-[\-\w]+$/),ml=dt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Wf=dt(/^(?:\w+script|data):/i),Gf=dt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Kf=dt(/^html$/i),Yf=dt(/^[a-z][.\w]*(-[.\w]+)+$/i),Rn={element:1,text:3,progressingInstruction:7,comment:8,document:9},Zf=function(){return typeof window=="undefined"?null:window},Xf=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const r="data-tt-policy-suffix";n&&n.hasAttribute(r)&&(s=n.getAttribute(r));const i="dompurify"+(s?"#"+s:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return null}},bl=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function xl(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Zf();const t=q=>xl(q);if(t.version="3.4.3",t.removed=[],!e||!e.document||e.document.nodeType!==Rn.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const s=n,r=s.currentScript,i=e.DocumentFragment,o=e.HTMLTemplateElement,a=e.Node,l=e.Element,f=e.NodeFilter,u=e.NamedNodeMap,d=u===void 0?e.NamedNodeMap||e.MozNamedAttrMap:u,g=e.HTMLFormElement,y=e.DOMParser,E=e.trustedTypes,x=l.prototype,M=An(x,"cloneNode"),m=An(x,"remove"),H=An(x,"nextSibling"),Y=An(x,"childNodes"),$=An(x,"parentNode");if(typeof o=="function"){const q=n.createElement("template");q.content&&q.content.ownerDocument&&(n=q.content.ownerDocument)}let z,O="";const P=n,ee=P.implementation,V=P.createNodeIterator,se=P.createDocumentFragment,fe=P.getElementsByTagName,D=s.importNode;let Z=bl();t.isSupported=typeof rl=="function"&&typeof $=="function"&&ee&&ee.createHTMLDocument!==void 0;const Se=zf,Ue=Uf,te=jf,C=Vf,pe=qf,Ge=Wf,re=Gf,B=Yf;let de=ml,ae=null;const ve=X({},[...pl,...Fr,...Br,...Hr,...dl]);let ge=null;const nt=X({},[...hl,...zr,...gl,...Ns]);let ye=Object.seal(Tn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ht=null,G=null;const Ce=Object.seal(Tn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ft=!0,c=!0,h=!1,b=!0,k=!1,v=!0,_=!1,I=!1,R=!1,A=!1,S=!1,U=!1,L=!0,j=!1;const K="user-content-";let ne=!0,he=!1,ie={},ke=null;const $e=X({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ot=null;const lt=X({},["audio","video","img","source","image","track"]);let Bt=null;const Jn=X({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),De="http://www.w3.org/1998/Math/MathML",Qe="http://www.w3.org/2000/svg",at="http://www.w3.org/1999/xhtml";let Ht=at,Ur=!1,jr=null;const hd=X({},[De,Qe,at],Nr);let Vr=X({},["mi","mo","mn","ms","mtext"]),qr=X({},["annotation-xml"]);const gd=X({},["title","style","font","a","script"]);let es=null;const md=["application/xhtml+xml","text/html"],bd="text/html";let Le=null,Cn=null;const xd=n.createElement("form"),Sl=function(p){return p instanceof RegExp||p instanceof Function},Wr=function(){let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Cn&&Cn===p)return;(!p||typeof p!="object")&&(p={}),p=tt(p),es=md.indexOf(p.PARSER_MEDIA_TYPE)===-1?bd:p.PARSER_MEDIA_TYPE,Le=es==="application/xhtml+xml"?Nr:Xn,ae=Ae(p,"ALLOWED_TAGS")&&Xe(p.ALLOWED_TAGS)?X({},p.ALLOWED_TAGS,Le):ve,ge=Ae(p,"ALLOWED_ATTR")&&Xe(p.ALLOWED_ATTR)?X({},p.ALLOWED_ATTR,Le):nt,jr=Ae(p,"ALLOWED_NAMESPACES")&&Xe(p.ALLOWED_NAMESPACES)?X({},p.ALLOWED_NAMESPACES,Nr):hd,Bt=Ae(p,"ADD_URI_SAFE_ATTR")&&Xe(p.ADD_URI_SAFE_ATTR)?X(tt(Jn),p.ADD_URI_SAFE_ATTR,Le):Jn,ot=Ae(p,"ADD_DATA_URI_TAGS")&&Xe(p.ADD_DATA_URI_TAGS)?X(tt(lt),p.ADD_DATA_URI_TAGS,Le):lt,ke=Ae(p,"FORBID_CONTENTS")&&Xe(p.FORBID_CONTENTS)?X({},p.FORBID_CONTENTS,Le):$e,ht=Ae(p,"FORBID_TAGS")&&Xe(p.FORBID_TAGS)?X({},p.FORBID_TAGS,Le):tt({}),G=Ae(p,"FORBID_ATTR")&&Xe(p.FORBID_ATTR)?X({},p.FORBID_ATTR,Le):tt({}),ie=Ae(p,"USE_PROFILES")?p.USE_PROFILES&&typeof p.USE_PROFILES=="object"?tt(p.USE_PROFILES):p.USE_PROFILES:!1,Ft=p.ALLOW_ARIA_ATTR!==!1,c=p.ALLOW_DATA_ATTR!==!1,h=p.ALLOW_UNKNOWN_PROTOCOLS||!1,b=p.ALLOW_SELF_CLOSE_IN_ATTR!==!1,k=p.SAFE_FOR_TEMPLATES||!1,v=p.SAFE_FOR_XML!==!1,_=p.WHOLE_DOCUMENT||!1,A=p.RETURN_DOM||!1,S=p.RETURN_DOM_FRAGMENT||!1,U=p.RETURN_TRUSTED_TYPE||!1,R=p.FORCE_BODY||!1,L=p.SANITIZE_DOM!==!1,j=p.SANITIZE_NAMED_PROPS||!1,ne=p.KEEP_CONTENT!==!1,he=p.IN_PLACE||!1,de=Ff(p.ALLOWED_URI_REGEXP)?p.ALLOWED_URI_REGEXP:ml,Ht=typeof p.NAMESPACE=="string"?p.NAMESPACE:at,Vr=Ae(p,"MATHML_TEXT_INTEGRATION_POINTS")&&p.MATHML_TEXT_INTEGRATION_POINTS&&typeof p.MATHML_TEXT_INTEGRATION_POINTS=="object"?tt(p.MATHML_TEXT_INTEGRATION_POINTS):X({},["mi","mo","mn","ms","mtext"]),qr=Ae(p,"HTML_INTEGRATION_POINTS")&&p.HTML_INTEGRATION_POINTS&&typeof p.HTML_INTEGRATION_POINTS=="object"?tt(p.HTML_INTEGRATION_POINTS):X({},["annotation-xml"]);const T=Ae(p,"CUSTOM_ELEMENT_HANDLING")&&p.CUSTOM_ELEMENT_HANDLING&&typeof p.CUSTOM_ELEMENT_HANDLING=="object"?tt(p.CUSTOM_ELEMENT_HANDLING):Tn(null);if(ye=Tn(null),Ae(T,"tagNameCheck")&&Sl(T.tagNameCheck)&&(ye.tagNameCheck=T.tagNameCheck),Ae(T,"attributeNameCheck")&&Sl(T.attributeNameCheck)&&(ye.attributeNameCheck=T.attributeNameCheck),Ae(T,"allowCustomizedBuiltInElements")&&typeof T.allowCustomizedBuiltInElements=="boolean"&&(ye.allowCustomizedBuiltInElements=T.allowCustomizedBuiltInElements),k&&(c=!1),S&&(A=!0),ie&&(ae=X({},dl),ge=Tn(null),ie.html===!0&&(X(ae,pl),X(ge,hl)),ie.svg===!0&&(X(ae,Fr),X(ge,zr),X(ge,Ns)),ie.svgFilters===!0&&(X(ae,Br),X(ge,zr),X(ge,Ns)),ie.mathMl===!0&&(X(ae,Hr),X(ge,gl),X(ge,Ns))),Ce.tagCheck=null,Ce.attributeCheck=null,Ae(p,"ADD_TAGS")&&(typeof p.ADD_TAGS=="function"?Ce.tagCheck=p.ADD_TAGS:Xe(p.ADD_TAGS)&&(ae===ve&&(ae=tt(ae)),X(ae,p.ADD_TAGS,Le))),Ae(p,"ADD_ATTR")&&(typeof p.ADD_ATTR=="function"?Ce.attributeCheck=p.ADD_ATTR:Xe(p.ADD_ATTR)&&(ge===nt&&(ge=tt(ge)),X(ge,p.ADD_ATTR,Le))),Ae(p,"ADD_URI_SAFE_ATTR")&&Xe(p.ADD_URI_SAFE_ATTR)&&X(Bt,p.ADD_URI_SAFE_ATTR,Le),Ae(p,"FORBID_CONTENTS")&&Xe(p.FORBID_CONTENTS)&&(ke===$e&&(ke=tt(ke)),X(ke,p.FORBID_CONTENTS,Le)),Ae(p,"ADD_FORBID_CONTENTS")&&Xe(p.ADD_FORBID_CONTENTS)&&(ke===$e&&(ke=tt(ke)),X(ke,p.ADD_FORBID_CONTENTS,Le)),ne&&(ae["#text"]=!0),_&&X(ae,["html","head","body"]),ae.table&&(X(ae,["tbody"]),delete ht.tbody),p.TRUSTED_TYPES_POLICY){if(typeof p.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ds('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof p.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ds('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');z=p.TRUSTED_TYPES_POLICY,O=z.createHTML("")}else z===void 0&&(z=Xf(E,r)),z!==null&&typeof O=="string"&&(O=z.createHTML(""));Ze&&Ze(p),Cn=p},El=X({},[...Fr,...Br,...Bf]),Al=X({},[...Hr,...Hf]),yd=function(p){let T=$(p);(!T||!T.tagName)&&(T={namespaceURI:Ht,tagName:"template"});const N=Xn(p.tagName),ce=Xn(T.tagName);return jr[p.namespaceURI]?p.namespaceURI===Qe?T.namespaceURI===at?N==="svg":T.namespaceURI===De?N==="svg"&&(ce==="annotation-xml"||Vr[ce]):!!El[N]:p.namespaceURI===De?T.namespaceURI===at?N==="math":T.namespaceURI===Qe?N==="math"&&qr[ce]:!!Al[N]:p.namespaceURI===at?T.namespaceURI===Qe&&!qr[ce]||T.namespaceURI===De&&!Vr[ce]?!1:!Al[N]&&(gd[N]||!El[N]):!!(es==="application/xhtml+xml"&&jr[p.namespaceURI]):!1},vt=function(p){Sn(t.removed,{element:p});try{$(p).removeChild(p)}catch{m(p)}},dn=function(p,T){try{Sn(t.removed,{attribute:T.getAttributeNode(p),from:T})}catch{Sn(t.removed,{attribute:null,from:T})}if(T.removeAttribute(p),p==="is")if(A||S)try{vt(T)}catch{}else try{T.setAttribute(p,"")}catch{}},Rl=function(p){let T=null,N=null;if(R)p=""+p;else{const Me=al(p,/^[\r\n\t ]+/);N=Me&&Me[0]}es==="application/xhtml+xml"&&Ht===at&&(p=''+p+"");const ce=z?z.createHTML(p):p;if(Ht===at)try{T=new y().parseFromString(ce,es)}catch{}if(!T||!T.documentElement){T=ee.createDocument(Ht,"template",null);try{T.documentElement.innerHTML=Ur?O:ce}catch{}}const Ne=T.body||T.documentElement;return p&&N&&Ne.insertBefore(n.createTextNode(N),Ne.childNodes[0]||null),Ht===at?fe.call(T,_?"html":"body")[0]:_?T.documentElement:Ne},Cl=function(p){return V.call(p.ownerDocument||p,p,f.SHOW_ELEMENT|f.SHOW_COMMENT|f.SHOW_TEXT|f.SHOW_PROCESSING_INSTRUCTION|f.SHOW_CDATA_SECTION,null)},Gr=function(p){return p instanceof g&&(typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||!(p.attributes instanceof d)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function"||typeof p.hasChildNodes!="function")},Kr=function(p){return typeof a=="function"&&p instanceof a};function zt(q,p,T){kn(q,N=>{N.call(t,p,T,Cn)})}const Pl=function(p){let T=null;if(zt(Z.beforeSanitizeElements,p,null),Gr(p))return vt(p),!0;const N=Le(p.nodeName);if(zt(Z.uponSanitizeElement,p,{tagName:N,allowedTags:ae}),v&&p.hasChildNodes()&&!Kr(p.firstElementChild)&&ze(/<[/\w!]/g,p.innerHTML)&&ze(/<[/\w!]/g,p.textContent)||v&&p.namespaceURI===at&&N==="style"&&Kr(p.firstElementChild)||p.nodeType===Rn.progressingInstruction||v&&p.nodeType===Rn.comment&&ze(/<[/\w]/g,p.data))return vt(p),!0;if(ht[N]||!(Ce.tagCheck instanceof Function&&Ce.tagCheck(N))&&!ae[N]){if(!ht[N]&&Ml(N)&&(ye.tagNameCheck instanceof RegExp&&ze(ye.tagNameCheck,N)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(N)))return!1;if(ne&&!ke[N]){const ce=$(p)||p.parentNode,Ne=Y(p)||p.childNodes;if(Ne&&ce){const Me=Ne.length;for(let st=Me-1;st>=0;--st){const gt=M(Ne[st],!0);ce.insertBefore(gt,H(p))}}}return vt(p),!0}return p instanceof l&&!yd(p)||(N==="noscript"||N==="noembed"||N==="noframes")&&ze(/<\/no(script|embed|frames)/i,p.innerHTML)?(vt(p),!0):(k&&p.nodeType===Rn.text&&(T=p.textContent,kn([Se,Ue,te],ce=>{T=En(T,ce," ")}),p.textContent!==T&&(Sn(t.removed,{element:p.cloneNode()}),p.textContent=T)),zt(Z.afterSanitizeElements,p,null),!1)},Il=function(p,T,N){if(G[T]||L&&(T==="id"||T==="name")&&(N in n||N in xd))return!1;const ce=ge[T]||Ce.attributeCheck instanceof Function&&Ce.attributeCheck(T,p);if(!(c&&!G[T]&&ze(C,T))){if(!(Ft&&ze(pe,T))){if(!ce||G[T]){if(!(Ml(p)&&(ye.tagNameCheck instanceof RegExp&&ze(ye.tagNameCheck,p)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(p))&&(ye.attributeNameCheck instanceof RegExp&&ze(ye.attributeNameCheck,T)||ye.attributeNameCheck instanceof Function&&ye.attributeNameCheck(T,p))||T==="is"&&ye.allowCustomizedBuiltInElements&&(ye.tagNameCheck instanceof RegExp&&ze(ye.tagNameCheck,N)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(N))))return!1}else if(!Bt[T]){if(!ze(de,En(N,re,""))){if(!((T==="src"||T==="xlink:href"||T==="href")&&p!=="script"&&ul(N,"data:")===0&&ot[p])){if(!(h&&!ze(Ge,En(N,re,"")))){if(N)return!1}}}}}}return!0},wd=X({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Ml=function(p){return!wd[Xn(p)]&&ze(B,p)},Ol=function(p){zt(Z.beforeSanitizeAttributes,p,null);const T=p.attributes;if(!T||Gr(p))return;const N={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ge,forceKeepAttr:void 0};let ce=T.length;for(;ce--;){const Ne=T[ce],Me=Ne.name,st=Ne.namespaceURI,gt=Ne.value,_t=Le(Me),Zr=gt;let Fe=Me==="value"?Zr:Mf(Zr);if(N.attrName=_t,N.attrValue=Fe,N.keepAttr=!0,N.forceKeepAttr=void 0,zt(Z.uponSanitizeAttribute,p,N),Fe=N.attrValue,j&&(_t==="id"||_t==="name")&&ul(Fe,K)!==0&&(dn(Me,p),Fe=K+Fe),v&&ze(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Fe)){dn(Me,p);continue}if(_t==="attributename"&&al(Fe,"href")){dn(Me,p);continue}if(N.forceKeepAttr)continue;if(!N.keepAttr){dn(Me,p);continue}if(!b&&ze(/\/>/i,Fe)){dn(Me,p);continue}k&&kn([Se,Ue,te],$l=>{Fe=En(Fe,$l," ")});const Ll=Le(p.nodeName);if(!Il(Ll,_t,Fe)){dn(Me,p);continue}if(z&&typeof E=="object"&&typeof E.getAttributeType=="function"&&!st)switch(E.getAttributeType(Ll,_t)){case"TrustedHTML":{Fe=z.createHTML(Fe);break}case"TrustedScriptURL":{Fe=z.createScriptURL(Fe);break}}if(Fe!==Zr)try{st?p.setAttributeNS(st,Me,Fe):p.setAttribute(Me,Fe),Gr(p)?vt(p):ll(t.removed)}catch{dn(Me,p)}}zt(Z.afterSanitizeAttributes,p,null)},Yr=function(p){let T=null;const N=Cl(p);for(zt(Z.beforeSanitizeShadowDOM,p,null);T=N.nextNode();)zt(Z.uponSanitizeShadowNode,T,null),Pl(T),Ol(T),T.content instanceof i&&Yr(T.content);zt(Z.afterSanitizeShadowDOM,p,null)},Bs=function(p){if(p.nodeType===Rn.element&&p.shadowRoot instanceof i){const ce=p.shadowRoot;Bs(ce),Yr(ce)}const T=p.childNodes;if(!T)return;const N=[];kn(T,ce=>{Sn(N,ce)});for(const ce of N)Bs(ce)};return t.sanitize=function(q){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},T=null,N=null,ce=null,Ne=null;if(Ur=!q,Ur&&(q=""),typeof q!="string"&&!Kr(q)&&(q=Nf(q),typeof q!="string"))throw Ds("dirty is not a string, aborting");if(!t.isSupported)return q;if(I||Wr(p),t.removed=[],typeof q=="string"&&(he=!1),he){const gt=q.nodeName;if(typeof gt=="string"){const _t=Le(gt);if(!ae[_t]||ht[_t])throw Ds("root node is forbidden and cannot be sanitized in-place")}Bs(q)}else if(q instanceof a)T=Rl(""),N=T.ownerDocument.importNode(q,!0),N.nodeType===Rn.element&&N.nodeName==="BODY"||N.nodeName==="HTML"?T=N:T.appendChild(N),Bs(N);else{if(!A&&!k&&!_&&q.indexOf("<")===-1)return z&&U?z.createHTML(q):q;if(T=Rl(q),!T)return A?null:U?O:""}T&&R&&vt(T.firstChild);const Me=Cl(he?q:T);for(;ce=Me.nextNode();)Pl(ce),Ol(ce),ce.content instanceof i&&Yr(ce.content);if(he)return q;if(A){if(k){T.normalize();let gt=T.innerHTML;kn([Se,Ue,te],_t=>{gt=En(gt,_t," ")}),T.innerHTML=gt}if(S)for(Ne=se.call(T.ownerDocument);T.firstChild;)Ne.appendChild(T.firstChild);else Ne=T;return(ge.shadowroot||ge.shadowrootmode)&&(Ne=D.call(s,Ne,!0)),Ne}let st=_?T.outerHTML:T.innerHTML;return _&&ae["!doctype"]&&T.ownerDocument&&T.ownerDocument.doctype&&T.ownerDocument.doctype.name&&ze(Kf,T.ownerDocument.doctype.name)&&(st=" +`+st),k&&kn([Se,Ue,te],gt=>{st=En(st,gt," ")}),z&&U?z.createHTML(st):st},t.setConfig=function(){let q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Wr(q),I=!0},t.clearConfig=function(){Cn=null,I=!1},t.isValidAttribute=function(q,p,T){Cn||Wr({});const N=Le(q),ce=Le(p);return Il(N,ce,T)},t.addHook=function(q,p){typeof p=="function"&&Sn(Z[q],p)},t.removeHook=function(q,p){if(p!==void 0){const T=Pf(Z[q],p);return T===-1?void 0:If(Z[q],T,1)[0]}return ll(Z[q])},t.removeHooks=function(q){Z[q]=[]},t.removeAllHooks=function(){Z=bl()},t}var Qf=xl();const Jf={key:1,class:"flex min-w-0 max-w-[calc(100%-2.5rem)] flex-1 flex-col max-[600px]:max-w-[calc(100%-2.25rem)]"},ep={key:0,class:"flex w-fit flex-col items-start gap-1"},tp=["aria-label"],np={class:"inline-flex items-center gap-1.5"},sp={class:"text-[8px] font-semibold tracking-[0.12em] uppercase text-[#3a67c9]"},rp={key:1,class:"flex w-fit max-w-full flex-col items-start gap-2"},ip={class:"chat-card relative w-fit max-w-full whitespace-pre-line rounded-[10px_10px_10px_3px] px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900"},op=["innerHTML"],lp={key:0,class:"pointer-events-none absolute inset-x-0 bottom-0 h-14 rounded-b-[10px] bg-linear-to-t from-white via-white/92 to-white/0","aria-hidden":"true"},ap={key:0,class:"flex flex-wrap items-center gap-2"},up=["title","aria-label"],cp={key:1,class:"flex flex-wrap items-center"},fp=["title","aria-label"],pp={viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},dp=["innerHTML"],yl={__name:"ChatMessage",props:{message:{type:Object,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,default:()=>({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd"})}},setup(e){const t=e,n=J(!1),s=J(null),r=J(!1),i=J(!1),o=Ee(()=>typeof window!="undefined"&&"speechSynthesis"in window&&"SpeechSynthesisUtterance"in window);function a(O){typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("changai-tts-provider",{detail:{provider:O}}))}function l(O){if(typeof O!="string")return"";const P=O.replace(/[\u{1F000}-\u{1FFFF}]/gu,"").replace(/[\u{2600}-\u{26FF}]/gu,"").replace(/[\u{2700}-\u{27BF}]/gu,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/#{1,6}\s+/g,"").replace(/[-*+]\s+/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\s+/g," ");return P.includes("<")?(new DOMParser().parseFromString(O,"text/html").body.textContent||"").replace(/\s+/g," ").trim():P.trim()}function f(){o.value&&window.speechSynthesis.cancel(),s.value&&(s.value.pause(),s.value.src="",s.value=null),n.value=!1}function u(){var O,P,ee;if(i.value=!i.value,i.value)f();else{const V=M.value;if(!t.autoReadEnabled||!((O=t.ttsConfig)!=null&&O.enableVoiceChat)||!V||E())return;if((P=t.ttsConfig)!=null&&P.pollyAvailable&&((ee=t.ttsConfig)!=null&&ee.usePolly)){g(V).catch(se=>{d(V)});return}d(V)}}function d(O){if(!o.value||!O)return;window.dispatchEvent(new CustomEvent("changai-tts-stop")),window.speechSynthesis.cancel();const P=new SpeechSynthesisUtterance(O);P.rate=1,P.pitch=1,P.onend=()=>{n.value=!1},P.onerror=()=>{n.value=!1},n.value=!0,a("browser"),window.speechSynthesis.speak(P)}async function g(O){var fe;const P=await Oc(O,((fe=t.ttsConfig)==null?void 0:fe.voiceId)||"Zayd");if(!(P!=null&&P.ok)||!(P!=null&&P.audio_base64))throw new Error((P==null?void 0:P.error)||"Polly synthesis failed");window.dispatchEvent(new CustomEvent("changai-tts-stop")),f();const ee=(P==null?void 0:P.mime_type)||"audio/mpeg",V=new Audio(`data:${ee};base64,${P.audio_base64}`);s.value=V,n.value=!0;let se=!1;V.onplay=()=>{se=!0,a("polly")},V.onended=()=>{s.value===V&&(s.value=null),n.value=!1},V.onerror=()=>{s.value===V&&(s.value=null),n.value=!1},await V.play(),se||a("polly")}function y(){f()}function E(){var O;return!!((O=t.message)!=null&&O.isStatus)}function x(O){const P=O.target.closest("a");!P||!P.href||(O.preventDefault(),O.stopPropagation(),window.open(P.href,"_blank","noopener,noreferrer"))}const M=Ee(()=>{var O;return l(((O=t.message)==null?void 0:O.text)||"")}),m=Ee(()=>{var O;return((O=t.message)==null?void 0:O.role)!=="user"&&E()}),H=Ee(()=>{var O;return(O=t.message)!=null&&O.isStatus?t.message.statusType==="support"?"Sending to support":M.value||"Thinking":""}),Y=Ee(()=>{var ee;if(((ee=t.message)==null?void 0:ee.role)==="user"||m.value)return!1;const O=M.value,P=O.split(/\n+/).filter(Boolean).length;return O.length>520||P>8}),$=Ee(()=>{var O,P;return((O=t.message)==null?void 0:O.role)!=="user"&&!m.value&&((P=t.ttsConfig)==null?void 0:P.enableVoiceChat)}),z=Ee(()=>{var P;const O=((P=t.message)==null?void 0:P.text)||"";return Qf.sanitize(xe.parse(O))});return on(()=>t.message.text,async(O,P)=>{var se,fe,D;if(!t.autoReadEnabled||t.message.role==="user"||i.value)return;if(!((se=t.ttsConfig)!=null&&se.enableVoiceChat)){a("off");return}const ee=l(O);if(!ee||E())return;const V=l(P||"");if(ee!==V){if((fe=t.ttsConfig)!=null&&fe.pollyAvailable&&((D=t.ttsConfig)!=null&&D.usePolly))try{await g(ee);return}catch{}d(ee)}}),on(()=>t.message.text,()=>{r.value=!1,i.value=!1}),zn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-stop",y)}),ys(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-stop",y),n.value&&f()}),(O,P)=>(F(),W("div",{class:we(["motion-safe:animate-fade-rise flex w-full gap-1.5",e.message.role==="user"?"flex-col items-end":"items-start"])},[e.message.role!=="user"?(F(),Et(Fo,{key:0})):qe("",!0),e.message.role!=="user"?(F(),W("div",Jf,[m.value?(F(),W("div",ep,[w("div",{class:"chat-card inline-flex w-fit rounded-[10px_10px_10px_3px] px-3 py-2",role:"status","aria-live":"polite","aria-label":H.value},[w("div",np,[P[1]||(P[1]=w("span",{class:"relative inline-flex h-4 w-4 shrink-0 items-center justify-center"},[w("span",{class:"absolute inset-0 rounded-full border border-transparent border-t-[#4b89ff] border-r-[#4b89ff]/70 animate-gemini-arc"}),w("svg",{viewBox:"0 0 24 24",class:"relative h-3 w-3 text-[#4b89ff] animate-gemini-spark","aria-hidden":"true"},[w("path",{fill:"currentColor",d:"M12 2.8c.52 3.22 1.6 5.66 3.22 7.28 1.62 1.62 4.06 2.7 7.28 3.22-3.22.52-5.66 1.6-7.28 3.22-1.62 1.62-2.7 4.06-3.22 7.28-.52-3.22-1.6-5.66-3.22-7.28-1.62-1.62-4.06-2.7-7.28-3.22 3.22-.52 5.66-1.6 7.28-3.22 1.62-1.62 2.7-4.06 3.22-7.28Z"})])],-1)),w("span",sp,Je(H.value),1)])],8,tp)])):(F(),W("div",rp,[w("div",ip,[w("div",{class:we(["overflow-x-auto",Y.value&&!r.value?"max-h-48 overflow-y-hidden":""]),innerHTML:z.value,onClick:x},null,10,op),Y.value&&!r.value?(F(),W("div",lp)):qe("",!0)]),Y.value?(F(),W("div",ap,[w("button",{type:"button",class:"inline-flex items-center rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-600 transition-colors duration-200 hover:border-brand-200 hover:text-brand-600",title:r.value?"Collapse response":"Expand response","aria-label":r.value?"Collapse response":"Expand response",onClick:P[0]||(P[0]=ee=>r.value=!r.value)},Je(r.value?"Collapse":"Expand"),9,up)])):qe("",!0),$.value?(F(),W("div",cp,[w("button",{type:"button",class:we(["inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors duration-200",i.value?"border-red-200 bg-red-50 text-red-600 hover:border-red-300 hover:bg-red-100":"border-green-200 bg-green-50 text-green-600 hover:border-green-300 hover:bg-green-100"]),title:i.value?"Unmute voice playback":"Mute voice playback","aria-label":i.value?"Unmute voice playback":"Mute voice playback",onClick:u},[(F(),W("svg",pp,[P[6]||(P[6]=w("path",{d:"M11 5L6 9H3v6h3l5 4V5Z"},null,-1)),i.value?(F(),W(He,{key:0},[P[2]||(P[2]=w("path",{d:"M15 9l4 6"},null,-1)),P[3]||(P[3]=w("path",{d:"M19 9l-4 6"},null,-1))],64)):(F(),W(He,{key:1},[P[4]||(P[4]=w("path",{d:"M15 10a3 3 0 0 1 0 4"},null,-1)),P[5]||(P[5]=w("path",{d:"M17.5 7.5a6 6 0 0 1 0 9"},null,-1))],64))]))],10,fp)])):qe("",!0)]))])):(F(),W("div",{key:2,class:"w-fit max-w-[85%] whitespace-pre-line rounded-[13px_13px_3px_13px] bg-linear-to-br from-brand-500 to-brand-600 px-4 py-3 text-[11px] leading-relaxed wrap-anywhere text-white shadow-[0_14px_30px_-18px_rgba(109,79,194,0.85)] max-[600px]:max-w-[88%]",innerHTML:z.value},null,8,dp))],2))}},hp={class:"flex flex-col gap-4 sm:gap-5"},gp={class:"motion-safe:animate-fade-rise flex w-full items-start gap-1.5"},mp={__name:"ChatTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(F(),W("div",hp,[w("div",gp,[Oe(Fo),n[0]||(n[0]=w("p",{class:"w-fit max-w-[calc(100%-2.5rem)] whitespace-pre-line rounded-[10px_10px_10px_3px] bg-brand-50 px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900 max-[600px]:max-w-[calc(100%-2.25rem)]"},[Ss(" Hello there 👋 I am ChangAI from "),w("a",{target:"_blank",href:"https://erpgulf.com",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ERPGulf.com"),Ss(", your ERP assistant."),w("br"),w("a",{target:"_blank",href:"https://app.erpgulf.com/en/articles/chang-ai-quick-start-guide",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ChangAI Quick Start Guide - Click here.")],-1))]),(F(!0),W(He,null,ws(e.messages,(s,r)=>(F(),Et(yl,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}};function wl(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function vl(e){var t,n;return(e==null?void 0:e.message)||((t=e==null?void 0:e.responseJSON)==null?void 0:t.exception)||((n=e==null?void 0:e.responseJSON)==null?void 0:n.message)||(e==null?void 0:e.responseText)||String(e)}function bp(e){return typeof e=="string"?e:e&&typeof e=="object"?e.error?`⚠️ ${e.error}`:e.answer||e.text||"":""}const xp={key:0,class:"rounded-lg bg-brand-50 px-4 py-3 text-xs text-black"},yp={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},wp={key:1,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-brand-50 p-2 text-[11px]"},vp={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},_p={__name:"DebugTab",props:{logs:{type:Array,required:!0},currentDebug:{type:Object,default:null}},setup(e){const t=new Set(["gemini_json_content","private_key","private_key_id","client_secret","client_id","aws_access_key","aws_secret_key","api_key","token","access_token","refresh_token","password","secret","authorization","embed_version_id","llm_version_id","entity_retriever","retriever","deploy_url","support_api_url","get_ticket_details_url"]);function n(r,i=0){if(i>10||r===null||r===void 0||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(Array.isArray(r))return r.map(o=>n(o,i+1));if(typeof r=="object"){const o={};for(const[a,l]of Object.entries(r))t.has(a.toLowerCase())||(o[a]=n(l,i+1));return o}return r}function s(r){return wl(n(r))}return(r,i)=>(F(),W("div",null,[e.logs.length===0?(F(),W("p",xp,"No debug data yet.")):qe("",!0),(F(!0),W(He,null,ws(e.logs,(o,a)=>(F(),W("div",{key:a,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-gray-100 p-2 text-[11px]"},[w("pre",yp,Je(s(o)),1)]))),128)),e.currentDebug?(F(),W("div",wp,[w("pre",vp,Je(s(e.currentDebug)),1)])):qe("",!0)]))}},Tp={class:"flex flex-col gap-4 sm:gap-5"},kp={key:0,class:"chat-card motion-safe:animate-fade-rise rounded-lg px-4 py-3 text-xs text-slate-900"},Sp={__name:"SupportTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(F(),W("div",Tp,[e.messages.length===0?(F(),W("p",kp,"Send a message to Support.")):qe("",!0),(F(!0),W(He,null,ws(e.messages,(s,r)=>(F(),Et(yl,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}},Ep={class:"flex flex-col gap-4"},Ap={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Rp={class:"flex items-start justify-between gap-4"},Cp=["aria-pressed","title"],Pp={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Ip={class:"flex items-start justify-between gap-4"},Mp={class:"mt-2 text-[11px] text-slate-500"},Op={key:0,class:"mt-1 text-[11px] text-slate-500"},Lp={key:1,class:"mt-1 text-[11px] text-slate-500"},$p=["aria-pressed","disabled"],Dp={key:0,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},Np={key:1,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},Fp={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Bp={class:"flex items-start justify-between gap-4"},Hp=["aria-pressed","title"],zp={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Up={class:"flex items-start justify-between gap-4"},jp=["aria-pressed","title"],Vp={__name:"SettingsTab",props:{autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},settings:{type:Object,default:null},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1}},emits:["toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e){const t=e,n=Ee(()=>{var s,r;return(s=t.ttsConfig)!=null&&s.enableVoiceChat?(r=t.ttsConfig)!=null&&r.pollyAvailable?"Available":"Unavailable":"Voice disabled on server"});return(s,r)=>{var i,o,a,l,f,u,d,g,y,E,x,M,m,H,Y;return F(),W("div",Ep,[r[10]||(r[10]=w("div",{class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4 text-slate-900"},[w("h3",{class:"text-sm font-semibold tracking-[0.01em]"},"Speech Settings"),w("p",{class:"mt-1 text-xs leading-relaxed text-slate-600"},"These controls apply only inside this chatbot box for the current browser session.")],-1)),w("div",Ap,[w("div",Rp,[r[4]||(r[4]=w("div",null,[w("p",{class:"text-sm font-semibold text-slate-900"},"Auto Read Replies"),w("p",{class:"mt-1 text-xs text-slate-600"},"Automatically read bot replies aloud.")],-1)),w("button",{class:we(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.autoReadEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.autoReadEnabled?"true":"false",title:e.autoReadEnabled?"Disable auto read":"Enable auto read",onClick:r[0]||(r[0]=$=>s.$emit("toggleAutoRead"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.autoReadEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,Cp)]),w("p",{class:we(["mt-3 text-[11px] font-medium",e.autoReadEnabled?"text-emerald-700":"text-slate-500"])},Je(e.autoReadEnabled?"Auto read is active.":"Auto read is currently off."),3)]),w("div",Pp,[w("div",Ip,[w("div",null,[r[5]||(r[5]=w("p",{class:"text-sm font-semibold text-slate-900"},"Use Amazon Polly",-1)),r[6]||(r[6]=w("p",{class:"mt-1 text-xs text-slate-600"},"Use Polly when available; otherwise browser speech is used automatically.",-1)),w("p",Mp,"Availability: "+Je(n.value),1),(i=e.settings)!=null&&i.aws_region?(F(),W("p",Op,"Region: "+Je(e.settings.aws_region),1)):qe("",!0),(o=e.ttsConfig)!=null&&o.voiceId?(F(),W("p",Lp,"Voice: "+Je(e.ttsConfig.voiceId),1)):qe("",!0)]),w("button",{class:we(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-55",(a=e.ttsConfig)!=null&&a.usePolly&&((l=e.ttsConfig)!=null&&l.enableVoiceChat)&&((f=e.ttsConfig)!=null&&f.pollyAvailable)?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":(u=e.ttsConfig)!=null&&u.usePolly&&((d=e.ttsConfig)!=null&&d.enableVoiceChat)&&((g=e.ttsConfig)!=null&&g.pollyAvailable)?"true":"false",disabled:!((y=e.ttsConfig)!=null&&y.pollyAvailable)||!((E=e.ttsConfig)!=null&&E.enableVoiceChat),onClick:r[1]||(r[1]=$=>s.$emit("togglePollyPreference"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",(x=e.ttsConfig)!=null&&x.usePolly&&((M=e.ttsConfig)!=null&&M.enableVoiceChat)&&((m=e.ttsConfig)!=null&&m.pollyAvailable)?"left-[1.45rem]":"left-0.5"])},null,2)],10,$p)]),(H=e.ttsConfig)!=null&&H.enableVoiceChat?(Y=e.ttsConfig)!=null&&Y.pollyAvailable?qe("",!0):(F(),W("p",Np,"Polly is not available for this site. Browser speech will be used.")):(F(),W("p",Dp,"Voice chat is disabled in ChangAI Settings."))]),w("div",Fp,[w("div",Bp,[w("div",null,[r[7]||(r[7]=w("p",{class:"text-sm font-semibold text-slate-900"},"Enable Debug Tab",-1)),r[8]||(r[8]=w("p",{class:"mt-1 text-xs text-slate-600"}," Show or hide the Debug tab inside this chatbot. ",-1)),w("p",{class:we(["mt-2 text-[11px] font-medium",e.debugEnabled?"text-emerald-700":"text-slate-500"])},Je(e.debugEnabled?"Debug tab is active.":"Debug tab is currently off."),3)]),w("button",{type:"button",class:we(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.debugEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.debugEnabled?"true":"false",title:e.debugEnabled?"Disable debug tab":"Enable debug tab",onClick:r[2]||(r[2]=$=>s.$emit("toggleDebug"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.debugEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,Hp)])]),w("div",zp,[w("div",Up,[r[9]||(r[9]=w("div",null,[w("p",{class:"text-sm font-semibold text-slate-900"},"Send non-ERP questions directly to AI"),w("p",{class:"mt-1 text-xs text-slate-600"},"Questions unrelated to your ERP will skip the system and go straight to AI")],-1)),w("button",{class:we(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.sendNonERPtoaiEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.sendNonERPtoaiEnabled?"true":"false",title:e.sendNonERPtoaiEnabled?"Non-ERP questions are being sent directly to AI":"Enable direct AI reply for non-ERP questions",onClick:r[3]||(r[3]=$=>s.$emit("toggleSendNonERP"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.sendNonERPtoaiEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,jp)]),w("p",{class:we(["mt-3 text-[11px] font-medium",e.sendNonERPtoaiEnabled?"text-emerald-700":"text-slate-500"])},Je(e.sendNonERPtoaiEnabled?"Non-ERP questions are now routed directly to AI":"Direct AI routing is currently off"),3)])])}}},qp={key:0,class:"pointer-events-none absolute -top-14 left-0 right-0 z-20 flex justify-center px-2",role:"status","aria-live":"polite"},Wp={__name:"StatusToast",props:{visible:{type:Boolean,required:!0},message:{type:String,default:""},type:{type:String,default:"info"},dismissible:{type:Boolean,default:!0}},emits:["close"],setup(e){const t=e,n=Ee(()=>t.type==="error"?"bg-red-50 text-red-700 ring-red-200":(t.type==="listening","bg-blue-50 text-blue-700 ring-blue-200")),s=Ee(()=>t.type==="error"?"bg-red-500":t.type==="listening"?"bg-blue-500 animate-pulse":"bg-blue-500");return(r,i)=>(F(),Et(Pu,{"enter-active-class":"transition duration-200 ease-out","enter-from-class":"translate-y-1 opacity-0","enter-to-class":"translate-y-0 opacity-100","leave-active-class":"transition duration-150 ease-in","leave-from-class":"translate-y-0 opacity-100","leave-to-class":"translate-y-1 opacity-0"},{default:Di(()=>[e.visible?(F(),W("div",qp,[w("div",{class:we(["pointer-events-auto flex max-w-[92%] items-start gap-2 rounded-lg px-3 py-2 text-xs shadow-lg ring-1",n.value])},[w("span",{class:we(["mt-0.5 h-2 w-2 shrink-0 rounded-full",s.value])},null,2),w("span",null,Je(e.message),1),e.dismissible?(F(),W("button",{key:0,type:"button",class:"ml-1 appearance-none border-0 text-current/80 transition hover:text-current focus:outline-none","aria-label":"Dismiss notification",onClick:i[0]||(i[0]=o=>r.$emit("close"))}," × ")):qe("",!0)],2)])):qe("",!0)]),_:1}))}},Gp={class:"relative w-full"},Kp=["placeholder","disabled"],Yp=["title","aria-label","disabled"],Zp={key:0,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},Xp={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},Qp={key:2,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true",class:"animate-spin"},Jp=["title","aria-label","disabled"],ed={key:0,viewBox:"0 0 24 24",width:"18",height:"18",fill:"none","aria-hidden":"true",class:"text-rose-600 motion-safe:animate-stop-button-pulse"},td={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},nd={__name:"ChatForm",props:{placeholder:{type:String,default:"Message..."},disabled:{type:Boolean,default:!1},isAwaitingResponse:{type:Boolean,default:!1}},emits:["submit","cancel"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=J(""),o=J(null),a=J(!1),l=J(!1),f=J(!1),u=J(!1),d=J(!1),g=J(!1),y=J(!1),E=J(""),x=J("info"),M=J("Voice input is unavailable in this browser/context.");let m=null,H=null,Y=null;const $=J(""),z=J(!1),O=Ee(()=>f.value?"Requesting microphone permission...":u.value?"Starting voice input...":d.value?"Stopping voice input...":l.value?a.value?"Stop voice input":"Start voice input":"Voice input is unavailable in this browser/context"),P=Ee(()=>s.isAwaitingResponse?"Stop response":"Send"),ee=Ee(()=>s.isAwaitingResponse?!1:s.disabled||!i.value.trim()),V=Ee(()=>s.isAwaitingResponse?"bg-white border border-rose-100 shadow-[0_8px_20px_-12px_rgba(159,18,57,0.35)] hover:bg-rose-50":"bg-linear-to-br from-brand-500 to-brand-600 text-white shadow-[0_10px_24px_-16px_rgba(109,79,194,0.85)] hover:from-brand-600 hover:to-violet-700");function se(){return typeof window=="undefined"?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}function fe(){var ae;const re=se(),B=typeof window!="undefined"?window.isSecureContext:!1,de=typeof navigator!="undefined"&&!!((ae=navigator.mediaDevices)!=null&&ae.getUserMedia);l.value=!!(re&&B&&de),B?(!de||!re)&&(M.value="Voice input is not supported in this browser."):M.value="Voice input requires HTTPS (or localhost).",re&&l.value&&(m=new re,m.continuous=!0,m.interimResults=!0,m.lang=typeof navigator!="undefined"&&navigator.language||"en-US",m.onstart=()=>{a.value=!0,u.value=!1,d.value=!1,D(),C("Listening... Tap mic to stop","listening",{persistent:!0,key:"listening"})},m.onend=()=>{a.value=!1,u.value=!1,d.value=!1,D(),$.value==="listening"&&pe(),z.value&&(z.value=!1,Ge())},m.onerror=ve=>{if(a.value=!1,u.value=!1,d.value=!1,D(),z.value=!1,(ve==null?void 0:ve.error)==="not-allowed"||(ve==null?void 0:ve.error)==="service-not-allowed"){C("Microphone permission denied. Please allow microphone access in browser settings.","error");return}if((ve==null?void 0:ve.error)==="audio-capture"){C("No microphone detected. Please connect a microphone and try again.","error");return}if((ve==null?void 0:ve.error)==="no-speech"){C("No speech detected. Try speaking a bit louder.","info");return}C("Voice input failed. Please try again.","error")},m.onresult=ve=>{let ge="";for(let nt=ve.resultIndex;nt{if(m&&!(!a.value&&!d.value))try{m.abort()}catch{d.value=!1,z.value=!1}},1200)}}function Se(){if(!l.value||!m){C(M.value,"error");return}if(a.value||u.value||d.value){Z({submitAfterStop:a.value});return}te()}async function Ue(){var re;if(g.value)return!0;if(!((re=navigator.mediaDevices)!=null&&re.getUserMedia))return C("Microphone API is unavailable in this browser.","error"),!1;f.value=!0,C("Requesting microphone permission...","info",{persistent:!0,key:"requesting"});try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(de=>de.stop()),g.value=!0,!0}catch(B){return(B==null?void 0:B.name)==="NotAllowedError"||(B==null?void 0:B.name)==="SecurityError"?C("Microphone permission denied. Please allow it and try again.","error"):(B==null?void 0:B.name)==="NotFoundError"?C("No microphone found on this device.","error"):C("Unable to access microphone. Please check browser permissions.","error"),!1}finally{f.value=!1,$.value==="requesting"&&pe()}}async function te(){var B;if(!(!m||a.value||u.value||d.value||!await Ue()||!m)){z.value=!1,(B=o.value)==null||B.focus(),u.value=!0;try{m.start()}catch(de){u.value=!1,d.value=!1,(de==null?void 0:de.name)!=="InvalidStateError"&&C("Unable to start voice input. Please try again.","error")}}}function C(re,B="info",de={}){const{duration:ae=4200,persistent:ve=!1,key:ge=""}=de;E.value=re,x.value=B,$.value=ge,y.value=!0,H&&clearTimeout(H),ve||(H=setTimeout(()=>{y.value=!1,$.value=""},ae))}function pe(){y.value=!1,$.value="",H&&(clearTimeout(H),H=null)}function Ge(){if(s.isAwaitingResponse){r("cancel");return}const re=i.value.trim();re&&((a.value||u.value||d.value)&&m&&Z({submitAfterStop:!1}),r("submit",re),i.value="")}return t({focus:()=>{var re;return(re=o.value)==null?void 0:re.focus()}}),zn(()=>{fe()}),ys(()=>{if(m&&(a.value||u.value||d.value)){z.value=!1,D();try{m.abort()}catch{}}D(),pe()}),(re,B)=>(F(),W("div",Gp,[w("form",{class:"group flex min-h-11 items-center gap-2 rounded-full border border-slate-200/90 bg-white/95 px-3 shadow-[0_12px_26px_-20px_rgba(15,23,42,0.7)] transition-all duration-250 focus-within:-translate-y-0.5 focus-within:border-brand-200 focus-within:shadow-[0_18px_30px_-20px_rgba(13,110,253,0.5)] focus-within:ring-2 focus-within:ring-brand-500/25",style:{"border-radius":"9999px"},autocomplete:"off",onSubmit:pt(Ge,["prevent"]),onClick:B[5]||(B[5]=pt(()=>{},["stop"])),onMousedown:B[6]||(B[6]=pt(()=>{},["stop"])),onKeydown:B[7]||(B[7]=pt(()=>{},["stop"])),onKeyup:B[8]||(B[8]=pt(()=>{},["stop"]))},[Pa(w("input",{ref_key:"inputRef",ref:o,type:"text","onUpdate:modelValue":B[0]||(B[0]=de=>i.value=de),class:"h-11 w-full border-none bg-transparent text-sm font-medium text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:e.disabled?"Waiting for response...":e.placeholder,disabled:e.disabled,required:"",onKeydown:B[1]||(B[1]=pt(()=>{},["stop"])),onKeyup:B[2]||(B[2]=pt(()=>{},["stop"])),onKeypress:B[3]||(B[3]=pt(()=>{},["stop"])),onInput:B[4]||(B[4]=pt(()=>{},["stop"]))},null,40,Kp),[[Xu,i.value]]),w("button",{type:"button",class:we(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border border-transparent text-slate-600 transition-all duration-200 hover:-translate-y-0.5 hover:border-slate-200 hover:bg-slate-100 hover:text-slate-900 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",a.value?"border-red-200 bg-red-100 text-red-600 shadow-[0_10px_20px_-18px_rgba(220,38,38,0.9)] hover:bg-red-100 hover:text-red-600":""]),style:{"border-radius":"9999px"},title:O.value,"aria-label":O.value,disabled:e.disabled||!l.value||f.value||u.value||d.value,onClick:Se},[a.value&&!f.value?(F(),W("svg",Zp,B[9]||(B[9]=[w("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"},null,-1)]))):f.value?(F(),W("svg",Qp,B[11]||(B[11]=[w("circle",{cx:"12",cy:"12",r:"9",opacity:"0.3"},null,-1),w("path",{d:"M21 12a9 9 0 0 1-9 9"},null,-1)]))):(F(),W("svg",Xp,B[10]||(B[10]=[w("path",{d:"M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"},null,-1),w("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"},null,-1),w("path",{d:"M12 19v3"},null,-1)])))],10,Yp),w("button",{type:"submit",title:P.value,"aria-label":P.value,class:we(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border-0 transition-all duration-200 hover:-translate-y-0.5 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",V.value]),style:{"border-radius":"9999px"},disabled:ee.value},[e.isAwaitingResponse?(F(),W("svg",ed,B[12]||(B[12]=[w("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor","stroke-width":"2.1",class:"opacity-95"},null,-1),w("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.35",fill:"currentColor"},null,-1)]))):(F(),W("svg",td,B[13]||(B[13]=[w("path",{d:"M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z"},null,-1)])))],10,Jp)],32),Oe(Wp,{visible:y.value,message:E.value,type:x.value,dismissible:x.value!=="listening",onClose:pe},null,8,["visible","message","type","dismissible"])]))}},sd={class:"relative overflow-hidden bg-linear-to-br from-brand-600 via-brand-500 to-violet-400"},rd={class:"min-w-0"},id={key:1,class:"border-t border-slate-200/80 bg-white/90 px-3 py-3 pb-[calc(12px+env(safe-area-inset-bottom))] backdrop-blur-sm sm:px-4 sm:py-4"},od=56,ld={__name:"ChatbotPopup",props:{isOpen:{type:Boolean,required:!0},activeTab:{type:String,required:!0},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1},chatHistory:{type:Array,required:!0},debugLogs:{type:Array,required:!0},currentDebug:{type:Object,default:null},supportHistory:{type:Array,required:!0},autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},activeTtsProvider:{type:String,required:!0},settings:{type:Object,default:null},isAwaitingChatResponse:{type:Boolean,default:!1},isAwaitingSupportResponse:{type:Boolean,default:!1}},emits:["close","submit","cancelResponse","update:activeTab","toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=J(null),o=J(null),a=J(s.activeTab),l=J("default"),f=J(!1),u=Ee(()=>a.value==="support"?s.isAwaitingSupportResponse:a.value==="chat"?s.isAwaitingChatResponse:!1);function d(){const M=i.value;if(!s.isOpen||!M){f.value=!1;return}const m=M.scrollHeight-M.clientHeight;if(m<=4){f.value=!1;return}const H=m-M.scrollTop;f.value=H>od}function g(){const M=i.value;M&&(M.scrollTo({top:M.scrollHeight,behavior:"smooth"}),setTimeout(()=>{d()},220))}function y(){St(()=>{d()})}function E(){if(l.value==="default"){l.value="half";return}if(l.value==="half"){l.value="full";return}l.value="default"}const x=Ee(()=>{const M="chat-shell fixed z-[9999] flex min-h-0 flex-col overflow-hidden border border-slate-200/80 shadow-[0_32px_80px_-44px_rgba(2,6,23,0.7),0_18px_40px_-24px_rgba(15,23,42,0.45)] transition-all duration-300 ease-out origin-bottom-right",m=s.isOpen?"pointer-events-auto opacity-100 translate-x-0 translate-y-0 scale-100 motion-safe:animate-surface-in":"pointer-events-none opacity-0 translate-x-1/5 translate-y-8 scale-95";return l.value==="full"?[M,m,"inset-0 h-screen w-screen max-h-screen max-w-screen rounded-none origin-center"]:l.value==="half"?[M,m,"bottom-[74px] right-5 h-[min(86vh,860px)] w-[min(50vw,860px)] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(86vh,760px)] max-[900px]:w-[min(70vw,760px)] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]:[M,m,"bottom-[74px] right-5 h-[min(560px,72vh)] w-[min(360px,calc(100vw-40px))] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(70vh,540px)] max-[900px]:w-[min(360px,calc(100vw-24px))] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]});return on(()=>s.activeTab,M=>{a.value=M,y()}),on(()=>s.isOpen,M=>{M&&a.value!=="settings"&&St(()=>{var m;return(m=o.value)==null?void 0:m.focus()}),y()}),on(a,M=>{r("update:activeTab",M),y()}),on(()=>[s.chatHistory.length,s.supportHistory.length,s.debugLogs.length,s.currentDebug],()=>{y()}),on(()=>s.debugEnabled,M=>{!M&&a.value==="debug"&&(a.value="chat"),y()}),zn(()=>{y()}),t({scrollToBottom(){St(()=>{g()})}}),(M,m)=>(F(),W("div",{class:we(x.value),onKeydown:m[9]||(m[9]=pt(()=>{},["stop"])),onKeyup:m[10]||(m[10]=pt(()=>{},["stop"])),onKeypress:m[11]||(m[11]=pt(()=>{},["stop"]))},[m[14]||(m[14]=w("div",{class:"pointer-events-none absolute -right-14 -top-14 h-36 w-36 rounded-full bg-brand-500/15 blur-2xl"},null,-1)),m[15]||(m[15]=w("div",{class:"pointer-events-none absolute -bottom-14 -left-12 h-32 w-32 rounded-full bg-violet-400/15 blur-2xl"},null,-1)),w("div",sd,[m[12]||(m[12]=w("div",{class:"pointer-events-none absolute inset-0 opacity-45",style:{background:"linear-gradient(120deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.02) 52%, rgba(255,255,255,0.12) 100%)"}},null,-1)),Oe(vc,{windowMode:l.value,autoReadEnabled:e.autoReadEnabled,activeTtsProvider:e.activeTtsProvider,onClose:m[0]||(m[0]=H=>M.$emit("close")),onCycleResize:E,onToggleAutoRead:m[1]||(m[1]=H=>M.$emit("toggleAutoRead"))},null,8,["windowMode","autoReadEnabled","activeTtsProvider"]),Oe(Sc,{modelValue:a.value,"onUpdate:modelValue":m[2]||(m[2]=H=>a.value=H),debugEnabled:e.debugEnabled},null,8,["modelValue","debugEnabled"])]),w("div",{class:"chat-scrollbar min-h-0 flex-1 overflow-x-hidden overflow-y-scroll bg-slate-50/60 px-4 py-4 max-[900px]:px-3.5 max-[900px]:py-3.5 max-[600px]:px-3 max-[600px]:py-3",ref_key:"chatBodyRef",ref:i,onScrollPassive:d},[w("div",rd,[a.value==="chat"?(F(),Et(mp,{key:0,messages:e.chatHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="debug"&&e.debugEnabled?(F(),Et(_p,{key:1,logs:e.debugLogs,currentDebug:e.currentDebug},null,8,["logs","currentDebug"])):a.value==="support"?(F(),Et(Sp,{key:2,messages:e.supportHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="settings"?(F(),Et(Vp,{key:3,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig,settings:e.settings,debugEnabled:e.debugEnabled,sendNonERPtoaiEnabled:e.sendNonERPtoaiEnabled,onToggleAutoRead:m[3]||(m[3]=H=>M.$emit("toggleAutoRead")),onTogglePollyPreference:m[4]||(m[4]=H=>M.$emit("togglePollyPreference")),onToggleDebug:m[5]||(m[5]=H=>M.$emit("toggleDebug")),onToggleSendNonERP:m[6]||(m[6]=H=>M.$emit("toggleSendNonERP"))},null,8,["autoReadEnabled","ttsConfig","settings","debugEnabled","sendNonERPtoaiEnabled"])):qe("",!0)])],544),f.value?(F(),W("button",{key:0,type:"button",class:we(["absolute right-4 z-20 grid h-9 w-9 place-items-center rounded-full border border-brand-200/70 bg-white/95 text-brand-600 shadow-[0_14px_26px_-16px_rgba(15,23,42,0.65)] transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-300 hover:text-brand-700 focus:outline-none",a.value!=="settings"?"bottom-[calc(90px+env(safe-area-inset-bottom))] sm:bottom-[96px]":"bottom-4 sm:bottom-5"]),title:"Scroll to bottom","aria-label":"Scroll to bottom",onClick:g},m[13]||(m[13]=[w("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},[w("path",{d:"M7 10l5 5 5-5"})],-1)]),2)):qe("",!0),a.value!=="settings"?(F(),W("div",id,[Oe(nd,{ref_key:"chatFormRef",ref:o,placeholder:a.value==="support"?"Message Support...":"Message...",disabled:u.value,isAwaitingResponse:u.value,onSubmit:m[7]||(m[7]=H=>M.$emit("submit",H)),onCancel:m[8]||(m[8]=H=>M.$emit("cancelResponse"))},null,8,["placeholder","disabled","isAwaitingResponse"])])):qe("",!0)],34))}},_l="changai_chat_id",Tl="changai_polly_enabled";function ad(){let e=sessionStorage.getItem(_l);return e||(e=`session_${Date.now()}_${crypto.randomUUID()}`,sessionStorage.setItem(_l,e)),e}function ud(){const e=localStorage.getItem(Tl);return e===null?!0:e==="true"}function cd(e){localStorage.setItem(Tl,String(!!e))}const fd={__name:"App",setup(e){const t=J(!1),n=J("chat"),s=J([]),r=J([]),i=J(!1),o=J([]),a=J(null),l=J("actual"),f=J(!0),u=J(null),d=J(!1),g=J(null),y=J(!1),E=J({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd",enable_changai:!1}),x=J("off"),M=J(null),m=J(null),H=Ee(()=>M.value!==null),Y=Ee(()=>m.value!==null);function $(){if(!E.value.enableVoiceChat){x.value="off";return}x.value=E.value.usePolly?"polly":"browser"}function z(te){var pe;const C=(pe=te==null?void 0:te.detail)==null?void 0:pe.provider;(C==="polly"||C==="browser"||C==="off")&&(x.value=C)}async function O(){var pe,Ge,re,B,de;if(!(d.value||u.value)){d.value=!0;try{u.value=await Mc(l.value),E.value={enableVoiceChat:!!((pe=u.value)!=null&&pe.enable_voice_chat),pollyAvailable:!!((Ge=u.value)!=null&&Ge.polly_enabled),usePolly:!!((re=u.value)!=null&&re.polly_enabled)&&ud(),voiceId:((B=u.value)==null?void 0:B.polly_voice_id)||"Zayd",enable_changai:!!((de=u.value)!=null&&de.enable_changai)},$(),r.value.push({type:"settings",settings:u.value})}catch(ae){const ve=vl(ae);r.value.push({type:"settings",error:ve})}finally{d.value=!1}}}function P(){t.value=!t.value}function ee(){var te;(te=a.value)==null||te.scrollToBottom()}function V(){f.value=!f.value}function se(){const te=!E.value.usePolly;E.value={...E.value,usePolly:te&&E.value.pollyAvailable},cd(E.value.usePolly),$()}function fe(){y.value=!y.value}async function D(te){n.value==="support"?await Ue(te):await Z(te)}async function Z(te){var ye,ht;g.value=null,l.value==="actual"&&await O(),s.value.push({role:"user",text:te}),await St(),ee();const C=cs({role:"model",text:"Thinking...",cancelable:!0,isStatus:!0,statusType:"thinking"});s.value.push(C),await St(),ee();let pe=!1;const Ge=ad(),re=`${Ge}_${Date.now()}`,B=y.value,de=Pc(te,Ge,l.value,re,y.value),ae=`debug_${re}`;let ve=Date.now();const ge=[],nt=G=>{var h;const Ce=Date.now(),Ft=((Ce-ve)/1e3).toFixed(2);ve=Ce;const c=`${G.message} (${Ft}s)`;if(G.message&&(ge.push(c),g.value=c),!G.done&&G.message&&(C.text=G.message,C.statusType="pipeline"),G.done){C.cancelable=!1,G.error?(C.text=`⚠️ ${G.message||"Something failed"}`,C.isStatus=!1,C.statusType=null):(h=G.data)!=null&&h.answer&&(C.text=G.data.answer,C.isStatus=!1,C.statusType=null),frappe.realtime.off(ae),g.value=null;return}};frappe.realtime.on(ae,nt),M.value=()=>{pe||(pe=!0,de.cancel(),frappe.realtime.off(ae),C.isStatus=!1,C.statusType=null,C.text="Cancelled by user.",r.value.push({type:"cancelled",user:te,steps:[...ge]}),g.value=null,C.cancelable=!1,M.value=null)};try{const G=await de.promise;if(G!=null&&G.open_report){if(C.isStatus=!1,C.statusType=null,C.text=`Opening "${G.report_name}" report." `,r.value.push({type:"success",steps:[...ge],final_response:G,entity_raw:G.entity_raw}),g.value=null,!G.report_name){C.text="Report name extraction failed.Can you ask the same question again?";return}frappe.set_route("query-report",G.report_name,G.filters||{});return}else if(G!=null&&G.create_entity){C.isStatus=!1,C.statusType=null,C.cancelable=!1,C.text=`Opening "${G.doc}" doctype for creating Entity "${G.entity_name}" record.`,r.value.push({type:"success",user:te,steps:[...ge],final_response:G}),g.value=null;const Ft=G.doc,c=G.entity_name||"",b={Customer:{customer_name:c},Supplier:{supplier_name:c},Employee:{employee_name:c},Item:{item_code:c,item_name:c},Project:{project_name:c},Lead:{lead_name:c},Opportunity:{opportunity_name:c}}[Ft]||{};frappe.route_options=b,frappe.set_route("Form",Ft,"new");const k=setInterval(()=>{cur_frm&&cur_frm.doctype===Ft&&cur_frm.is_new()&&(clearInterval(k),Object.entries(b).forEach(([v,_])=>{_&&cur_frm.fields_dict[v]&&(cur_frm.set_value(v,_),cur_frm.refresh_field(v))}))},200);return}if(pe)return;C.cancelable=!1;const Ce=((ye=bp(G==null?void 0:G.Bot))==null?void 0:ye.trim())||"No response.";C.isStatus=!1,C.statusType=null,C.text=Ce,r.value.push({type:"success",user:te,steps:[...ge],final_response:G}),g.value=null}catch(G){if(pe)return;frappe.realtime.off(ae),C.cancelable=!1,C.isStatus=!1,C.statusType=null;const Ce=vl(G);g.value=null,r.value.push({type:"failed",user:te,steps:[...ge],error:Ce}),(G==null?void 0:G.code)==="ERR_NETWORK_CHANGED"||(ht=G==null?void 0:G.message)!=null&&ht.includes("ERR_NETWORK_CHANGED")?(C.isStatus=!1,C.statusType=null,C.text="⚠️ Network error. Please check your connection and try again."):(C.isStatus=!1,C.statusType=null,C.text="⚠️ Something went wrong. Please try again.")}finally{frappe.realtime.off(ae),pe||(M.value=null)}await St(),ee()}function Se(){var te,C;if(n.value==="support"){(te=m.value)==null||te.call(m);return}(C=M.value)==null||C.call(M)}async function Ue(te){o.value.push({role:"user",text:te}),await St(),ee();const C=cs({role:"model",text:"Sending to support...",isStatus:!0,statusType:"support"});o.value.push(C),await St(),ee();let pe=!1;const Ge=Ic(te,l.value);m.value=()=>{pe||(pe=!0,Ge.cancel(),C.isStatus=!1,C.statusType=null,C.text="Cancelled by user.",m.value=null)};try{const re=await Ge.promise;if(pe)return;C.isStatus=!1,C.statusType=null,C.text=re?wl(re):"Support request sent successfully."}catch{if(pe)return;C.isStatus=!1,C.statusType=null,C.text="⚠️ Failed to reach support. Please try again."}finally{pe||(m.value=null)}await St(),ee()}return zn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-provider",z),l.value==="actual"&&O()}),ys(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-provider",z)}),(te,C)=>(F(),W(He,null,[E.value.enable_changai?(F(),Et(ac,{key:0,isOpen:t.value,onToggle:P},null,8,["isOpen"])):qe("",!0),Oe(ld,{ref_key:"popupRef",ref:a,isOpen:t.value,activeTab:n.value,"onUpdate:activeTab":C[0]||(C[0]=pe=>n.value=pe),chatHistory:s.value,debugLogs:r.value,currentDebug:g.value,supportHistory:o.value,autoReadEnabled:f.value,ttsConfig:E.value,activeTtsProvider:x.value,settings:u.value,isAwaitingChatResponse:H.value,isAwaitingSupportResponse:Y.value,debugEnabled:i.value,sendNonERPtoaiEnabled:y.value,onToggleDebug:C[1]||(C[1]=pe=>i.value=!i.value),onClose:C[2]||(C[2]=pe=>t.value=!1),onSubmit:D,onCancelResponse:Se,onToggleAutoRead:V,onTogglePollyPreference:se,onToggleSendNonERP:fe},null,8,["isOpen","activeTab","chatHistory","debugLogs","currentDebug","supportHistory","autoReadEnabled","ttsConfig","activeTtsProvider","settings","isAwaitingChatResponse","isAwaitingSupportResponse","debugEnabled","sendNonERPtoaiEnabled"])],64))}};function pd(){const e=document.querySelector('link[href*="/assets/changai/dist/changai-chatbot.css"]');if(e!=null&&e.href)return e.href;const t=Array.from(document.scripts).find(n=>{var s;return(s=n.src)==null?void 0:s.includes("/assets/changai/dist/changai-chatbot.js")});return t!=null&&t.src?t.src.replace(/changai-chatbot\.js(\?.*)?$/,"changai-chatbot.css$1"):null}function dd(e){const t=pd();if(!t){const n=Array.from(document.querySelectorAll("style[data-vite-dev-id]"));return n.length&&n.forEach(s=>{const r=document.createElement("style");r.dataset.changaiShadowDevStyle="1",r.textContent=s.textContent||"",e.appendChild(r)}),Promise.resolve()}return e.querySelector('link[data-changai-shadow-style="1"]')?Promise.resolve():new Promise(n=>{const s=document.createElement("link");s.rel="stylesheet",s.href=t,s.dataset.changaiShadowStyle="1",s.onload=()=>n(),s.onerror=()=>n(),e.appendChild(s),setTimeout(n,1200)})}async function kl(){if(document.getElementById("changai-chatbot-host"))return;const e=document.createElement("div");e.id="changai-chatbot-host",document.body.appendChild(e);const t=e.attachShadow({mode:"open"});await dd(t);const n=document.createElement("div");n.id="changai-chatbot-root",t.appendChild(n),nc(fd).mount(n);function s(r){r.stopPropagation()}n.addEventListener("keydown",s),n.addEventListener("keyup",s),n.addEventListener("keypress",s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",kl):kl()})(); diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 945d499..03162eb 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -2,7 +2,7 @@ import { ref, reactive, computed, nextTick, onMounted, onBeforeUnmount } from 'vue' import ChatbotToggler from './components/ChatbotToggler.vue' import ChatbotPopup from './components/ChatbotPopup.vue' -import { starupCall, runPipelineCancelable, callSupportBot, getSettingsDetails } from './utils/frappe.js' +import { runPipelineCancelable, callSupportBotCancelable, getSettingsDetails } from './utils/frappe.js' import { getOrCreateChatId, getPollyPreference, setPollyPreference } from './utils/session.js' import { normalizeBotText, getErrorText, safeStringify } from './utils/helpers.js' const showChatbot = ref(false) @@ -27,7 +27,9 @@ const ttsConfig = ref({ }) const activeTtsProvider = ref('off') const cancelPendingChatRequest = ref(null) +const cancelPendingSupportRequest = ref(null) const isAwaitingChatResponse = computed(() => cancelPendingChatRequest.value !== null) +const isAwaitingSupportResponse = computed(() => cancelPendingSupportRequest.value !== null) function updateProviderFromSettings() { if (!ttsConfig.value.enableVoiceChat) { @@ -126,8 +128,9 @@ async function handleChatSubmit(message) { const requestId = `${chatId}_${Date.now()}` const sendNonErptoAI = sendNonERPtoaiEnabled.value console.log('sendNonErptoAI value being sent:', sendNonErptoAI, typeof sendNonErptoAI) - const request = runPipelineCancelable(message,chatId, responseMode.value,requestId,sendNonERPtoaiEnabled.value) const eventName = `debug_${requestId}` + frappe.realtime.on(eventName, onPipelineUpdate) + const request = runPipelineCancelable(message,chatId, responseMode.value,requestId,sendNonERPtoaiEnabled.value) let lastStepTime = Date.now() const steps = [] const onPipelineUpdate = (msg) => { @@ -135,10 +138,12 @@ async function handleChatSubmit(message) { const seconds = ((now - lastStepTime) / 1000).toFixed(2) lastStepTime = now console.log('REALTIME STEP', msg) - const step = `${msg.message} (${seconds}s)` if (msg.message) { + const step = `${msg.message} (${seconds}s)` steps.push(step) currentDebug.value = step + thinkingMsg.text = msg.message + thinkingMsg.statusType = 'pipeline' } if (!msg.done && msg.message) { @@ -158,18 +163,17 @@ if (msg.done) { thinkingMsg.statusType = null } - frappe.realtime.off(eventName) + frappe.realtime.off(eventName, onPipelineUpdate) currentDebug.value = null return } } - frappe.realtime.on(eventName, onPipelineUpdate) cancelPendingChatRequest.value = () => { if (cancelled) return cancelled = true request.cancel() - frappe.realtime.off(eventName) + frappe.realtime.off(eventName, onPipelineUpdate) thinkingMsg.isStatus = false thinkingMsg.statusType = null thinkingMsg.text = 'Cancelled by user.' @@ -182,8 +186,108 @@ if (msg.done) { thinkingMsg.cancelable = false cancelPendingChatRequest.value = null } - try { - const response = await request.promise +try { + const response = await request.promise + if (response?.open_report) + { + thinkingMsg.isStatus = false + thinkingMsg.statusType = null + thinkingMsg.text = `Opening "${response.report_name}" report." ` + debugLogs.value.push({ + type: 'success', + steps: [...steps], + final_response: response, + entity_raw: response.entity_raw + }) + currentDebug.value = null + if (!response.report_name) { + thinkingMsg.text = `Report name extraction failed.Can you ask the same question again?` + return + } + frappe.set_route('query-report', response.report_name, response.filters || {}) + return + } +else if (response?.create_entity) { + thinkingMsg.isStatus = false + thinkingMsg.statusType = null + thinkingMsg.cancelable = false + thinkingMsg.text = `Opening "${response.doc}" doctype for creating Entity "${response.entity_name}" record.` + + debugLogs.value.push({ + type: 'success', + user: message, + steps: [...steps], + final_response: response, + }) + + currentDebug.value = null + + const doctype = response.doc + const entityName = response.entity_name || "" + + const defaultMap = { + Customer: { + customer_name: entityName + }, + Supplier: { + supplier_name: entityName + }, + Employee: { + employee_name: entityName + }, + Item: { + item_code: entityName, + item_name: entityName + }, + Project: { + project_name: entityName + }, + Lead: { + lead_name: entityName + }, + Opportunity: { + opportunity_name: entityName + } + } + + const defaults = defaultMap[doctype] || {} + + frappe.route_options = defaults + + frappe.set_route("Form", doctype, "new") + + const timer = setInterval(() => { + if (cur_frm && cur_frm.doctype === doctype && cur_frm.is_new()) { + clearInterval(timer) + + Object.entries(defaults).forEach(([field, value]) => { + if (value && cur_frm.fields_dict[field]) { + cur_frm.set_value(field, value) + cur_frm.refresh_field(field) + } + }) + } + }, 200) + + return +} +if (response?.stop_followup) { + thinkingMsg.isStatus = false + thinkingMsg.statusType = null + thinkingMsg.cancelable = false + thinkingMsg.text = response.message || 'You’re welcome!' + + debugLogs.value.push({ + type: 'stop_followup', + user: message, + steps: [...steps], + final_response: response, + }) + + currentDebug.value = null + return +} + if (cancelled) return thinkingMsg.cancelable = false const finalBotText = normalizeBotText(response?.Bot)?.trim() || 'No response.' @@ -199,7 +303,7 @@ if (msg.done) { currentDebug.value = null } catch (err) { if (cancelled) return - frappe.realtime.off(eventName) + frappe.realtime.off(eventName, onPipelineUpdate) thinkingMsg.cancelable = false thinkingMsg.isStatus = false thinkingMsg.statusType = null @@ -212,17 +316,19 @@ if (msg.done) { error: errorText, }) console.error('ChangAI API Error:', err) - if (error === "ERR_NETWORK_CHANGED"){ + if (err?.code === "ERR_NETWORK_CHANGED" || err?.message?.includes("ERR_NETWORK_CHANGED")){ thinkingMsg.isStatus = false thinkingMsg.statusType = null thinkingMsg.text = '⚠️ Network error. Please check your connection and try again.' } + else{ thinkingMsg.isStatus = false thinkingMsg.statusType = null thinkingMsg.text = '⚠️ Something went wrong. Please try again.' + } } finally { - frappe.realtime.off(eventName) + frappe.realtime.off(eventName, onPipelineUpdate) if (!cancelled) { cancelPendingChatRequest.value = null } @@ -232,6 +338,11 @@ if (msg.done) { } function handleCancelResponse() { + if (activeTab.value === 'support') { + cancelPendingSupportRequest.value?.() + return + } + cancelPendingChatRequest.value?.() } @@ -245,12 +356,35 @@ async function handleSupportSubmit(message) { await nextTick() scrollToBottom() + let cancelled = false + const request = callSupportBotCancelable(message, responseMode.value) + + cancelPendingSupportRequest.value = () => { + if (cancelled) return + cancelled = true + request.cancel() + thinkingMsg.isStatus = false + thinkingMsg.statusType = null + thinkingMsg.text = 'Cancelled by user.' + cancelPendingSupportRequest.value = null + } + try { - const response = await callSupportBot(message, responseMode.value) + const response = await request.promise + if (cancelled) return + thinkingMsg.isStatus = false + thinkingMsg.statusType = null thinkingMsg.text = response ? safeStringify(response) : 'Support request sent successfully.' } catch (err) { + if (cancelled) return console.error('Support API Error:', err) + thinkingMsg.isStatus = false + thinkingMsg.statusType = null thinkingMsg.text = '⚠️ Failed to reach support. Please try again.' + } finally { + if (!cancelled) { + cancelPendingSupportRequest.value = null + } } await nextTick() @@ -288,7 +422,8 @@ onBeforeUnmount(() => { :ttsConfig="ttsConfig" :activeTtsProvider="activeTtsProvider" :settings="settings" - :isAwaitingResponse="isAwaitingChatResponse" + :isAwaitingChatResponse="isAwaitingChatResponse" + :isAwaitingSupportResponse="isAwaitingSupportResponse" :debugEnabled="debugEnabled" :sendNonERPtoaiEnabled="sendNonERPtoaiEnabled" @toggleDebug="debugEnabled = !debugEnabled" diff --git a/frontend/src/components/ChatbotPopup.vue b/frontend/src/components/ChatbotPopup.vue index fa7cbe3..bddb955 100644 --- a/frontend/src/components/ChatbotPopup.vue +++ b/frontend/src/components/ChatbotPopup.vue @@ -64,8 +64,8 @@ @@ -99,7 +99,8 @@ const props = defineProps({ ttsConfig: { type: Object, required: true }, activeTtsProvider: { type: String, required: true }, settings: { type: Object, default: null }, - isAwaitingResponse: { type: Boolean, default: false }, + isAwaitingChatResponse: { type: Boolean, default: false }, + isAwaitingSupportResponse: { type: Boolean, default: false }, }) const emit = defineEmits(['close', 'submit', 'cancelResponse', 'update:activeTab', 'toggleAutoRead', 'togglePollyPreference', 'toggleDebug','toggleSendNonERP']) @@ -110,6 +111,12 @@ const localTab = ref(props.activeTab) const windowMode = ref('default') const showScrollButton = ref(false) +const isAwaitingCurrentTabResponse = computed(() => { + if (localTab.value === 'support') return props.isAwaitingSupportResponse + if (localTab.value === 'chat') return props.isAwaitingChatResponse + return false +}) + const SCROLL_BUTTON_THRESHOLD = 56 function updateScrollButtonVisibility() { diff --git a/frontend/src/utils/frappe.js b/frontend/src/utils/frappe.js index 1fd57fd..8c39f10 100644 --- a/frontend/src/utils/frappe.js +++ b/frontend/src/utils/frappe.js @@ -97,6 +97,50 @@ export function runPipelineCancelable(userQuestion, chatId, mode = 'actual', req return { promise, cancel } } +export function callSupportBotCancelable(message, mode = 'actual') { + if (mode === 'test') { + return { + promise: Promise.resolve(`[TEST MODE] ${JSON.stringify({ message })}`), + cancel: () => false, + } + } + + if (!window.frappe || !window.frappe.call) { + return { + promise: Promise.reject(new Error('Frappe API is unavailable in actual mode.')), + cancel: () => false, + } + } + + let requestHandle = null + let settled = false + + const promise = new Promise((resolve, reject) => { + requestHandle = window.frappe.call({ + method: API.SUPPORT, + args: { message }, + callback(r) { + settled = true + resolve(r.message) + }, + error(err) { + settled = true + reject(err) + }, + }) + }) + + const cancel = () => { + if (settled) return false + if (!requestHandle || typeof requestHandle.abort !== 'function') return false + requestHandle.abort() + settled = true + return true + } + + return { promise, cancel } +} + export function callSupportBot(message, mode = 'actual') { return frappeCall(API.SUPPORT, { message }, mode) }