ots-client 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/adapters/type-adapter.d.ts +6 -0
  2. package/dist/client/base-client.d.ts +59 -0
  3. package/dist/client/index.d.ts +3 -0
  4. package/dist/client/query-builder.d.ts +23 -0
  5. package/dist/decorators/index.d.ts +56 -0
  6. package/dist/deps/acorn-BOl0sFTPW7-g7l5tn7d4.js +16 -0
  7. package/dist/deps/acorn-BOl0sFTPW7-hklkvjepo.js +3005 -0
  8. package/dist/deps/angular-XNXkkMW2x2-7du6op6fw.js +2533 -0
  9. package/dist/deps/angular-XNXkkMW2x2-we6wvxttc.js +3 -0
  10. package/dist/deps/babel-JmunAd9gx3-6dq643w5b.js +7217 -0
  11. package/dist/deps/babel-JmunAd9gx3-wao5c2v19.js +15 -0
  12. package/dist/deps/estree-QR0a7eAiZm-36ju20hxl.js +4528 -0
  13. package/dist/deps/estree-QR0a7eAiZm-t0kwe9gae.js +44 -0
  14. package/dist/deps/flow-GdDnVSvT5w-rgi5vp4qm.js +27411 -0
  15. package/dist/deps/flow-GdDnVSvT5w-rnla0vmdw.js +20 -0
  16. package/dist/deps/glimmer-Yu8RjFE1-a-5ivcwuhu1.js +37 -0
  17. package/dist/deps/glimmer-Yu8RjFE1-a-60xpuum9o.js +2703 -0
  18. package/dist/deps/graphql-b_914AArZY-uwrebifsb.js +28 -0
  19. package/dist/deps/graphql-b_914AArZY-yc77nhrwj.js +1221 -0
  20. package/dist/deps/html-6ymxY6PL6B-ge7hzyfqj.js +2791 -0
  21. package/dist/deps/html-6ymxY6PL6B-ug8ebf4sa.js +25 -0
  22. package/dist/deps/index-apktVSn0Wa-1pqh8j69b.js +7 -0
  23. package/dist/deps/index-apktVSn0Wa-m4m4s4pcy.js +24535 -0
  24. package/dist/deps/markdown-44cJkal_TC-rli9cqus2.js +3190 -0
  25. package/dist/deps/markdown-44cJkal_TC-t8vpmxjyl.js +62 -0
  26. package/dist/deps/meriyah-IwksJmaFJr-1kz9p5807.js +5 -0
  27. package/dist/deps/meriyah-IwksJmaFJr-aj8jxnzem.js +2645 -0
  28. package/dist/deps/postcss-gD1c7_GzEP-7h0ly93la.js +61 -0
  29. package/dist/deps/postcss-gD1c7_GzEP-kecpdijjx.js +4739 -0
  30. package/dist/deps/typescript-tYbKJGRdB5-3c3whaiss.js +12947 -0
  31. package/dist/deps/typescript-tYbKJGRdB5-4n3mbr7g0.js +21 -0
  32. package/dist/deps/yaml-LL7qhBUJFz-xb6k8do2g.js +4079 -0
  33. package/dist/deps/yaml-LL7qhBUJFz-zl5hfpq31.js +159 -0
  34. package/dist/generate.cjs +42349 -0
  35. package/dist/generate.d.ts +1 -0
  36. package/dist/generate.js +241530 -0
  37. package/dist/generator/index.d.ts +6 -0
  38. package/dist/generator/parser.d.ts +20 -0
  39. package/dist/generator/table-generator.d.ts +3 -0
  40. package/dist/generator/type-generator.d.ts +6 -0
  41. package/dist/index.cjs +1 -0
  42. package/dist/index.d.ts +4 -0
  43. package/dist/index.js +726 -0
  44. package/dist/init/index.d.ts +3 -0
  45. package/dist/types/client.d.ts +35 -0
  46. package/dist/types/index.d.ts +98 -0
  47. package/dist/utils/index.d.ts +31 -0
  48. package/package.json +47 -0
@@ -0,0 +1,6 @@
1
+ export interface GenerateOptions {
2
+ schemaPath: string;
3
+ generatePath: string;
4
+ prettierOptions?: object;
5
+ }
6
+ export declare function generate(options: GenerateOptions): Promise<void>;
@@ -0,0 +1,20 @@
1
+ import { Project } from 'ts-morph';
2
+ import { SchemaMeta } from '../types/index';
3
+
4
+ /**
5
+ * 解析装饰器元数据
6
+ * @param project - ts-morph项目实例
7
+ * @param filePaths - 要解析的文件路径数组
8
+ */
9
+ export declare function parseDecorators(project: Project, filePaths: string[]): {
10
+ schemaMeta: SchemaMeta;
11
+ tableNames: string[];
12
+ };
13
+ /**
14
+ * 创建ts-morph项目
15
+ */
16
+ export declare function createProject(): Project;
17
+ /**
18
+ * 获取Schema目录下的所有TypeScript文件
19
+ */
20
+ export declare function getSchemaFiles(schemaPath: string): string[];
@@ -0,0 +1,3 @@
1
+ import { SchemaMeta } from '../types/index';
2
+
3
+ export declare function generateSchemaMeta(schemaMeta: SchemaMeta, tableNames: string[], outputPath: string, prettierOptions?: object): Promise<void>;
@@ -0,0 +1,6 @@
1
+ import { SchemaMeta } from '../types/index';
2
+
3
+ /**
4
+ * 生成类型声明文件 types.ts
5
+ */
6
+ export declare function generateTypes(schemaMeta: SchemaMeta, tableNames: string[], outputPath: string): void;
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var P=Object.defineProperty;var x=(c,t,e)=>t in c?P(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e;var m=(c,t,e)=>x(c,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./deps/index-apktVSn0Wa-1pqh8j69b.js"),Q="ots:table",I="ots:primaryKey",F="ots:partitionKey",U="ots:field",q="ots:createdAt",Y="ots:updatedAt";function N(c){return t=>{var e;(e=Reflect.defineMetadata)==null||e.call(Reflect,Q,c,t)}}function k(c){return(t,e)=>{var r;(r=Reflect.defineMetadata)==null||r.call(Reflect,I,c||{},t,e)}}function M(c){return(t,e)=>{var r;(r=Reflect.defineMetadata)==null||r.call(Reflect,F,c||{},t,e)}}function z(c){return(t,e)=>{var r;(r=Reflect.defineMetadata)==null||r.call(Reflect,U,c,t,e)}}function B(c){return(t,e)=>{var r;(r=Reflect.defineMetadata)==null||r.call(Reflect,q,!0,t,e)}}function G(c){return(t,e)=>{var r;(r=Reflect.defineMetadata)==null||r.call(Reflect,Y,!0,t,e)}}function K(c){if(!c||typeof c!="object")return!1;const t=Object.getPrototypeOf(c);return t===null||t===Object.prototype||Object.getPrototypeOf(t)===null?Object.prototype.toString.call(c)==="[object Object]":!1}const p={eq:o.TableStore.ComparatorType.EQUAL,not:o.TableStore.ComparatorType.NOT_EQUAL,lt:o.TableStore.ComparatorType.LESS_THAN,lte:o.TableStore.ComparatorType.LESS_EQUAL,gt:o.TableStore.ComparatorType.GREATER_THAN,gte:o.TableStore.ComparatorType.GREATER_EQUAL};function V(c,t,e){var r,i;if(K(t)){const n=Object.entries(t);if(n.length===1){const[a,s]=n[0];return new o.tablestore.SingleColumnCondition(c,o.TypeAdapter.toOTS(s,(r=e==null?void 0:e[c])==null?void 0:r.type),p[a])}else if(n.length>1){const a=new o.TableStore.CompositeCondition(o.TableStore.LogicalOperator.AND);return n.forEach(([s,l])=>{var y;a.addSubCondition(new o.TableStore.SingleColumnCondition(c,o.TypeAdapter.toOTS(l,(y=e==null?void 0:e[c])==null?void 0:y.type),p[s]))}),a}}else return new o.tablestore.SingleColumnCondition(c,o.TypeAdapter.toOTS(t,(i=e==null?void 0:e[c])==null?void 0:i.type),p.eq)}function _(c,t,e){if(c==="NOT"){const r=g(t,e);if(r){const i=new o.TableStore.CompositeCondition(o.TableStore.LogicalOperator.NOT);return i.addSubCondition(r),i}}else if(c==="AND"){if(Array.isArray(t)){if(t.length===1)return g(t[0],e);if(t.length>1){const r=t.map(i=>g(i,e)).filter(i=>!!i);if(r.length===1)return r[0];if(r.length>1){const i=new o.TableStore.CompositeCondition(o.TableStore.LogicalOperator.AND);return r.forEach(n=>i.addSubCondition(n)),i}}}}else if(c==="OR"){if(Array.isArray(t)){if(t.length===1)return g(t[0],e);if(t.length>1){const r=t.map(i=>g(i,e)).filter(i=>!!i);if(r.length===1)return r[0];if(r.length>1){const i=new o.TableStore.CompositeCondition(o.TableStore.LogicalOperator.OR);return r.forEach(n=>i.addSubCondition(n)),i}}}}else return V(c,t,e)}function g(c,t){const e=Object.entries(c);if(e.length===1){const[r,i]=e[0];return _(r,i,t)}else if(e.length>1){const r=e.map(([i,n])=>_(i,n,t)).filter(i=>!!i);if(r.length===1)return r[0];if(r.length>1){const i=new o.TableStore.CompositeCondition(o.TableStore.LogicalOperator.AND);return r.forEach(n=>i.addSubCondition(n)),i}}}const $={eq:[o.TableStore.QueryType.TERM_QUERY,"term"],in:[o.TableStore.QueryType.TERMS_QUERY,"terms"],lt:[o.TableStore.QueryType.RANGE_QUERY,"rangeTo",{includeUpper:!1}],lte:[o.TableStore.QueryType.RANGE_QUERY,"rangeTo",{includeUpper:!0}],gt:[o.TableStore.QueryType.RANGE_QUERY,"rangeFrom",{includeLower:!1}],gte:[o.TableStore.QueryType.RANGE_QUERY,"rangeFrom",{includeLower:!0}],contains:[o.TableStore.QueryType.WILDCARD_QUERY,"value",{},c=>`*${c}*`],startsWith:[o.TableStore.QueryType.WILDCARD_QUERY,"value",{},c=>`${c}*`],endsWith:[o.TableStore.QueryType.WILDCARD_QUERY,"value",{},c=>`*${c}`]};function W(c,t,e){var r;if(K(t)){const i=Object.entries(t);return{queryType:o.TableStore.QueryType.BOOL_QUERY,mustQueries:i.map(([n,a])=>{var h;const[s,l,y,d]=$[n]??[],u=d?d(a):a;return{queryType:s,[l]:o.TypeAdapter.toOTS(u,(h=e==null?void 0:e[c])==null?void 0:h.type),...y??{}}})}}else return{queryType:o.TableStore.QueryType.TERM_QUERY,query:{fieldName:c,term:o.TypeAdapter.toOTS(t,(r=e==null?void 0:e[c])==null?void 0:r.type)}}}function H(c,t,e){if(c==="NOT"){const r=w(t,e);return{queryType:o.TableStore.QueryType.BOOL_QUERY,mustNotQueries:[r]}}else return c==="AND"?Array.isArray(t)?{queryType:o.TableStore.QueryType.BOOL_QUERY,mustQueries:t.map(r=>w(r,e))}:w(t,e):c==="OR"?Array.isArray(t)?{queryType:o.TableStore.QueryType.BOOL_QUERY,shouldQueries:t.map(r=>w(r,e)),minimumShouldMatch:1}:w(t,e):W(c,t,e)}function w(c,t){const e=Object.entries(c);return{queryType:o.TableStore.QueryType.BOOL_QUERY,query:{mustQueries:e.map(([r,i])=>H(r,i,t))}}}const J={asc:o.TableStore.SortOrder.SORT_ORDER_ASC,desc:o.TableStore.SortOrder.SORT_ORDER_DESC};class E{static buildColumnCondition(t,e){return g(t??{},e)}static buildSearchQuery(t,e){return!t||Object.keys(t).length===0?{queryType:o.TableStore.QueryType.MATCH_ALL_QUERY}:w(t,e)}static buildSearchSort(t){const e=Object.entries(t??{});if(e.length>0)return{sorters:e.map(([i,n])=>({fieldSort:{fieldName:i,order:J[n==null?void 0:n.toLowerCase()]}}))}}static matchCondition(t,e){return!e||Object.keys(e).length===0?!0:Object.entries(e).every(([r,i])=>this.matchField(t,r,i))}static matchField(t,e,r){if(e==="NOT")return!this.matchCondition(t,r);if(e==="AND")return Array.isArray(r)?r.every(n=>this.matchCondition(t,n)):this.matchCondition(t,r);if(e==="OR")return Array.isArray(r)?r.some(n=>this.matchCondition(t,n)):this.matchCondition(t,r);const i=t[e];return typeof r=="object"&&r!==null?Object.entries(r).every(([n,a])=>this.compareValue(i,n,a)):this.compareValue(i,"eq",r)}static compareValue(t,e,r){switch(e){case"eq":return t===r;case"not":return t!==r;case"lt":return t<r;case"lte":return t<=r;case"gt":return t>r;case"gte":return t>=r;case"in":return Array.isArray(r)?r.includes(t):!1;case"contains":return typeof t=="string"&&typeof r=="string"?t.includes(r):!1;default:return t===r}}static extractSortValues(t,e){return!e||Object.keys(e).length===0?[]:Object.keys(e).map(r=>t[r])}static buildSortComparator(t){if(!t||Object.keys(t).length===0)return()=>0;const e=Object.keys(t);return(r,i)=>{for(const n of e){const a=t[n],s=r[n],l=i[n];if(s===l)continue;let y=s==null?1:l==null||s<l?-1:1;return a==="desc"?-y:y}return 0}}}const b=class b{constructor(t,e,r){m(this,"client");m(this,"schemaMeta");m(this,"context");m(this,"fieldMetaMap",{});m(this,"cacheTableInitialized",!1);this.client=t,this.schemaMeta=e,this.context=r,this.fieldMetaMap=Object.entries(e).reduce((i,[n,a])=>(i[n]=a.columns.reduce((s,l)=>(s[l.name]=l,s),{}),i),{})}getTableMeta(t){const e=this.schemaMeta[t];if(!e)throw new Error(`Table '${t}' not found in schema metadata`);return e}fromOTS(t,e){if(!t)return null;const r={},i=this.fieldMetaMap[e.tableName];return Object.keys(t).forEach(n=>{const a=t[n],s=i==null?void 0:i[n];r[n]=s?o.TypeAdapter.fromOTS(a,s.type):a}),r}recordToOTS(t,e){if(!t)return null;const r={},i=this.fieldMetaMap[e.tableName];return Object.keys(t).forEach(n=>{const a=t[n],s=i==null?void 0:i[n];r[n]=s?o.TypeAdapter.toOTS(a,s.type):a}),r}transformRawData(t,e){var n,a;const r=this.fieldMetaMap[t],i={};return(n=e==null?void 0:e.primaryKey)==null||n.forEach(s=>{const l=r==null?void 0:r[s.name];i[s.name]=l?o.TypeAdapter.fromOTS(s.value,l.type):s.value}),(a=e==null?void 0:e.attributes)==null||a.forEach(s=>{const l=r==null?void 0:r[s.columnName];i[s.columnName]=l?o.TypeAdapter.fromOTS(s.columnValue,l.type):s.columnValue}),i}splitPkObject(t,e){const r={},i={},n=e.primaryKeys;return Object.keys(t).forEach(a=>{n.includes(a)?r[a]=t[a]:i[a]=t[a]}),[r,i]}getSelect(t){const e=Object.entries(t??{}).reduce((r,[i,n])=>(n&&r.push(i),r),[]);if(e.length>0)return e}pkToOts(t,e){return e.primaryKeys.map(r=>({[r]:t[r]}))}async findUnique(t,{where:e,select:r}){const i=this.getTableMeta(t),n=this.fieldMetaMap[t],a=o.fillPartitionKey(e??{},i.partitionKeyColumn,this.context);o.validatePartitionKey(a,i.partitionKeyColumn);const[s,l]=this.splitPkObject(a,i),y=this.pkToOts(this.recordToOTS(s,i),i),d=E.buildColumnCondition(l,n);try{const u=await this.client.getRow({tableName:t,primaryKey:y,columnFilter:d,columnsToGet:this.getSelect(r)});return u.row?this.transformRawData(t,u.row):null}catch(u){throw console.error("findUnique error:",u),u}}async findUniqueOrThrow(t,{where:e,select:r}){const i=await this.findUnique(t,{where:e,select:r});if(!i)throw new Error("Data Not Found");return i}async findFirst(t,e){const{data:r}=await this.findManyFragment(t,{where:e==null?void 0:e.where,select:e==null?void 0:e.select,limit:1});return r.length>0?r[0]:null}async findFirstOrThrow(t,e){const r=await this.findFirst(t,e);if(!r)throw new Error("Data Not Found");return r}async findManyFragment(t,e){const r=this.getTableMeta(t),i=this.fieldMetaMap[t],n=E.buildSearchQuery(e==null?void 0:e.where,i),a=E.buildSearchSort(e==null?void 0:e.orderBy),s=this.getSelect(e==null?void 0:e.select);try{const l=await this.client.search({tableName:t,indexName:`${t}_index`,searchQuery:{offset:(e==null?void 0:e.offset)??0,limit:(e==null?void 0:e.limit)??100,getTotalCount:!0,query:n,sort:a},columnToGet:{returnType:o.tablestore.ColumnReturnType.RETURN_SPECIFIED,returnNames:s??r.columnKeys}}),y=((l==null?void 0:l.rows)??[]).map(d=>this.transformRawData(t,d));return{total:Number((l==null?void 0:l.totalCounts)??0),data:y}}catch(l){throw console.error("findManyFragment error:",l),l}}async findManyCombination(t,e){const n=(e==null?void 0:e.limit)??99e3;if(n>99e3)throw new Error("limit can not oversize 99000");let a=(e==null?void 0:e.offset)??0,s=Math.min(n,100),l=0;const y=[];try{for(;;){const{total:d,data:u}=await this.findManyFragment(t,{offset:a,limit:s,select:e==null?void 0:e.select,where:e==null?void 0:e.where,orderBy:e==null?void 0:e.orderBy});y.push(...u),l+=s;const h=n-l;if(h<=0||d<=l)return{total:d,data:y};s=Math.min(h,s),a=l}}catch(d){throw console.error("findManyCombination error:",d),d}}async findMany(t,e){try{const{data:r}=await this.findManyCombination(t,e);return r}catch(r){throw console.error("findMany error:",r),r}}async findPage(t,e){const i=(e==null?void 0:e.limit)||10;if(i>100)throw new Error("limit must be less than or equal to 100");const n=e==null?void 0:e.where,a=e==null?void 0:e.orderBy,s=(e==null?void 0:e.page)||1,l=e==null?void 0:e.select,y=(s-1)*i,{total:d,data:u}=await this.findManyCombination(t,{where:n,orderBy:a,limit:i,offset:y,select:l}),h=Math.ceil(d/i);return{data:u,total:d,page:s,pageCount:h,limit:i,hasPrev:s>1,hasNext:s<h}}async create(t,{data:e}){var u;const r=this.getTableMeta(t),i=this.fieldMetaMap[t];let n=o.fillPartitionKey(e??{},r.partitionKeyColumn,this.context);n=o.applyDefaultValues(n,r,this.context),o.validatePartitionKey(n,r.partitionKeyColumn);const[a,s]=this.splitPkObject(n,r),l=this.pkToOts(this.recordToOTS(a,r),r),y=[];Object.entries(s??{}).forEach(([h,C])=>{var T;const f=(T=i[h])==null?void 0:T.type;y.push({[h]:o.TypeAdapter.toOTS(C,f)})});const d=new o.tablestore.Condition(o.tablestore.RowExistenceExpectation.EXPECT_NOT_EXIST,null);try{await this.client.putRow({tableName:t,primaryKey:l,condition:d,attributeColumns:y});const h=JSON.stringify(a);this.writeCache(t,h,n,!1).catch(()=>{})}catch(h){throw(u=h==null?void 0:h.message)!=null&&u.includes("OTSConditionCheckFail")?(console.error("create error: Record already exists"),Error("Record already exists")):(console.error("create error:",h),h)}}async update(t,{where:e,data:r}){const i=this.getTableMeta(t),n=this.fieldMetaMap[t],a=[],s=[];if(Object.entries(r??{}).forEach(([f,T])=>{var A;const O=(A=n[f])==null?void 0:A.type;O==="long"&&(T!=null&&T.$increment)?s.push({[f]:o.TypeAdapter.toOTS(T.$increment,O)}):a.push({[f]:o.TypeAdapter.toOTS(T,O)})}),a.length===0&&s.length===0)return;o.applyUpdateValues(a,i);const l=o.fillPartitionKey(e??{},i.partitionKeyColumn,this.context);o.validatePartitionKey(l,i.partitionKeyColumn);const[y,d]=this.splitPkObject(l,i),u=this.pkToOts(this.recordToOTS(y,i),i),h=E.buildColumnCondition(d,n),C=new o.tablestore.Condition(o.tablestore.RowExistenceExpectation.IGNORE,h);try{await this.client.updateRow({tableName:t,primaryKey:u,condition:C,updateOfAttributeColumns:[...a.length>0?[{PUT:a}]:[{}],...s.length>0?[{INCREMENT:s}]:[{}]]});const f=JSON.stringify(y),T=await this.findUnique(t,{where:y});T&&this.writeCache(t,f,T,!1).catch(()=>{})}catch(f){throw console.error("update error:",f),f}}async delete(t,{where:e}){const r=this.getTableMeta(t),i=this.fieldMetaMap[t],n=o.fillPartitionKey(e??{},r.partitionKeyColumn,this.context);o.validatePartitionKey(n,r.partitionKeyColumn);const[a,s]=this.splitPkObject(n,r),l=this.pkToOts(this.recordToOTS(a,r),r),y=E.buildColumnCondition(s,i),d=new o.tablestore.Condition(o.tablestore.RowExistenceExpectation.IGNORE,y);try{await this.client.deleteRow({tableName:t,primaryKey:l,condition:d});const u=JSON.stringify(a);this.writeCache(t,u,a,!0).catch(()=>{})}catch(u){throw console.error("delete error:",u),u}}async count(t,e){try{const{total:r}=await this.findManyFragment(t,{where:e==null?void 0:e.where,limit:0});return r}catch(r){throw console.error("count error:",r),r}}async initCacheTable(){var t,e;if(!this.cacheTableInitialized){try{await this.client.describeTable({tableName:b.CACHE_TABLE_NAME}),this.cacheTableInitialized=!0;return}catch(r){if((t=r.message)!=null&&t.includes("OTSTableNotExist"))try{await this.client.createTable({tableMeta:{tableName:b.CACHE_TABLE_NAME,primaryKey:[{name:"table",type:o.tablestore.PrimaryKeyType.STRING},{name:"bizId",type:o.tablestore.PrimaryKeyType.STRING}]},tableOptions:{timeToLive:5,maxVersions:1e5},reservedThroughput:{capacityUnit:{read:0,write:0}}})}catch(i){(e=i.message)!=null&&e.includes("OTSObjectAlreadyExist")||console.error("Failed to create cache table:",i)}}this.cacheTableInitialized=!0}}async writeCache(t,e,r,i=!1){try{const n=Date.now(),a={isDeleted:i,data:r};await this.client.putRow({tableName:b.CACHE_TABLE_NAME,primaryKey:[{table:t},{bizId:e}],attributeColumns:[{data:{value:JSON.stringify(a),timestamp:n}}],condition:new o.tablestore.Condition(o.tablestore.RowExistenceExpectation.IGNORE,null)})}catch(n){console.warn("[writeCache] Failed:",n.message)}}async getCacheData(t,e,r,i){var n;try{const a=await this.client.getRow({tableName:b.CACHE_TABLE_NAME,primaryKey:[{table:t},{bizId:e}],maxVersions:1e5,timeRange:{startTime:r,endTime:i},columnsToGet:["data"]});if(!((n=a.row)!=null&&n.attributes))return null;const s=a.row.attributes.filter(d=>d.columnName==="data");let l=0,y=null;for(const d of s){const u=Number(d.timestamp);if(u>=r&&u<=i&&u>l){l=u;try{y=JSON.parse(String(d.columnValue||""))}catch{y=null}}}return l>0&&y?{bizId:e,timestamp:l,isDeleted:y.isDeleted??!1,data:y.data??{}}:null}catch(a){return console.warn(`[getCacheData] Failed to get row for bizId ${e}:`,a.message),null}}aggregateCacheRecords(t){const e=new Map;for(const r of t){const i=e.get(r.bizId);(!i||r.timestamp>i.timestamp)&&e.set(r.bizId,r)}return e}getPrimaryKeyValues(t,e){const r=this.getTableMeta(e),i={};for(const n of r.primaryKeys)t[n]!==void 0&&(i[n]=t[n]);return i}async queryRealtime(t,e){await this.initCacheTable();const r=Date.now(),i=r-b.CACHE_WINDOW_MS,n=r,a=e==null?void 0:e.bizId;let s=null;a&&(s=await this.getCacheData(t,a,i,n));let l=null,y=null;s&&(s.isDeleted?l=s.bizId:y={bizId:s.bizId,data:s.data});const d=e==null?void 0:e.where;let u=y?[y]:[];if(d&&Object.keys(d).length>0&&u.length>0&&(u=u.filter(S=>E.matchCondition(S.data,d))),u.length===0&&!l){const{total:S,data:L}=await this.findManyCombination(t,e);return{data:L,total:S}}let h=d??{};l&&(h={AND:[h,{NOT:{bizId:{in:[l]}}}]});const C=(e==null?void 0:e.limit)??100,{data:f,total:T}=await this.findManyCombination(t,{where:h,orderBy:e==null?void 0:e.orderBy,limit:C,offset:0,select:e==null?void 0:e.select}),O=new Map;for(const S of f)O.set(JSON.stringify(this.getPrimaryKeyValues(S,t)),S);u.length>0&&O.set(u[0].bizId,u[0].data);const A=Array.from(O.values());e!=null&&e.orderBy&&Object.keys(e.orderBy).length>0&&A.sort(E.buildSortComparator(e.orderBy));const j=T+u.length,D=(e==null?void 0:e.offset)??0;return{data:A.slice(D,D+C),total:j}}};m(b,"CACHE_TABLE_NAME","_data_cache_"),m(b,"CACHE_WINDOW_MS",3e3);let R=b;function X(c,t,e){const r=new R(c,t,e),i={};return Object.keys(t).forEach(n=>{i[n]={findUnique:a=>r.findUnique(n,a),findUniqueOrThrow:a=>r.findUniqueOrThrow(n,a),findFirst:a=>r.findFirst(n,a),findFirstOrThrow:a=>r.findFirstOrThrow(n,a),findMany:a=>r.findMany(n,a),findPage:a=>r.findPage(n,a),create:a=>r.create(n,a),update:a=>r.update(n,a),delete:a=>r.delete(n,a),count:a=>r.count(n,a),queryRealtime:a=>r.queryRealtime(n,a)}}),i}async function Z(c,t){await Promise.all(Object.values(t).map(async e=>v(c,e)))}async function v(c,t){await ee(c,t),await te(c,t.tableName,t)}async function ee(c,t){var e;try{await c.createTable({tableMeta:{tableName:t.tableName,primaryKey:t.columns.filter(r=>r.isPrimaryKey).map(r=>({name:r.name,type:re(r.type)}))},tableOptions:{timeToLive:-1,maxVersions:1},reservedThroughput:{capacityUnit:{read:0,write:0}}}),console.log(`Table ${t.tableName} created successfully`)}catch(r){(e=r.message)!=null&&e.includes("OTSObjectAlreadyExist")?console.log(`[Ignore]: Table ${t.tableName} already exists`):console.log(`[Error]: ${r.message}`)}}async function te(c,t,e){var i;const r=`${t}_index`;try{await c.createSearchIndex({tableName:t,indexName:r,schema:{fieldSchemas:(e.searchIndexes??[]).map(n=>({fieldName:n.fieldName,fieldType:ne(n.indexType),enableSortAndAgg:!0,...ae(n.indexType,n.options)}))}}),console.log(`Search index ${r} created successfully`)}catch(n){(i=n.message)!=null&&i.includes("OTSObjectAlreadyExist")?console.log(`[Index Error]: Search index ${r} already exists`):console.log(`[Index Error]: ${n.message}`)}}function re(c){switch(c){case"long":return o.tablestore.PrimaryKeyType.INTEGER;case"binary":return o.tablestore.PrimaryKeyType.BINARY;default:return o.tablestore.PrimaryKeyType.STRING}}const ie={number:o.tablestore.FieldType.DOUBLE,boolean:o.tablestore.FieldType.BOOLEAN,long:o.tablestore.FieldType.LONG,date:o.tablestore.FieldType.DATE,keyword:o.tablestore.FieldType.KEYWORD,text:o.tablestore.FieldType.TEXT,geopoint:o.tablestore.FieldType.GEO_POINT,vector:o.tablestore.FieldType.VECTOR??9};function ne(c){return ie[c]}function ae(c,t){var e;return c==="vector"?{...t??{},vectorOptions:{dataType:(e=o.tablestore.VectorDataType)==null?void 0:e.VD_FLOAT_32,...(t==null?void 0:t.vectorOptions)??{}}}:c==="date"?{dateFormats:["yyyy-MM-dd'T'HH:mm:ss.SSSX"],...t??{}}:t??{}}exports.VectorMetricType=o.VectorMetricType;exports.CreatedAt=B;exports.Field=z;exports.PartitionKey=M;exports.PrimaryKey=k;exports.Table=N;exports.UpdatedAt=G;exports.createOTSClient=X;exports.initTables=Z;
@@ -0,0 +1,4 @@
1
+ export * from './decorators';
2
+ export * from './types';
3
+ export { createOTSClient } from './client';
4
+ export { initTables } from './init';