@tacoreai/web-sdk 1.0.12 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/utils/index.js ADDED
@@ -0,0 +1,114 @@
1
+ export * from "./errorLogger.js";
2
+
3
+ const globalOptions = {
4
+ // 数据库 client 默认配置
5
+ clientDefaultConfig: {},
6
+ };
7
+
8
+ export function setGlobalOptions(newOptions) {
9
+ Object.assign(globalOptions, newOptions);
10
+ }
11
+
12
+ export function getGlobalOptions() {
13
+ return { ...globalOptions };
14
+ }
15
+
16
+ // 新增:环境判断
17
+ export const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
18
+ // 后端环境 (Node.js) 为 'backend', 浏览器环境根据全局变量判断,默认为 'development'
19
+ export const env = isBrowser ? (window.__TACORE_APP_ENV__ || 'development') : 'backend';
20
+
21
+ export const isDevelopmentBrowser = env === 'development';
22
+ export const isProductionBrowser = env === 'production';
23
+ export const isBackend = !isBrowser;
24
+
25
+ export function getRouterBasename() {
26
+ if (isBackend) {
27
+ // 在后端环境中,basename 的概念不适用
28
+ return "";
29
+ }
30
+ const { host, pathname } = window.location;
31
+
32
+ // 修改:支持 apps.tacore.ai 和 apps-test.tacore.ai
33
+ if (host === "apps.tacore.ai" || host === "apps-test.tacore.ai") {
34
+ const match = pathname.match(/^\/([^/]+)/);
35
+ const appId = match?.[1];
36
+ return `/${appId}`;
37
+ }
38
+ const match = pathname.match(/^\/app-run\/([^/]+)/);
39
+ const appId = match?.[1];
40
+ // stone 珍贵的 手动注释:主要是本地开发环境和集成环境的预览,这些环境返回 /app-run/$appId 路径
41
+ if (appId) {
42
+ return `/app-run/${appId}`;
43
+ }
44
+ // stone 珍贵的 手动注释:不可以是/,这样就和上面的情况不一致了(上面的情况末尾不是斜杠),会导致拼接路径错误,拼接后出现连续两个斜杠
45
+ // 考虑到独立部署的应用,还不多,改这种场景的返回值
46
+ return "";
47
+ }
48
+
49
+ export function getAppsApiBaseUrl() {
50
+ // 后端环境逻辑
51
+ if (isBackend) {
52
+ // stone 手动: tacore server 内网地址
53
+ const baseUrl = process.env.TACORE_SERVER_INTRANET_BASE_URL;
54
+ if (!baseUrl) {
55
+ throw new Error("TACORE_SERVER_INTRANET_BASE_URL environment variable is not set in the backend environment.");
56
+ }
57
+ return baseUrl;
58
+ }
59
+
60
+ const { host } = window.location;
61
+ if (host.includes("localhost:5174")) {
62
+ return "/api";
63
+ }
64
+ if (host === "test.tacore.ai") {
65
+ return "//api-test.tacore.chat";
66
+ }
67
+ return `//api.tacore.chat`;
68
+ }
69
+
70
+ /**
71
+ * AI 响应后处理器,用于清理和规范化原始 AI 响应。
72
+ * @param {string} rawContent - 原始 AI 响应字符串。
73
+ * @returns {string} - 清理后的字符串。
74
+ */
75
+ export function _postProcessAIResponse(rawContent) {
76
+ if (typeof rawContent !== "string" || !rawContent) {
77
+ return ""
78
+ }
79
+
80
+ let processedContent = rawContent
81
+
82
+ // 移除 <agi-thinking> 块
83
+ const thinkingRegex = /<agi-thinking>[\s\S]*?<\/agi-thinking>/g
84
+ processedContent = processedContent.replace(thinkingRegex, "")
85
+
86
+ // 反转义 HTML 实体
87
+ processedContent = processedContent.replace(/&lt;/g, "<")
88
+ processedContent = processedContent.replace(/&gt;/g, ">")
89
+ processedContent = processedContent.replace(/&amp;/g, "&")
90
+ processedContent = processedContent.replace(/&quot;/g, '"')
91
+ processedContent = processedContent.replace(/&apos;/g, "'")
92
+
93
+ // 移除 CDATA 标签
94
+ processedContent = processedContent.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
95
+
96
+ // 修复标签拼写错误
97
+ processedContent = processedContent.replace(/<agi-gode/g, "<AGI-CODE".toLocaleLowerCase())
98
+ processedContent = processedContent.replace(/<\/agi-gode>/g, "</AGI-CODE>".toLocaleLowerCase())
99
+ processedContent = processedContent.replace(/<agi--code/g, "<AGI-CODE".toLocaleLowerCase())
100
+ processedContent = processedContent.replace(/<\/agi--code>/g, "</AGI-CODE>".toLocaleLowerCase())
101
+ processedContent = processedContent.replace(/<agi-gcode/g, "<AGI-CODE".toLocaleLowerCase())
102
+ processedContent = processedContent.replace(/<\/agi-gcode>/g, "</AGI-CODE>".toLocaleLowerCase())
103
+
104
+ // 移除 CSS import 语句
105
+ processedContent = processedContent.replace(/^\s*import\s+['"][^'"]+\.css['"];?\s*$/gm, "")
106
+
107
+ // 移除 Markdown 代码块围栏
108
+ processedContent = processedContent.replace(/^```.*$/gm, "")
109
+
110
+ // 清理多余的换行符
111
+ processedContent = processedContent.replace(/\n{3,}/g, "\n\n").trim()
112
+
113
+ return processedContent
114
+ }
package/dist/index.umd.js DELETED
@@ -1 +0,0 @@
1
- (function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@cloudbase/js-sdk")):typeof define=="function"&&define.amd?define("@tacoreai/web-sdk",["exports","@cloudbase/js-sdk"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l.TacoreAIWebSDK={},l.cloudbase))})(this,function(l,h){"use strict";function v(){const{hostname:c,pathname:t}=window.location;if(["localhost","127.0.0.1","tacoreai.com","tacore.ai"].includes(c)){const e=t.match(/^\/app-run\/([^/]+)/);return`/app-run/${e==null?void 0:e[1]}`}return"/"}const $=Object.freeze(Object.defineProperty({__proto__:null,getRouterBasename:v},Symbol.toStringTag,{value:"Module"}));class p{constructor(t={}){this._db=null,this._collection=null,this._cloudBaseApp=null,this._cloudBaseAuth=null,this.config={env:t.env||"mobenai-weapp-dev-2e8qhi3a963364",persistence:t.persistence||"local",collectionName:t.collectionName||"platform-metadata",...t}}ensureInitialized(){this._cloudBaseApp||(this._cloudBaseApp=h.init({env:this.config.env})),this._cloudBaseAuth||(this._cloudBaseAuth=this._cloudBaseApp.auth({persistence:this.config.persistence})),this._db||(this._db=this._cloudBaseApp.database(),this._collection=this._db.collection(this.config.collectionName))}get db(){return this.ensureInitialized(),this._db}get collection(){return this.ensureInitialized(),this._collection}get cloudBaseApp(){return this.ensureInitialized(),this._cloudBaseApp}get cloudBaseAuth(){return this.ensureInitialized(),this._cloudBaseAuth}getRawDB(){return this.ensureInitialized(),this._db}getRawCollection(){return this.ensureInitialized(),this._collection}isConnected(){return this._db!==null&&this._cloudBaseApp!==null}reset(){this._db=null,this._collection=null,this._cloudBaseApp=null,this._cloudBaseAuth=null}async getCurrentUserId(){var t;try{this.ensureInitialized();const e=await this._cloudBaseAuth.getLoginState();return((t=e==null?void 0:e.user)==null?void 0:t.uid)||null}catch(e){return console.error("Failed to get current user ID:",e),null}}async getAccessToken(){try{return this.ensureInitialized(),(await this._cloudBaseAuth.getAccessToken()).accessToken}catch(t){return console.error("Failed to get access token:",t),null}}updateConfig(t){this.config={...this.config,...t},(t.env||t.collectionName)&&this.reset()}getConfig(){return{...this.config}}}class m{constructor(){this.throttleTimeout=300}generateRequestKey(t,e){const r=JSON.stringify(e,Object.keys(e).sort());return`${t}:${r}`}async withThrottle(t,e,r){return await r()}clearPendingRequests(){console.log("All throttled requests cleared")}getPendingRequestCount(){return 0}setThrottleTimeout(t){t>0&&(this.throttleTimeout=t,console.log(`Throttle timeout updated to ${t}ms`))}clearRequestCache(t,e){console.log(`Request cache cleared for: ${t}`)}getCacheStatus(){return{throttledFunctionsCount:0,cachedResultsCount:0,throttleTimeout:this.throttleTimeout}}async forceExecute(t,e,r){return console.log(`Force executing request: ${t}`),await r()}}class b{constructor(t){this.connection=t}validateWyIDFormat(t){return!t||typeof t!="string"?!1:/^[a-z_]+_\d+_[a-z0-9]+$|^[a-zA-Z0-9\-_]+$/.test(t)}async checkWyIDExists(t){try{return this.connection.ensureInitialized(),(await this.connection.collection.where({wyID:t,isDeleted:!1}).limit(1).get()).data.length>0}catch(e){throw console.error("Failed to check wyID existence:",e),new Error(`Failed to check wyID existence: ${e}`)}}async getExistingDocumentInfo(t){try{this.connection.ensureInitialized();const e=await this.connection.collection.where({wyID:t,isDeleted:!1}).field({wyID:!0,model:!0,createdAt:!0,createdBy:!0}).limit(1).get();return e.data.length>0?e.data[0]:null}catch(e){return console.error("Failed to get existing document info:",e),null}}async validateWyIDUniqueness(t){if(!this.validateWyIDFormat(t))throw new Error(`Invalid wyID format: ${t}. Expected format: prefix_timestamp_random or valid authUserId`);if(await this.checkWyIDExists(t)){const r=await this.getExistingDocumentInfo(t),n=r?` (existing: ${r.model}, created: ${r.createdAt})`:"";throw new Error(`DUPLICATE_WYID: Document with wyID '${t}' already exists${n}`)}}async validateBatchWyIDUniqueness(t){const e=t.filter((o,i)=>t.indexOf(o)!==i);if(e.length>0)throw new Error(`BATCH_DUPLICATE_WYID: Duplicate wyIDs in batch: ${e.join(", ")}`);for(const o of t){if(!o)throw new Error("VALIDATION_ERROR: Document wyID is required");if(!this.validateWyIDFormat(o))throw new Error(`VALIDATION_ERROR: Invalid wyID format: ${o}`)}const n=(await Promise.all(t.map(async o=>{const i=await this.checkWyIDExists(o);return{wyID:o,exists:i}}))).filter(o=>o.exists).map(o=>o.wyID);if(n.length>0)throw new Error(`BATCH_DUPLICATE_WYID: Documents with wyIDs already exist: ${n.join(", ")}`)}async getWyIDStats(){try{this.connection.ensureInitialized();const t=await this.connection.collection.field({wyID:!0,model:!0,isDeleted:!0}).get(),e={total:t.data.length,active:t.data.filter(r=>!r.isDeleted).length,deleted:t.data.filter(r=>r.isDeleted).length,byModel:{}};return t.data.forEach(r=>{e.byModel[r.model]||(e.byModel[r.model]={total:0,active:0,deleted:0}),e.byModel[r.model].total++,r.isDeleted?e.byModel[r.model].deleted++:e.byModel[r.model].active++}),e}catch(t){throw console.error("Failed to get wyID stats:",t),new Error(`Failed to get wyID stats: ${t}`)}}}class I{constructor(){}buildWhereCondition(t){const e={};return Object.keys(t).forEach(r=>{["limit","skip","orderBy"].includes(r)||(e[r]=t[r])}),e}buildBaseWhereCondition(t,e={}){return{model:t,isDeleted:!1,...this.buildWhereCondition(e)}}buildListQueryFields(t=[]){const e={wyID:!0,model:!0,createdAt:!0,updatedAt:!0,version:!0,organizationId:!0};return t.forEach(r=>{e[`data.${r}`]=!0}),e}buildDetailQueryFields(){return{wyID:!0,model:!0,data:!0,createdAt:!0,updatedAt:!0,createdBy:!0,updatedBy:!0,organizationId:!0,isDeleted:!0,version:!0}}applyFieldSelection(t,e){return e.fields?t.field(e.fields):e.includeData?t:t.field(this.buildListQueryFields())}applyPagination(t,e){let r=t;return e.limit&&(r=r.limit(e.limit)),e.skip&&(r=r.skip(e.skip)),r}applySorting(t,e){return e.orderBy?t.orderBy(e.orderBy.field,e.orderBy.direction):t}buildQuery(t,e,r={},n={}){const o=this.buildBaseWhereCondition(e,r);let i=t.where(o);return i=this.applyPagination(i,r),i=this.applySorting(i,r),i=this.applyFieldSelection(i,n),i}buildSearchQuery(t,e,r,n={}){let o=t.where({model:e,isDeleted:!1,searchText:new RegExp(r,"i")});return o=this.applyPagination(o,n),n.fields?o=o.field(n.fields):o=o.field({wyID:!0,model:!0,createdAt:!0,updatedAt:!0}),o}buildCountQuery(t,e,r={}){const n=this.buildBaseWhereCondition(e,r);return t.where(n)}buildBatchQuery(t,e,r,n,o={}){let i=t.where({model:r,wyID:e.command.in(n),isDeleted:!1});return i=this.applyFieldSelection(i,o),i}calculatePaginationInfo(t,e){const r=e.limit||20,n=e.skip||0,o=Math.floor(n/r)+1;return{total:t,page:o,pageSize:r,totalPages:Math.ceil(t/r),hasNext:n+r<t,hasPrev:n>0}}}class y{static buildBaseDocument(t,e,r,n,o=null,i=null){const a=new Date().toISOString();return{wyID:t,model:e,data:r,createdBy:n,updatedBy:n,createdAt:a,updatedAt:a,isDeleted:!1,version:1,organizationId:o}}static buildUpdateDocument(t,e,r=null){const n=new Date().toISOString(),o={...t,updatedBy:e,updatedAt:n};return r&&r.db&&r.db.command&&(o.version=r.db.command.inc(1)),o}static buildSoftDeleteDocument(t,e=null){const r=new Date().toISOString(),n={isDeleted:!0,deletedAt:r,deletedBy:t,updatedBy:t,updatedAt:r};return e&&e.db&&e.db.command&&(n.version=e.db.command.inc(1)),n}static validateDocument(t){const e=[];return t.wyID||e.push("wyID is required"),t.model||e.push("model is required"),t.data||e.push("data is required"),t.createdBy||e.push("createdBy is required"),typeof t.data!="object"&&e.push("data must be an object"),typeof t.version!="number"&&e.push("version must be a number"),typeof t.isDeleted!="boolean"&&e.push("isDeleted must be a boolean"),e}static cleanDocument(t){const e={...t};return Object.keys(e).forEach(r=>{(e[r]===void 0||e[r]===null)&&delete e[r]}),e}static mergeUpdates(t,e){const r={...t};return Object.keys(e).forEach(n=>{if(n.includes(".")){const[o,i]=n.split(".");r[o]||(r[o]={}),r[o][i]=e[n]}else r[n]=e[n]}),r}static extractFieldValue(t,e){const r=e.split(".");let n=t;for(const o of r)if(n&&typeof n=="object")n=n[o];else return;return n}static buildListQueryFields(t=[]){const e={wyID:!0,model:!0,createdAt:!0,updatedAt:!0,organizationId:!0,isDeleted:!0};return t.forEach(r=>{e[`data.${r}`]=!0}),e}static buildDetailQueryFields(){return{wyID:!0,model:!0,data:!0,createdAt:!0,updatedAt:!0,createdBy:!0,updatedBy:!0,organizationId:!0,isDeleted:!0,version:!0}}}class g{constructor(t,e,r,n={}){this.connection=t,this.validator=e,this.queryBuilder=r,this.config=n}getCurrentOrganizationId(){return this.config.getCurrentOrganizationId?this.config.getCurrentOrganizationId():null}getCurrentUserId(){return this.config.getCurrentUserId?this.config.getCurrentUserId():null}async create(t){try{if(this.connection.ensureInitialized(),!t.wyID)throw new Error("Document wyID is required");if(!t.model)throw new Error("Document model is required");await this.validator.validateWyIDUniqueness(t.wyID);let e=t;if(!t.createdAt||!t.updatedAt){const n=t.createdBy||this.getCurrentUserId(),o=t.organizationId||this.getCurrentOrganizationId();e=y.buildBaseDocument(t.wyID,t.model,t.data,n,o,this.connection),e={...e,...t}}const r=await this.connection.collection.add(e);return console.log(`Document created successfully: ${e.model}/${e.wyID}`),e.wyID}catch(e){throw console.error("Failed to create document:",e),e.message.includes("DUPLICATE_WYID")?e:e.message.includes("wyID is required")||e.message.includes("model is required")||e.message.includes("Invalid wyID format")?new Error(`VALIDATION_ERROR: ${e.message}`):new Error(`DATABASE_ERROR: Failed to create document: ${e.message}`)}}async findById(t,e,r={}){try{this.connection.ensureInitialized();let n=this.connection.collection.where({model:t,wyID:e,isDeleted:!1});return n=this.queryBuilder.applyFieldSelection(n,r),(await n.get()).data[0]||null}catch(n){throw console.error("Failed to find document by ID:",n),new Error(`Failed to find document: ${n}`)}}async findList(t,e={},r={}){try{this.connection.ensureInitialized();const o=await this.queryBuilder.buildQuery(this.connection.collection,t,e,r).get(),i=await this.count(t,e),a=this.queryBuilder.calculatePaginationInfo(i,e);return{data:o.data,...a}}catch(n){throw console.error("Failed to find document list:",n),new Error(`Failed to find document list: ${n}`)}}async findByIds(t,e,r={}){try{return this.connection.ensureInitialized(),e.length===0?[]:(await this.queryBuilder.buildBatchQuery(this.connection.collection,this.connection.db,t,e,r).get()).data}catch(n){throw console.error("Failed to find documents by IDs:",n),new Error(`Failed to find documents by IDs: ${n}`)}}async update(t,e,r){try{this.connection.ensureInitialized();const n=this.getCurrentUserId(),o=y.buildUpdateDocument(r,n,this.connection),i=await this.connection.collection.where({model:t,wyID:e,isDeleted:!1}).update(o);return console.log(`Document updated: ${e}, affected: ${i.updated}`),i.updated>0}catch(n){throw console.error("Failed to update document:",n),new Error(`Failed to update document: ${n}`)}}async softDelete(t,e,r){try{this.connection.ensureInitialized();const n=y.buildSoftDeleteDocument(r,this.connection),o=await this.connection.collection.where({model:t,wyID:e,isDeleted:!1}).update(n);return console.log(`Document soft deleted: ${e}`),o.updated>0}catch(n){throw console.error("Failed to soft delete document:",n),new Error(`Failed to soft delete document: ${n}`)}}async hardDelete(t,e){try{this.connection.ensureInitialized();const r=await this.connection.collection.where({model:t,wyID:e}).remove();return console.log(`Document hard deleted: ${e}`),r.deleted>0}catch(r){throw console.error("Failed to hard delete document:",r),new Error(`Failed to hard delete document: ${r}`)}}async count(t,e={}){try{return this.connection.ensureInitialized(),(await this.queryBuilder.buildCountQuery(this.connection.collection,t,e).count()).total}catch(r){throw console.error("Failed to count documents:",r),new Error(`Failed to count documents: ${r}`)}}async batchUpdate(t,e){try{this.connection.ensureInitialized();let r=0;for(const{wyID:n,data:o}of e)await this.update(t,n,o)&&r++;return r}catch(r){throw console.error("Failed to batch update documents:",r),new Error(`Failed to batch update documents: ${r}`)}}}class D{constructor(t,e){this.crudOperations=t,this.validator=e}async batchCreate(t){try{if(!Array.isArray(t)||t.length===0)throw new Error("Documents array is required and cannot be empty");const e=t.map(o=>o.wyID).filter(Boolean);await this.validator.validateBatchWyIDUniqueness(e);const r=[],n=[];for(let o=0;o<t.length;o++)try{const i=await this.crudOperations.create(t[o]);r.push({index:o,wyID:i,success:!0})}catch(i){n.push({index:o,error:i.message,success:!1}),console.error(`Failed to create document at index ${o}:`,i)}return n.length>0&&console.warn(`Batch create completed with ${n.length} errors:`,n),console.log(`Batch create completed: ${r.length} successful, ${n.length} failed`),{successful:r,failed:n,totalProcessed:t.length,successCount:r.length,failureCount:n.length}}catch(e){throw console.error("Failed to batch create documents:",e),new Error(`Failed to batch create documents: ${e}`)}}async batchUpdate(t,e){try{if(!Array.isArray(e)||e.length===0)throw new Error("Updates array is required and cannot be empty");const r=[],n=[];for(let o=0;o<e.length;o++){const{wyID:i,data:a}=e[o];if(!i){n.push({index:o,wyID:null,error:"wyID is required",success:!1});continue}try{const s=await this.crudOperations.update(t,i,a);r.push({index:o,wyID:i,success:s,updated:s})}catch(s){n.push({index:o,wyID:i,error:s.message,success:!1}),console.error(`Failed to update document at index ${o} (wyID: ${i}):`,s)}}return n.length>0&&console.warn(`Batch update completed with ${n.length} errors:`,n),console.log(`Batch update completed: ${r.length} processed, ${n.length} failed`),{successful:r,failed:n,totalProcessed:e.length,successCount:r.filter(o=>o.updated).length,failureCount:n.length}}catch(r){throw console.error("Failed to batch update documents:",r),new Error(`Failed to batch update documents: ${r}`)}}async batchSoftDelete(t,e,r){try{if(!Array.isArray(e)||e.length===0)throw new Error("wyIDs array is required and cannot be empty");if(!r)throw new Error("userId is required for soft delete operations");const n=[],o=[];for(let i=0;i<e.length;i++){const a=e[i];if(!a){o.push({index:i,wyID:null,error:"wyID is required",success:!1});continue}try{const s=await this.crudOperations.softDelete(t,a,r);n.push({index:i,wyID:a,success:s,deleted:s})}catch(s){o.push({index:i,wyID:a,error:s.message,success:!1}),console.error(`Failed to soft delete document at index ${i} (wyID: ${a}):`,s)}}return o.length>0&&console.warn(`Batch soft delete completed with ${o.length} errors:`,o),console.log(`Batch soft delete completed: ${n.length} processed, ${o.length} failed`),{successful:n,failed:o,totalProcessed:e.length,successCount:n.filter(i=>i.deleted).length,failureCount:o.length}}catch(n){throw console.error("Failed to batch soft delete documents:",n),new Error(`Failed to batch soft delete documents: ${n}`)}}async batchHardDelete(t,e){try{if(!Array.isArray(e)||e.length===0)throw new Error("wyIDs array is required and cannot be empty");console.warn(`Performing batch hard delete for ${e.length} documents. This operation cannot be undone.`);const r=[],n=[];for(let o=0;o<e.length;o++){const i=e[o];if(!i){n.push({index:o,wyID:null,error:"wyID is required",success:!1});continue}try{const a=await this.crudOperations.hardDelete(t,i);r.push({index:o,wyID:i,success:a,deleted:a})}catch(a){n.push({index:o,wyID:i,error:a.message,success:!1}),console.error(`Failed to hard delete document at index ${o} (wyID: ${i}):`,a)}}return n.length>0&&console.warn(`Batch hard delete completed with ${n.length} errors:`,n),console.log(`Batch hard delete completed: ${r.length} processed, ${n.length} failed`),{successful:r,failed:n,totalProcessed:e.length,successCount:r.filter(o=>o.deleted).length,failureCount:n.length}}catch(r){throw console.error("Failed to batch hard delete documents:",r),new Error(`Failed to batch hard delete documents: ${r}`)}}async batchValidate(t){try{if(!Array.isArray(t)||t.length===0)throw new Error("Documents array is required and cannot be empty");const e=[],r=[],n=t.map(o=>o.wyID).filter(Boolean);try{await this.validator.validateBatchWyIDUniqueness(n)}catch(o){console.warn("Batch wyID validation failed:",o.message)}for(let o=0;o<t.length;o++){const i=t[o];try{if(!i.wyID)throw new Error("wyID is required");if(!i.model)throw new Error("model is required");if(!this.validator.validateWyIDFormat(i.wyID))throw new Error(`Invalid wyID format: ${i.wyID}`);e.push({index:o,wyID:i.wyID,valid:!0})}catch(a){r.push({index:o,wyID:i.wyID||null,error:a.message,valid:!1})}}return{valid:e,invalid:r,totalProcessed:t.length,validCount:e.length,invalidCount:r.length,isAllValid:r.length===0}}catch(e){throw console.error("Failed to batch validate documents:",e),new Error(`Failed to batch validate documents: ${e}`)}}}class B{constructor(t,e){this.connection=t,this.queryBuilder=e}async search(t,e,r={}){try{return this.connection.ensureInitialized(),(await this.queryBuilder.buildSearchQuery(this.connection.collection,t,e,r).get()).data}catch(n){throw console.error("Failed to search documents:",n),new Error(`Failed to search documents: ${n}`)}}async advancedSearch(t,e,r={}){try{this.connection.ensureInitialized();const n={model:t,isDeleted:!1};if(e.text&&(n.searchText=new RegExp(e.text,"i")),e.dateRange){const{startDate:d,endDate:u,field:w="createdAt"}=e.dateRange;d&&u?n[w]=this.connection.db.command.and([this.connection.db.command.gte(d),this.connection.db.command.lte(u)]):d?n[w]=this.connection.db.command.gte(d):u&&(n[w]=this.connection.db.command.lte(u))}e.organizationId&&(n.organizationId=e.organizationId),e.createdBy&&(n.createdBy=e.createdBy),e.customFields&&Object.keys(e.customFields).forEach(d=>{n[d]=e.customFields[d]});let o=this.connection.collection.where(n);o=this.queryBuilder.applyPagination(o,r),o=this.queryBuilder.applySorting(o,r),o=this.queryBuilder.applyFieldSelection(o,r);const i=await o.get(),s=await this.connection.collection.where(n).count(),f=this.queryBuilder.calculatePaginationInfo(s.total,r);return{data:i.data,...f}}catch(n){throw console.error("Failed to perform advanced search:",n),new Error(`Failed to perform advanced search: ${n}`)}}async getStatsByModel(){try{this.connection.ensureInitialized();const t=await this.connection.collection.field({model:!0,isDeleted:!0}).get(),e={};return t.data.forEach(r=>{e[r.model]||(e[r.model]={total:0,active:0,deleted:0}),e[r.model].total++,r.isDeleted?e[r.model].deleted++:e[r.model].active++}),e}catch(t){throw console.error("Failed to get stats by model:",t),new Error(`Failed to get stats by model: ${t}`)}}async getStatsByOrganization(){try{this.connection.ensureInitialized();const t=await this.connection.collection.field({organizationId:!0,model:!0,isDeleted:!0}).get(),e={};return t.data.forEach(r=>{const n=r.organizationId||"no-organization";e[n]||(e[n]={total:0,active:0,deleted:0,byModel:{}}),e[n].total++,r.isDeleted?e[n].deleted++:e[n].active++,e[n].byModel[r.model]||(e[n].byModel[r.model]={total:0,active:0,deleted:0}),e[n].byModel[r.model].total++,r.isDeleted?e[n].byModel[r.model].deleted++:e[n].byModel[r.model].active++}),e}catch(t){throw console.error("Failed to get stats by organization:",t),new Error(`Failed to get stats by organization: ${t}`)}}async getStatsByTimeRange(t,e,r="day"){try{this.connection.ensureInitialized();const n=await this.connection.collection.where({isDeleted:!1,createdAt:this.connection.db.command.and([this.connection.db.command.gte(t),this.connection.db.command.lte(e)])}).field({createdAt:!0,model:!0}).get(),o={};return n.data.forEach(i=>{const a=new Date(i.createdAt);let s;switch(r){case"hour":s=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")} ${String(a.getHours()).padStart(2,"0")}:00`;break;case"day":s=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`;break;case"month":s=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}`;break;case"year":s=`${a.getFullYear()}`;break;default:s=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`}o[s]||(o[s]={total:0,byModel:{}}),o[s].total++,o[s].byModel[i.model]||(o[s].byModel[i.model]=0),o[s].byModel[i.model]++}),o}catch(n){throw console.error("Failed to get stats by time range:",n),new Error(`Failed to get stats by time range: ${n}`)}}async getRecentActivity(t=50,e=null){try{this.connection.ensureInitialized();const r={isDeleted:!1};return e&&(r.model=e),(await this.connection.collection.where(r).orderBy("updatedAt","desc").limit(t).field({wyID:!0,model:!0,createdAt:!0,updatedAt:!0,createdBy:!0,updatedBy:!0,organizationId:!0}).get()).data}catch(r){throw console.error("Failed to get recent activity:",r),new Error(`Failed to get recent activity: ${r}`)}}async fullTextSearch(t,e={}){try{this.connection.ensureInitialized();const{models:r=[],limit:n=50,skip:o=0}=e,i={isDeleted:!1};r.length>0&&(i.model=this.connection.db.command.in(r));const a=new RegExp(t,"i");i.$or=[{searchText:a},{"data.title":a},{"data.name":a},{"data.description":a},{wyID:a}];let s=this.connection.collection.where(i);n&&(s=s.limit(n)),o&&(s=s.skip(o)),s=s.orderBy("updatedAt","desc"),s=s.field({wyID:!0,model:!0,createdAt:!0,updatedAt:!0,organizationId:!0,"data.title":!0,"data.name":!0,"data.description":!0});const f=await s.get(),u=await this.connection.collection.where(i).count();return{data:f.data,total:u.total,page:Math.floor(o/n)+1,pageSize:n,hasMore:o+n<u.total}}catch(r){throw console.error("Failed to perform full text search:",r),new Error(`Failed to perform full text search: ${r}`)}}}class F{constructor(t={}){this.config={cloudbaseConfig:{env:"mobenai-weapp-dev-2e8qhi3a963364",persistence:"local",collectionName:"platform-metadata",...t.cloudbaseConfig},getCurrentOrganizationId:t.getCurrentOrganizationId||(()=>null),getCurrentUserId:t.getCurrentUserId||(()=>null),...t},this.connection=new p(this.config.cloudbaseConfig),this.throttler=new m,this.queryBuilder=new I,this.validator=new b(this.connection),this.crud=new g(this.connection,this.validator,this.queryBuilder,this.config),this.batch=new D(this.crud,this.validator),this.search=new B(this.connection,this.queryBuilder)}updateConfig(t){this.config={...this.config,...t},t.cloudbaseConfig&&this.connection.updateConfig(t.cloudbaseConfig),this.crud=new g(this.connection,this.validator,this.queryBuilder,this.config)}getConfig(){return{...this.config}}ensureInitialized(){return this.connection.ensureInitialized()}get db(){return this.connection.db}get collection(){return this.connection.collection}getRawDB(){return this.connection.getRawDB()}getRawCollection(){return this.connection.getRawCollection()}validateWyIDFormat(t){return this.validator.validateWyIDFormat(t)}async checkWyIDExists(t){return this.validator.checkWyIDExists(t)}async getExistingDocumentInfo(t){return this.validator.getExistingDocumentInfo(t)}async getWyIDStats(){return this.validator.getWyIDStats()}async create(t){return this.crud.create(t)}async findById(t,e,r={}){const n={model:t,wyID:e,options:r};return this.throttler.withThrottle("findById",n,async()=>this.crud.findById(t,e,r))}async findList(t,e={},r={}){const n={model:t,filter:e,options:r};return this.throttler.withThrottle("findList",n,async()=>this.crud.findList(t,e,r))}async findByIds(t,e,r={}){const n={model:t,wyIDs:e,options:r};return this.throttler.withThrottle("findByIds",n,async()=>this.crud.findByIds(t,e,r))}async update(t,e,r){return this.crud.update(t,e,r)}async softDelete(t,e,r){return this.crud.softDelete(t,e,r)}async hardDelete(t,e){return this.crud.hardDelete(t,e)}async count(t,e={}){const r={model:t,filter:e};return this.throttler.withThrottle("count",r,async()=>this.crud.count(t,e))}async batchCreate(t){return this.batch.batchCreate(t)}async batchUpdate(t,e){return this.batch.batchUpdate(t,e)}async batchSoftDelete(t,e,r){return this.batch.batchSoftDelete(t,e,r)}async batchHardDelete(t,e){return this.batch.batchHardDelete(t,e)}async batchValidate(t){return this.batch.batchValidate(t)}async search(t,e,r={}){const n={model:t,searchText:e,options:r};return this.throttler.withThrottle("search",n,async()=>this.search.search(t,e,r))}async advancedSearch(t,e,r={}){const n={model:t,searchCriteria:e,options:r};return this.throttler.withThrottle("advancedSearch",n,async()=>this.search.advancedSearch(t,e,r))}async fullTextSearch(t,e={}){const r={searchText:t,options:e};return this.throttler.withThrottle("fullTextSearch",r,async()=>this.search.fullTextSearch(t,e))}async getStatsByModel(){return this.search.getStatsByModel()}async getStatsByOrganization(){return this.search.getStatsByOrganization()}async getStatsByTimeRange(t,e,r="day"){return this.search.getStatsByTimeRange(t,e,r)}async getRecentActivity(t=50,e=null){return this.search.getRecentActivity(t,e)}buildWhereCondition(t){return this.queryBuilder.buildWhereCondition(t)}async runTransaction(t){throw console.warn("Transaction is temporarily disabled. Operations will be executed sequentially."),new Error("Transaction is not supported in browser environment. Please use sequential operations or migrate to server-side.")}async createInTransaction(t,e){throw console.warn("createInTransaction is temporarily disabled."),new Error("Transaction operations are not supported in browser environment.")}async updateInTransaction(t,e,r,n){throw console.warn("updateInTransaction is temporarily disabled."),new Error("Transaction operations are not supported in browser environment.")}async deleteInTransaction(t,e,r,n){throw console.warn("deleteInTransaction is temporarily disabled."),new Error("Transaction operations are not supported in browser environment.")}clearPendingRequests(){this.throttler.clearPendingRequests()}getPendingRequestCount(){return this.throttler.getPendingRequestCount()}setThrottleTimeout(t){this.throttler.setThrottleTimeout(t)}isConnected(){return this.connection.isConnected()}reset(){this.connection.reset(),this.throttler.clearPendingRequests()}getClientStatus(){return{isConnected:this.isConnected(),pendingRequests:this.getPendingRequestCount(),throttleTimeout:this.throttler.throttleTimeout,config:this.getConfig(),components:{connection:!!this.connection,throttler:!!this.throttler,validator:!!this.validator,crud:!!this.crud,batch:!!this.batch,search:!!this.search,queryBuilder:!!this.queryBuilder}}}}const A=Object.freeze(Object.defineProperty({__proto__:null,BatchOperations:D,CRUDOperations:g,DatabaseClient:F,DatabaseConnection:p,DocumentBuilder:y,QueryBuilder:I,RequestThrottler:m,SearchOperations:B,WyIDValidator:b},Symbol.toStringTag,{value:"Module"}));l.DatabaseCore=A,l.utils=$,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})});