@questwork/q-utilities 0.1.33 → 0.1.34

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.
@@ -1,12 +1,4841 @@
1
- var Bn=Object.defineProperty;var Un=(f,S,I)=>S in f?Bn(f,S,{enumerable:!0,configurable:!0,writable:!0,value:I}):f[S]=I;var Nt=(f,S,I)=>Un(f,typeof S!="symbol"?S+"":S,I);(function(f){"use strict";function S({allowCoordinator:n,allowOwner:e,query:t={},required:r,user:i}){if(!i)throw new Error("Require login.");i.permission;const s=i.permission.getScopes(r||{})||[];!s||s.length,s.includes("*")||(t.tenantCode=i.tenantCode),s.includes("TENANT")||(t.eventShortCode=i.eventShortCode),n&&t.registrationGroupCode&&i.myManagedRegistrationGroupCodes.includes(t.registrationGroupCode)?t.__ALLOW_COORDINATOR=!0:s.includes("EVENT")||(t.eventRegistrationCode=i.eventRegistrationCode),e&&(t.__ALLOW_OWNER=!0);const a=i.getExcludedFields(r);return a.length>0&&(t.__EXCLUDED_FIELDS=a),t.__LOGIN_SUBJECT_CODE=i.loginSubjectCode,t}function I(n,e){const t=new Date(n),r=e?new Date(e):new Date;if(isNaN(t.getTime())||isNaN(r.getTime())||t>r)return null;let i=r.getFullYear()-t.getFullYear();const s=r.getMonth()-t.getMonth();return(s<0||s===0&&r.getDate()<t.getDate())&&i--,i}function ie(n,{source:e,target:t}){return n.meta?((!n.meta.creator||n.meta.creator===e.getId())&&(n.meta.creator=t.getId()),(!n.meta.owner||n.meta.owner===e.getId())&&(n.meta.owner=t.getId())):((!n.creator||n.creator===e.getId())&&(n.creator=t.getId()),(!n.owner||n.owner===e.getId())&&(n.owner=t.getId())),n}function z(n){return n!=null&&typeof n!="boolean"&&String(n).trim()!==""&&!isNaN(Number(n))}function _(n,e){let t=n,r=e;if(typeof n=="string"&&(t=t.split(".")),!Array.isArray(n)&&typeof n=="object"){const{keys:s,obj:a}=n;t=s,r=a}if(t.length===0)return r;const i=t.shift();return r&&Object.prototype.hasOwnProperty.call(r,i)?_(t,r[i]):r&&i?t.length>0?_(t,r[i]):r[i]:r}function Dt(n){const e={};for(const[t,r]of Object.entries(n)){const i=t.match(/^(.*?)\|(boolean|date|html|number|string)$/);let s=t,a=null;i&&(s=i[1],a=i[2]);const o=s.split(".");let u=e;for(let c=0;c<o.length-1;c++){const d=o[c];(!u[d]||typeof u[d]!="object")&&(u[d]={}),u=u[d]}const l=o[o.length-1];if(a==="boolean")r===1||r==="1"||r===!0||r==="true"||r==="TRUE"?u[l]=!0:r===0||r==="0"||r===!1||r==="false"||r==="FALSE"?u[l]=!1:u[l]=!!r;else if(a==="number")u[l]=Number(r)||0;else if(a==="date")u[l]=new Date(r);else if(a==="html")if(r&&typeof r=="string"){let c=[];r.includes(`
2
-
3
- `)||r.includes(`\r
4
- \r
5
- `)?c=r.split(/\r?\n\s*\r?\n/).filter(d=>d.trim()!==""):c=r.split(/\r?\n/).filter(d=>d.trim()!==""),c.length>0?u[l]=c.map(d=>`<div>${d.trim()}</div>`).join(""):u[l]=r?`<div>${r}</div>`:""}else u[l]=r?`<div>${r.toString()}</div>`:"";else if(r==null)u[l]="";else if(typeof r=="number")u[l]=r;else if(typeof r=="string"&&r.trim()!==""){const c=r.trim();/^-?\d+$/.test(c)?u[l]=Number.parseInt(c,10):/^-?\d+\.\d+$/.test(c)?u[l]=Number.parseFloat(c):u[l]=r}else u[l]=(r==null?void 0:r.toString())||""}return e}function Mt(n,e){return e.split(".").reduce((r,i)=>{if(i.endsWith("[]")){const s=i.slice(0,-2);return Array.isArray(r[s])?r[s]:[]}if(i.includes("[")&&i.includes("]")){const s=i.match(/(\w+)\[(\d+)\]/);if(s){const a=s[1],o=s[2];return r&&r[a]&&r[a][o]}}else return r&&Array.isArray(r)?r.map(s=>s[i]):r&&r[i]},n)}function jt(n,e){return e.split(".").reduce((t,r)=>t&&t[r]!==void 0?t[r]:void 0,n)}function kt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp)&&Object.prototype.toString.call(n)==="[object Object]"}function se(n,...e){if(!e.length)return n;const t=e.shift();if(ae(n)&&ae(t))for(const r in t)ae(t[r])?(n[r]||(n[r]={}),se(n[r],t[r])):n[r]=t[r];return se(n,...e)}function xt(n,e,t){const r=e.split(".");let i=n;for(let o=0;o<r.length-1;o++){const u=r[o];let l,c;const d=u.match(/^(\w+)\[(\d+)\]$/);if(d){for(l=d[1],c=Number.parseInt(d[2],10),(!i[l]||!Array.isArray(i[l]))&&(i[l]=[]);i[l].length<=c;)i[l].push(void 0);i[l][c]==null&&(i[l][c]={}),i=i[l][c]}else i[u]||(i[u]={}),i=i[u]}const s=r[r.length-1],a=s.match(/^(\w+)\[(\d+)\]$/);if(a){const o=a[1],u=Number.parseInt(a[2],10);for((!i[o]||!Array.isArray(i[o]))&&(i[o]=[]);i[o].length<=u;)i[o].push(void 0);i[o][u]=t}else i[s]=t}function ae(n){return n&&typeof n=="object"&&!Array.isArray(n)}const b={expandDotNotation:Dt,get:Mt,getNestedValue:jt,isPlainObject:kt,merge:se,set:xt};class E{constructor(e={}){e=e||{},this.key=e.key||null,this.value=typeof e.value<"u"?e.value:""}static init(e={}){if(e instanceof this)return e;const t=new this(e);return t.isValid?t:null}static initFromArray(e=[]){return Array.isArray(e)?e.map(t=>this.init(t)):[]}static initOnlyValidFromArray(e=[]){return this.initFromArray(e).filter(t=>t)}static get _classname(){return"KeyValueObject"}static get _superclass(){return"KeyValueObject"}static addItem(e,t,r){e.push(this.init({key:t,value:r}))}static addRecord(e=[],t,r){return this.hasKeyValue(e,t,r)||e.push(this.init({key:t,value:r})),e}static appendRecord(e=[],t,r){return e.map(i=>(this.sameKey(i,t)&&(i.value=[...i.value,...r]),i))}static appendValueArray(e=[],t,r){return e.map(i=>(this.sameKey(i,t)&&(i.value=[...i.value,...r]),i))}static foundByKey(e=[],t){return e.find(i=>this.sameKey(i,t))||null}static foundValueByKey(e=[],t){const r=this.foundByKey(e,t);return r?r.value:null}static fromObject(e={}){return Object.keys(e).reduce((t,r)=>(t.push(this.init({key:r,value:e[r]})),t),[])}static getValueByKey(e=[],t){return this.foundValueByKey(e,t)}static getMetadataValueByKeyAsArray(e=[],t){const r=this.getValueByKey(e,t);return r?b.isPlainObject(r)?Object.keys(r).reduce((i,s)=>(i.push({key:s,value:r[s]}),i),[]):r:[]}static getValueByKeyFromArray(e=[],t){if(e.length===0)return null;const i=e.shift().find(s=>this.sameKey(s,t));return i&&i.value?i.value:this.getValueByKeyFromArray(e,t)}static getValuesByKey(e=[],t){return e.reduce((r,i)=>(this.sameKey(i,t)&&r.push(i.value),r),[])}static hasKeyValue(e=[],t,r){return typeof r>"u"?e.filter(i=>this.sameKey(i,t)).length>0:e.filter(i=>this.sameKey(i,t)&&ve(i.value,r)).length>0}static insertOrUpdateRecord(e=[],t,r){let i=[...e];return this.hasKeyValue(e,t)?i=this.updateRecord(e,t,r):i.push(this.init({key:t,value:r})),i}static keys(e=[]){return Array.isArray(e)?e.reduce((t,r)=>(t.push(r.key),t),[]):[]}static mapToKeyValue(e=[],t="key",r="value"){return Array.isArray(e)?e.reduce((i,s)=>{if(s&&typeof s=="object"){const a=b.get(s,t),o=b.get(s,r);a!=null&&i.push(this.init({key:a,value:o!==void 0?o:""}))}return i},[]):[]}static merge(e,t){return(t||[]).map(r=>{const i=e.find(s=>s.key===r.key);i?i.value=Ft(r.value,i.value):e.push(r)}),e}static removeByKey(e,t){return e.reduce((r,i)=>(this.sameKey(i,t)||r.push(i),r),[])}static removeByKeys(e,t){return e.reduce((r,i)=>(t.includes(i.key)||r.push(i),r),[])}static sameKey(e,t){return e?ve(e.key,t):!1}static toObject(e=[]){return Array.isArray(e)?e.reduce((t,r)=>(t[r.key]=r.value,t),{}):{}}static toString(e=[],t="; "){return Array.isArray(e)?e.reduce((r,i)=>(r.push(`${i.key}: ${i.value}`),r),[]).join(t):""}static updateRecord(e=[],t,r){return e.map(i=>this.sameKey(i,t)?{...i,value:r}:i)}static updateOrInsertRecord(e=[],t,r){return this.insertOrUpdateRecord(e,t,r)}static updateRecordsFromArray(e=[],t=[]){if(Array.isArray(e)&&Array.isArray(t)){const r=this.toObject(e),i=this.toObject(t);return this.fromObject({...r,...i})}return[]}static values(e=[]){return Array.isArray(e)?e.reduce((t,r)=>(t.push(r.value),t),[]):[]}get isValid(){return!!this.key}get toObject(){const e={};return this.isValid&&(e[this.key]=this.value),e}}function Ft(n,e){return n===void 0?e:Array.isArray(n)&&Array.isArray(e)?[...new Set([...n,...e])]:typeof n=="object"&&typeof e=="object"&&!Array.isArray(n)&&!Array.isArray(e)?{...n,...e}:e}function ve(n,e){return n===e}function C(n,e,t=Pt,r=E){if(!n)return!0;if(typeof t!="function"||r&&typeof r!="function")return!1;const{key:i="",value:s,placeholder:a,keyValuePath:o=""}=n,[u]=Object.keys(s);if(!i&&typeof a>"u")switch(u){case"$and":return s.$and.reduce((c,d)=>c&&C(d,e,t,r),!0);case"$or":return s.$or.reduce((c,d)=>c||C(d,e,t,r),!1);default:return!1}let l=typeof a>"u"?t(i,e):a;if(o){const c=r.toObject(l);l=t(o,c)}switch(u){case"$after":{if(z(s==null?void 0:s.$after)){const c=Number(String(s==null?void 0:s.$after));return Date.now()>c}return!1}case"$before":{if(z(s==null?void 0:s.$before)){const c=Number(String(s==null?void 0:s.$before));return Date.now()<c}return!1}case"$empty":return l==null===s.$empty;case"$eq":return l===s.$eq;case"$gt":return l>s.$gt;case"$gte":return l>=s.$gte;case"$hasOverlap":return Lt(l,s.$hasOverlap);case"$lt":return l<s.$lt;case"$lte":return l<=s.$lte;case"$in":return Array.isArray(l)?!!l.find(c=>s.$in.includes(c)):typeof l!="object"?!!s.$in.includes(l):!1;case"$includes":return Array.isArray(l)?l.includes(s.$includes):!1;case"$intervalTimeGt":{const c=new Date().getTime(),d=new Date(l).getTime();return c-d>s.$intervalTimeGt}case"$intervalTimeLt":{const c=new Date().getTime(),d=new Date(l).getTime();return c-d<s.$intervalTimeLt}case"$inValue":{const c=t(s.$inValue,e),d=Array.isArray(c)?c:[];return Array.isArray(l)?!!l.find(m=>d.includes(m)):typeof l=="string"?!!d.includes(l):!1}case"$isToday":{const c=new Date,d=c.setHours(0,0,0,0),m=c.setHours(23,59,59,59),h=new Date(l).getTime();return(d<=h&&m>=h)===s.$isToday}case"$ne":return l!==s.$ne;case"$notIn":return Array.isArray(l)?!l.find(c=>s.$notIn.includes(c)):typeof l!="object"?!s.$notIn.includes(l):!1;case"$notInValue":{const c=t(s.$notInValue,e),d=Array.isArray(c)?c:[];return Array.isArray(l)?!l.find(m=>d.includes(m)):typeof l!="object"?!d.includes(l):!1}case"$range":{const[c,d]=s.$range;return typeof c=="number"&&typeof d=="number"&&l>=c&&l<=d}default:return!1}}function Pt(n,e){return _(n.split("."),e)}function Lt(n,e){let t=n,r=e;typeof t=="string"&&(t=t.split(",")),typeof r=="string"&&(r=r.split(","));const i=new Set(t);return r.find(s=>i.has(s))}function oe(n,e){const t=n&&n instanceof Date?n:new Date(n),r=["日","一","二","三","四","五","六"],i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=e||"YYYY/MM/DD hh:mm",o=t.getDay(),u=s[o],l=r[o],c=i[o],d=t.getFullYear(),m=t.getMonth()+1,h=t.getDate(),g=t.getHours(),v=t.getMinutes(),D=t.getSeconds();return a.replace("YYYY",d).replace("MM",$(m)).replace("MM",$(m)).replace("DD",$(h)).replace("hh",$(g)).replace("mm",$(v)).replace("ss",$(D)).replace("M",m).replace("D",h).replace("h",g).replace("m",v).replace("s",D).replace("EEEE",$(c)).replace("EEE",$(l)).replace("EE",$(u)).replace("E",$(o))}function $(n){return n<10?`0${n}`:n}const p={argumentEmptyException:"Argument is empty",argumentFormatException:"Incorrect number or format of argument",invalidFuntionException:"Function Name is invalid",invalidRegExpException:"Invalid regular expression",isNotAFunctionException:"Is not a function",notExistException:"Key does not exist",resultEmptyException:"Result is empty",resultMoreThanOneException:"More than one result"};class y extends Error{constructor(e){super(e),this.message=e}}const Vt="_EMPTY",Oe=["concatIf","divide","eq","exec","filterAll","filterOne","formatDate","get","gt","gte","isEmpty","isNotEmpty","join","lt","lte","map","neq","removeHtml","replaceChar","sum","toLowerCase","toUpperCase"],Re="_HIDE",Bt="_NOT_EMPTY",w="_SELF",Ut=["<%=","%>"],Kt=["{{","}}"];function Te(n,e){if(typeof n!="string")throw new y(`_concatIf: ${p.argumentFormatException}: the data must be string :${n.join(", ")}`);if(e.length!==3)throw new y(`_concatIf: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;const[t,r,i]=e;if([Vt,Bt].includes(t)||r.length!==2)throw new y(`concatIf: ${p.argumentEmptyException}: ${t}, ${r}`);return n===""&&i.includes(Re)?"":n!==""&&(n!==null||n!==void 0)&&i.includes(Re)?`${r[0]}${n}${r[r.length-1]}`:i}function Ie(n,e){try{return Number.isNaN(n)?n:n/e}catch(t){throw t}}function Ne(n,e){if(e.length!==3)throw new y(`eq: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n===t?e[1]:e[2]}function Ht(n,e){try{const[t,...r]=e;return n[t](...r)}catch(t){throw t}}function le(n,e){try{if(!Array.isArray(e)||e.length===0)throw new y(p.argumentEmptyException);return!Array.isArray(n)||n.length===0?[]:typeof n[0]=="object"?De(n,e):typeof n[0]=="string"||typeof n[0]=="number"?Wt(n,e):[]}catch(t){throw t}}function Wt(n,e){const t=e.flat();return n.filter(r=>t.some(i=>Me(i,r)))}function De(n,e){if(e.length===1){const s=e[0];return n.filter(a=>s.includes(".")?_(s.split("."),a):Object.prototype.hasOwnProperty.call(a,s))}if(e.length>2){let s=n;for(let a=0;a<e.length;a+=2){const o=[e[a],e[a+1]];s=De(s,o)}return s}const[t,...r]=e,i=r.flat();return n.filter(s=>{const a=t.includes(".")?_(t.split("."),s):s[t];return i.some(o=>Me(o,a))})}function Me(n,e){if(n===void 0&&e===void 0||n===null&&e===null)return!0;if(typeof n=="boolean")return n===e;if(n===""||n==="*")return e==null?!1:typeof e=="string"?n===""?e==="":e!=="":Array.isArray(e)?n===""?e.length===0:e.length!==0:n!=="";if(Yt(n))return n===e;if(n.startsWith("[")&&n.endsWith("]"))return n==="[]"?Array.isArray(e)&&e.length===0:n==="[*]"?Array.isArray(e)&&e.length!==0:!1;const{operator:t,value:r}=qt(n);if(!t||r!==0&&!r)return!1;switch(t){case">":return e>r;case"<":return e<r;case"!=":return e!==r;case">=":return e>=r;case"<=":return e<=r;default:return!1}}function Yt(n){return typeof n=="string"?!(n.startsWith("[")&&n.endsWith("]")||/!=|>=|<=|>|</.test(n)):!Number.isNaN(n)}function qt(n){const t=["!=",">=","<=",">","<"].find(s=>n.startsWith(s));if(!t)return{operator:null,value:null};const r=n.slice(t.length);if(/^[a-z]*$/i.test(r)&&t!=="!=")return{operator:null,value:null};const i=!Number.isNaN(Number.parseFloat(r))&&!Number.isNaN(r)?Number(r):r;return{operator:t,value:i}}function zt(n,e){try{const t=le(n,e);if(t.length===1)return t[0];if(t.length===0)return null;throw new y(p.resultMoreThanOneException)}catch(t){throw t}}function je(n,e){if(e.length===0)throw new y(`_formateDate: ${p.argumentFormatException}: format parts must be not empty array`);if(n==null)return null;const t=new Date(n),r={yyyy:String(t.getFullYear()),mm:String(t.getMonth()+1).padStart(2,"0"),dd:String(t.getDate()).padStart(2,"0")},i=["yyyy","mm","dd"];if(e.filter(a=>a.length>1&&!i.includes(a)).length>0)throw new y(`_formateDate: ${p.argumentFormatException}: the format type is not valid: ${e.join(", ")}`);return e.reduce((a,o)=>a+(r[o]||o),"")}function G(n,e,t=null){try{if(e===null||typeof e>"u"||e==="")throw new y(p.argumentEmptyException);if(n===null)return null;if(e.includes(".")){const r=e.split(".");if(r.length>1){const i=r.shift(),s=r.join(".");return typeof n[i]<"u"?G(n[i],s,t):ke(e,t)}}return typeof n[e]<"u"?n[e]:ke(e,t)}catch(r){throw r}}function ke(n,e){return e!==null?e:null}function xe(n,e){if(e.length!==3)throw new y(`_gt: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n>t?e[1]:e[2]}function Fe(n,e){if(e.length!==3)throw new y(`_gte: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n>=t?e[1]:e[2]}function Pe(n,e){if(e.length!==2)throw new y(`_isEmpty: ${p.argumentFormatException}: ${e.join(", ")}`);return e.includes(w)&&(e=e.map(t=>t===w?n:t)),n!==null&&typeof n=="object"&&Object.keys(n).length===0||n===""||n===null||n===void 0||n.length===0?e[0]:e[1]}function Le(n,e){if(e.length!==2)throw new y(`_isNotEmpty: ${p.argumentFormatException}: ${e.join(", ")}`);return e.includes(w)&&(e=e.map(t=>t===w?n:t)),n!==null&&typeof n=="object"&&Object.keys(n).length===0||Array.isArray(n)&&n.length===0||typeof n=="string"&&n===""||n==null?e[1]:e[0]}function Ve(n,e){try{return n.length===0?"":n.length===1?Be(n[0]):n.map(t=>Be(t)).join(e)}catch(t){throw t}}function Be(n){return JSON.stringify(n).replace(/"([^"]+)":/g,"$1: ").replace(/"([^"]+)"/g,"$1").replace(/,/g,", ")}function Ue(n,e){if(e.length!==3)throw new y(`_lt: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n<t?e[1]:e[2]}function Ke(n,e){if(e.length!==3)throw new y(`_lte: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n<=t?e[1]:e[2]}function He(n,e){try{if(e.length===0)throw new y(p.argumentEmptyException);return n===null||typeof n>"u"?null:n.reduce((r,i)=>{e.length===1&&Array.isArray(e[0])&&(e=e[0],r.hasFormat=!0);const s=e.map(a=>{if(a.includes(".")){const o=a.split("."),u=o[0];o.shift();const l=o.join(".");return G(i[u],l)}return typeof i[a]<"u"?i[a]:null});return r.hasFormat?r.content.push(s):r.content=r.content.concat(s),r},{content:[],hasFormat:!1}).content}catch(t){throw t}}function We(n,e){if(e.length!==3)throw new y(`_neq: ${p.argumentFormatException}: ${e.join(", ")}`);if(n===null||typeof n>"u")return null;e.includes(w)&&(e=e.map(r=>r===w?n:r));const t=e[0];return n!==t?e[1]:e[2]}function Ye(n,e){if(n==null)return null;if(!Array.isArray(e))throw new y(`_removeHtml: ${p.argumentFormatException}: args parts must be array`);return Gt(n,e[0])}function Gt(n,e=`
6
- `){typeof e!="string"&&(e=`
7
- `);let r=n.replace(/&nbsp;/g," ").replace(/\s+/g," ").replace(/<\/?(p|div|h[1-6]|ul|ol|li|pre|section|article|table|tr|td|th)(\s[^>]*)?>/gi,"~~~").replace(/<br\s*\/?>/gi,"~~~").replace(/<[^>]+>/g,"").replace(/~{3,}/g,e).trim();return e===""?r=r.replace(/\s+/g," "):(r=r.replace(new RegExp(`${ue(e)}+`,"g"),e),r=r.replace(new RegExp(`^${ue(e)}|${ue(e)}$`,"g"),"")),r}function ue(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qe(n,e){if(n==null)return null;if(!Array.isArray(e))throw new y(`_replaceChar: ${p.argumentFormatException}: args parts must be array`);return Jt(n,e[0],e[1])}function Jt(n,e,t){return!n||!e?n:n.replace(new RegExp(e,"g"),t)}function ze(n,e){return Number.isNaN(n)||n===null||typeof n>"u"||n===""?n:e.reduce((t,r)=>t+r,n)}function Ge(n,e){if(e!==void 0)throw new y(`_toLowerCase: ${p.argumentFormatException}: ${e.join(", ")}`);return n===null||typeof n>"u"||typeof n!="string"?null:String(n).toLowerCase()}function Je(n,e){if(typeof n!="string")throw new y(`_toUpperCase: ${p.argumentFormatException}: the data must be string: ${n}`);if(e!==void 0)throw new y(`_toUpperCase: ${p.argumentFormatException}: the argument must be empty: ${e.join(", ")}`);return n===null||typeof n>"u"||typeof n!="string"?null:String(n).toUpperCase()}class ce{constructor(e){this.data=e}static init(e){return new this(e)}static initFromArray(e=[]){return Array.isArray(e)?e.map(t=>this.init(t)):[]}static initOnlyValidFromArray(e=[]){return this.initFromArray(e).filter(t=>t)}static concatIf(e,t){return Te(e,t)}static divide(e,t){return Ie(e,t)}static eq(e,t){return Ne(e,t)}static filterAll(e,t){return le(e,t)}static formatDate(e,t){return je(e,t)}static get(e,t,r=null){return G(e,t,r)}static gt(e,t){return xe(e,t)}static gte(e,t){return Fe(e,t)}static isEmpty(e,t){return Pe(e,t)}static isNotEmpty(e,t){return Le(e,t)}static join(e,t=""){return Ve(e,t)}static lt(e,t){return Ue(e,t)}static lte(e,t){return Ke(e,t)}static map(e,t=[]){return He(e,t)}static neq(e,t){return We(e,t)}static removeHtml(e,t){return Ye(e,t)}static replaceChar(e,t){return qe(e,t)}static sum(e,t){return ze(e,t)}static toLowerCase(e,t){return Ge(e,t)}static toUpperCase(e,t){return Je(e,t)}static parseFunction(e){return Ze(e,Oe)}static parseParams(e){return Xe(e)}pipe(e=""){this.delimiters=e.substring(0,2)==="{{"?Kt:Ut;const t=new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`),r=e.match(t);if(r!==null)try{return Ze(r[1],Oe).reduce((s,a)=>en(s,a.name,a.args),this.data)}catch(i){throw new y(`TemplateCompiler engine error: ${i.message}`)}throw new y(`TemplateCompiler engine error: ${p.invalidRegExpException}`)}}function Ze(n,e){const t=/(\w+)\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)/;let r;if(n.includes("|")){r=[];let i="",s=0,a=null;for(let o=0;o<n.length;o++){const u=n[o];if((u==='"'||u==="'")&&(o===0||n[o-1]!=="\\")){a===u?a=null:a===null&&(a=u),i+=u;continue}a===null&&(u==="("?s++:u===")"&&s--),u==="|"&&s===0&&a===null?(r.push(i),i=""):i+=u}i&&r.push(i)}else r=[n];return r.reduce((i,s)=>{const a=s.match(t);if(a!==null){const o=a[1],u=a[2],l=Xe(u);if(e.includes(o))i.push({name:o,args:l});else throw new y(`${o} is not a valid function`)}return i},[])}function Xe(n){const e=n.trim();return e?e.includes(",")?Zt(e).map(r=>fe(r.trim())):[fe(e)]:[]}function Zt(n){const e=[];let t="",r=0,i=0,s=null;for(let a=0;a<n.length;a++){const o=n[a];if((o==='"'||o==="'")&&(a===0||n[a-1]!=="\\")){s===o?s=null:s===null&&(s=o),t+=o;continue}if(s!==null){t+=o;continue}o==="["?r++:o==="]"?r--:o==="("?i++:o===")"&&i--,o===","&&s===null&&r===0&&i===0?(e.push(t),t=""):t+=o}return t&&e.push(t),e}function fe(n){if(typeof n!="string")return n;const e=n.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.substring(1,e.length-1);const t=Qt(e);return typeof t!="string"?t:e.startsWith("[")&&e.endsWith("]")?Xt(e):n}function Xt(n){const e=n.substring(1,n.length-1).trim();if(!e)return[];const t=[];let r="",i=null;for(let s=0;s<e.length;s++){const a=e[s];if((a==='"'||a==="'")&&(s===0||e[s-1]!=="\\")){i===a?i=null:i===null&&(i=a),r+=a;continue}a===","&&i===null?(r.trim()&&t.push(r.trim()),r=""):r+=a}return r.trim()&&t.push(r.trim()),t.map(s=>fe(s))}function Qt(n){if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.substring(1,n.length-1);if(n==="true")return!0;if(n==="false")return!1;if(n!=="undefined")return n==="null"?null:!Number.isNaN(n)&&!Number.isNaN(Number.parseFloat(n))?Number(n):n}function en(n,e,t){try{let r;switch(e){case"concatIf":return Te(n,t);case"divide":return Ie(n,t);case"eq":return Ne(n,t);case"exec":return Ht(n,t);case"filterAll":return le(n,t);case"filterOne":return zt(n,t);case"formatDate":return je(n,t);case"get":if(t.length>2)throw new y(p.argumentFormatException);return t.length===2&&(r=t[t.length-1]),G(n,t[0],r);case"gt":return xe(n,t);case"gte":return Fe(n,t);case"isEmpty":return Pe(n,t);case"isNotEmpty":return Le(n,t);case"join":return Ve(n,t[0]);case"lt":return Ue(n,t);case"lte":return Ke(n,t);case"map":return He(n,t);case"neq":return We(n,t);case"removeHtml":return Ye(n,t);case"replaceChar":return qe(n,t);case"sum":return ze(n,t);case"toLowerCase":return Ge(n);case"toUpperCase":return Je(n);default:throw new Error(`${e} is not a valid function`)}}catch(r){throw r}}function J(n,e){return n.reduce((t,r)=>{const{type:i,value:s="",restriction:a,template:o,format:u,showMinutes:l}=r;switch(i){case"array":{if(C(a,e,_)){const c=_(s.split("."),e)||[];t+=c.reduce((d,m)=>d+=J(o,m),"")}break}case"date":{if(C(a,e,_)){const c=_(s.split("."),e)||"";t+=oe(c,u).toString()}break}case"ellipsis":{if(C(a,e,_)){const{maxLength:c}=r,d=_(s.split("."),e)||"";d.length<=c?t+=d.toString():t+=`${d.substr(0,c)}...`}break}case"group":{if(C(a,e,_))return J(s,e);break}case"label":{C(a,e,_)&&(t+=s.toString());break}case"templateCompiler":{if(C(a,e,_)){const c=new ce({data:e});t+=c.pipe(s)}break}case"value":{if(C(a,e,_)){const c=_(s.split("."),e)||"";t+=c.toString()}break}}return t},"")}function Qe(n,e=/\$\{(.+?)\}/g,t,r){if(!n)return"";const i=typeof r=="function"?r:_,s=new RegExp(e,"g");return n.replace(s,(a,o)=>{const u=i({keys:o.split("."),obj:t});return u==null?"":typeof u=="object"?JSON.stringify(u):u})}function tn(n,e=0){try{if(typeof n=="number")return n.toString().length===10&&(n=n*1e3),new Date(n);if(typeof n=="string"&&n.length===8){const t=Number.parseInt(n.slice(0,4),10),r=Number.parseInt(n.slice(4,6),10)-1,i=Number.parseInt(n.slice(6,8),10);return new Date(t,r,i)}return new Date(n)}catch{throw new Error("input does not meet the requirements")}}class V{constructor({date:e,isUTC:t,is24Hour:r,timezoneOffset:i=0}={}){this.date=e,this.isUTC=t,this.is24Hour=r,this.timezoneOffset=i}getDateComponent(e){if(this.timezoneOffset!==0){const t=this.timezoneOffset*60*1e3;return new Date(this.date.getTime()+t)[`getUTC${e}`]()}else return this.isUTC?this.date[`getUTC${e}`]():this.date[`get${e}`]()}process(e){return e}}function k(n,e="0"){if(typeof n!="number")throw new TypeError("Parameter must be of number");return n<10?`${e}${n}`:n}class nn extends V{process(e){const t=this.getDateComponent("Date");return e=e.replace("DD",k(t)),e}}const rn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];class sn extends V{process(e){const t=this.getDateComponent("Month");return e=e.replace("MMM",rn[t]),e=e.replace("MM",k(t+1)),e}}class an extends V{process(e){const t=this.getDateComponent("FullYear");return e=e.replace("yyyy",t),e=e.replace("YYYY",t),e=e.replace("yy",t.toString().slice(-2)),e=e.replace("YY",t.toString().slice(-2)),e}}class on extends V{process(e){let t=this.getDateComponent("Hours");const r=!this.is24Hour;if(r&&t>12&&(t-=12),r&&t===0&&(t=12),e=e.replace("HH",k(this.getDateComponent("Hours"))),e=e.replace("hh",k(t)),this.is24Hour)e=e.replace(/\s*\bA\b\s*/g," "),e=e.replace(/\s*\ba\b\s*/g," "),e=e.replace(/\s+/g," ").trim();else{if(e.includes("A")){const i=this.getDateComponent("Hours")>=12?"PM":"AM";e=e.replace(/\bA\b/g,i)}if(e.includes("a")){const i=this.getDateComponent("Hours")>=12?"pm":"am";e=e.replace(/\ba\b/g,i)}}return e=e.replace("mm",k(this.getDateComponent("Minutes"))),e=e.replace("ss",k(this.getDateComponent("Seconds"))),e}}class ln extends V{process(e){if(e.includes("Z"))if(this.isUTC)e=e.replace("Z","+0000");else{const t=this.date.getTimezoneOffset(),r=t>0?"-":"+",i=Math.abs(t),s=Math.floor(i/60),a=i%60,o=`${r}${s.toString().padStart(2,"0")}${a.toString().padStart(2,"0")}`;e=e.replace("Z",o)}if(e.includes("ddd")){const t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],r=this.getDateComponent("Day");e=e.replace("ddd",t[r])}if(e.includes("dd")){const t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],r=this.getDateComponent("Day");e=e.replace("dd",t[r])}return e}}function un({date:n,format:e,isUTC:t,is24Hour:r,timezoneOffset:i=0}){return[ln,nn,sn,an,on].reduce((s,a)=>new a({date:n,isUTC:t,is24Hour:r,timezoneOffset:i}).process(s),e)}function et(n,e){const t=e||"YYYY/MM/DD hh:mm",r=t.includes("HH");let i=null;if(t.includes("Z"))i=0;else if(t.includes("+")){const a=t.match(/[+-]\d{2}:?\d{2}/);if(a){const o=a[0],u=o[0]==="+"?1:-1,l=parseInt(o.slice(1,3),10),c=o.includes(":")?parseInt(o.slice(4,6),10):parseInt(o.slice(3,5),10);i=u*(l*60+c)}}const s=tn(n,i===null?0:i);return un({date:s,format:t,isUTC:i!==null,is24Hour:r,timezoneOffset:i===null?0:i})}function tt(n,e={}){const{preserveBasicWhitespace:t=!0,removeNewlines:r=!1}=e;if(typeof n!="string")return{hasControlChars:!1,matches:[],inputType:typeof n,message:"Input is not a string"};const i=[];let s;return t&&!r?s=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g:s=/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,n.replace(s,(a,o)=>(i.push({character:a,code:a.charCodeAt(0),hex:"0x"+a.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0"),position:o,context:cn(n,o,10)}),"")),{hasControlChars:i.length>0,matches:i,totalFound:i.length,inputPreview:n.length>50?n.substring(0,50)+"...":n,inputLength:n.length,optionsUsed:{preserveBasicWhitespace:t},regexPattern:s.toString()}}function cn(n,e,t=10){const r=Math.max(0,e-t),i=Math.min(n.length,e+t+1);let s=n.substring(r,i);return s=s.replace(/[\x00-\x1F\x7F-\x9F]/g,a=>"\\u"+a.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0")),s}function nt(n){console.log("=== Control Character Detection Report ==="),console.log(`Input: "${n.inputPreview}" (${n.inputLength} chars)`),console.log(`Options: preserveBasicWhitespace = ${n.optionsUsed.preserveBasicWhitespace}`),console.log(`Regex pattern: ${n.regexPattern}`),console.log(`Control characters found: ${n.totalFound}`),n.hasControlChars?(console.log(`
8
- 📋 Matches found:`),n.matches.forEach((e,t)=>{console.log(`
9
- ${t+1}. Character: ${JSON.stringify(e.character)}`),console.log(` Code: ${e.code} (${e.hex})`),console.log(` Position: ${e.position}`),console.log(` Context: "...${e.context}..."`)})):console.log("✅ No control characters detected in Phase 1 range"),console.log("=== End Report ===")}function rt(n,e){n=n||{},e=e||{};const{firstName:t,middleName:r,noFirstName:i,prefix:s,title:a,upperCaseLastName:o=!0}=e;e.hasAsianCharacters=!1;let u=[];if((s||a)&&n.prefix){const c=de(e);u=c(u,n.prefix),u=c(u,n.title)}if(t!==!1&&!i){const c=de(e);u=c(u,n.firstName),u=c(u,n.givenName)}r===!0&&n.middleName&&(e.hasAsianCharacters=e.hasAsianCharacters||it(n.middleName.toString()),u.push(n.middleName.toString()));const l=de(e,o);return u=l(u,n.lastName),u=l(u,n.familyName),u=l(u,n.surname),e.hasAsianCharacters?u.reverse().join(""):u.join(" ")}function de(n={},e=!1){let t=!1;return(r,i)=>{if(!t&&i){t=!0,n.hasAsianCharacters=n.hasAsianCharacters||it(i.toString());const s=e?i.toString().toUpperCase():i.toString();r.push(s)}return r}}function it(n){return/[\u3400-\u9FBF]/.test(n)}function st({dataUrl:n="",filename:e=""}={}){const t=document.createElement("a");t.download=e,t.href=n,document.body.appendChild(t),t.click(),document.body.removeChild(t)}function at(n){return String(n).replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}function fn({responseHelper:n,handler:e,ignoreError:t=!1}){return async(r,i,s)=>{const a=typeof i=="function"&&!s,o=a?r:null,u=a?r.request:r,l=a?r.response:i,c=a?i:s;try{return await e({req:u,res:l}),a?await c():c()}catch(d){if(t)return a?await c():c();if(!n){if(a)throw d;return c(d)}const m=d.status||400,h=d.message||"An error occurred",g=n.standardizeResponse({err:d,message:h});a?(o.status=m,o.body=g):l.status(m).json(g)}}}function dn({responseHelper:n,service:e}){return async(t,r,i)=>{try{const{query:s}=t,a=await e.findAll({query:s});r.locals.findAllResult=a,await i()}catch(s){r.status(400).json(n.standardizeResponse({err:s,message:s.message||s}))}}}function hn({responseHelper:n,service:e}){return async(t,r,i)=>{try{const{params:s,query:a}=t,{id:o}=s,u=await e.findOne({query:{...a,id:o}});r.locals.findOneResult=u,await i()}catch(s){r.status(400).json(n.standardizeResponse({err:s,message:s.message||s}))}}}function mn(n,{query:e={}}={}){!e.__EXCLUDED_FIELDS||Array.isArray(e.__EXCLUDED_FIELDS)&&e.__EXCLUDED_FIELDS.length===0||(n.push({$set:{__originalEmail:"$_eventRegistration.email",__originalPhone:"$_eventRegistration.phone",__queryArr:{$ifNull:[e.__EXCLUDED_FIELDS||[],[]]},__isMyself:{$eq:["$_eventRegistration.loginSubjectCode",e.__LOGIN_SUBJECT_CODE]},__isGroupCoordinator:!!e.__ALLOW_COORDINATOR,__hasEventRegistration:{$ne:["$_eventRegistration",null]}}}),n.push({$set:{__shouldShowEmail:{$and:["$__hasEventRegistration",{$or:["$__isMyself","$__isGroupCoordinator",{$not:{$in:["email","$__queryArr"]}}]}]},__shouldShowPhone:{$and:["$__hasEventRegistration",{$or:["$__isMyself","$__isGroupCoordinator",{$not:{$in:["phone","$__queryArr"]}}]}]}}}),n.push({$set:{"_eventRegistration.email":{$cond:["$__shouldShowEmail","$__originalEmail","$$REMOVE"]},"_eventRegistration.phone":{$cond:["$__shouldShowPhone","$__originalPhone","$$REMOVE"]}}}),n.push({$unset:["__originalEmail","__originalPhone","__isMyself","__isGroupCoordinator","__queryArr","__hasEventRegistration","__shouldShowEmail","__shouldShowPhone"]}))}function yn({responseHelper:n,service:e}){return async(t,r,i)=>{try{const{body:s}=t;let a;Array.isArray(s)?a=await e.saveAll({docs:s}):a=await e.saveOne({doc:s}),r.locals.postResult=a,await i()}catch(s){r.status(400).json(n.standardizeResponse({err:s,message:s.message||s}))}}}function pn({responseHelper:n,service:e}){return async(t,r,i)=>{try{const{body:s,params:a}=t,{id:o}=a;if(o!==s.id)throw new Error("id in params and body must be same");const{data:u}=await e.findOne({query:{id:o}}),l=u[0];l.update(s);const c=await e.saveOne({doc:l});r.locals.updateOneResult=c,await i()}catch(s){r.status(400).json(n.standardizeResponse({err:s,message:s.message||s}))}}}const ot={customHandler:fn,findAllResult:dn,findOneResult:hn,hideSensitiveFields:mn,postResult:yn,updateOneResult:pn};function lt(n){const e=/[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi,t=new Set;return n?(n.forEach(r=>{if(!(!r||typeof r!="string"||!r.trim()))try{const s=r.replace(/[\u200B-\u200D\uFEFF\u202A-\u202E]/g,"").replace(/[<>]/g," ").replace(/\s+/g," ").trim().match(e);s&&s.forEach(a=>t.add(a.toLowerCase()))}catch(i){console.warn("Failed to process entry:",r,i)}}),Array.from(t).sort((r,i)=>r.localeCompare(i))):[]}async function Z(n,e,t){return new Promise((r,i)=>{const s=n[Symbol.iterator]();let a=0;const o=async u=>{const l=s.next();if(l.done){r(u);return}try{const[c,d]=await Promise.all([u,l.value]);o(e(c,d,a++))}catch(c){i(c)}};o(t)})}class X{constructor(e){e=e||{},this.model=e.model,this._sharedOptions=e._sharedOptions,this._queryOptions=e._queryOptions,this._saveOptions=e._saveOptions,this._Class=e._constructor&&e._constructor._Class?e._constructor._Class:null}static init(e={}){return T(this,e)}static get _classname(){return"Repo"}static get _superclass(){return"Repo"}get _classname(){return"Repo"}get _superclass(){return"Repo"}get isValid(){return this.model&&typeof this.model.deleteOne=="function"&&typeof this.model.findAll=="function"&&typeof this.model.saveOne=="function"}get queryOptions(){return{...this._sharedOptions,...this._queryOptions}}get saveOptions(){return{...this._sharedOptions,...this._saveOptions}}init(e){return this._Class&&typeof this._Class.init=="function"?this._Class.init(e):e}async deleteOne({id:e}){try{return{...await this.model.deleteOne({_id:e}),isNew:!1,data:[]}}catch(t){throw t}}findAll({config:e={},query:t,systemLog:r}){const i=Q({systemLog:r,label:"REPO_READ",message:`fn ${this._classname}.prototype.findAll`,input:[{query:{...t},systemLog:{...r}}]}),s={...this.queryOptions,...e};return new Promise((a,o)=>{this.model.findAll(t,s,(u,l,c)=>{if(u)i({level:"warn",output:u.toString()}),o(u);else{const d={isNew:!1,data:l,total:c||l.length};i({level:"info",output:{...d}}),a(d)}})})}findOne({config:e={},query:t,systemLog:r}){const i=Q({systemLog:r,label:"REPO_READ",message:`fn ${this._classname}.prototype.findOne`,input:[{query:{...t},systemLog:{...r}}]}),s={...this.queryOptions,...e};return new Promise((a,o)=>{this.model.findAll(t,s,(u,l)=>{if(u)o(u);else if(l.length===1){const c={isNew:!1,data:l,total:1};i({level:"info",output:{...c}}),a(c)}else l.length===0?o(new Error("record not found")):o(new Error("more than one is found"))})}).catch(a=>{throw i({level:"warn",output:a.toString()}),a})}saveAll({config:e={},docs:t,systemLog:r}){let i;const s=Q({systemLog:r,label:"REPO_WRITE",message:`fn ${this._classname}.prototype.saveAll`,input:[{config:e,docs:[...t],systemLog:{...r}}]});return(typeof this.model.saveAll=="function"?this.model.saveAll({config:e,docs:t}):gn({config:e,docs:t,service:this})).then(o=>{o.length!==1&&(i=null);const u={data:o,isNew:i,total:o.length};return s({level:"info",output:{...u}}),u}).catch(o=>{throw s({level:"warn",output:o.toString()}),o})}saveOne({config:e={},doc:t,systemLog:r}){const i=Q({systemLog:r,label:"REPO_WRITE",message:`fn ${this._classname}.prototype.saveOne`,input:[{config:e,doc:{...t},systemLog:{...r}}]}),s={...this.saveOptions,...e};return new Promise((a,o)=>{this.model.saveOne(t,s,(u,l)=>{u?(i({level:"warn",output:u.toString()}),o(u)):(i({level:"info",output:{...l}}),a(l))})})}}function Q({systemLog:n,label:e,message:t,input:r}={}){return({level:i,messgae:s,output:a}={})=>{n&&n.systemLogHelper&&n.systemLogHelper.log({batchId:n.batchId,label:e,level:i,message:s||t,data:{payload:{input:r,output:a}}})}}async function gn({config:n={},docs:e,service:t}){let r=null;return n.session||t.saveOptions.session?r=await _e(e,async i=>{if(i){const s=await t.saveOne({config:n,doc:i});return(s._data||s.data)[0]}return null},{concurrency:1}):r=await Promise.all(e.map(async i=>{if(i){const s=await t.saveOne({config:n,doc:i});return(s._data||s.data)[0]}return null})),r}class he{constructor(e={}){e=e||{},this._data=e.data||e._data||[],this.err=e.err,this.isNew=e.isNew||!1,this.message=e.message,this.total=e.total||0,this._instanceBuilder=e._instanceBuilder}static init(e={}){return e instanceof this?e:new this(e)}static get _classname(){return"ApiResponse"}static get _superclass(){return"ApiResponse"}get data(){return this._instanceBuilder&&typeof this._instanceBuilder=="function"?this._data.map(this._instanceBuilder):this._data}}function N({repo:n,result:e}){return he.init({...e,_instanceBuilder:t=>n.init(t)})}class me{constructor({repo:e}){this.repo=e}static get _classname(){return"Service"}static get _superclass(){return"Service"}async deleteOne({id:e}){const t=await this.repo.deleteOne({id:e});return N({repo:this.repo,result:t})}async findAll({config:e={},query:t={},systemLog:r}={}){const i=await this.repo.findAll({config:e,query:t,systemLog:r});return N({repo:this.repo,result:i})}async findOne({config:e={},query:t={},systemLog:r}={}){const i=await this.repo.findOne({config:e,query:t,systemLog:r});return N({repo:this.repo,result:i})}init(e){return this.repo.init(e)}initFromArray(e=[]){return Array.isArray(e)?e.map(t=>this.init(t)):[]}initOnlyValidFromArray(e=[]){return this.initFromArray(e).filter(t=>t)}async saveAll({config:e={},docs:t=[],systemLog:r}={}){const i=t.map(a=>e.skipInit?a:this.init(a)),s=await this.repo.saveAll({config:e,docs:i,systemLog:r});return N({repo:this.repo,result:s})}async saveOne({config:e={},doc:t={},systemLog:r}={}){const i=e.skipInit?t:this.init(t);if(i){const s=await this.repo.saveOne({config:e,doc:i,systemLog:r});return N({repo:this.repo,result:s})}return{isNew:null,data:[],err:new Error("doc is not a valid instance")}}}function ye({repo:n}){if(n===void 0)throw new Error("repo is required.");if(n._superclass!==X._superclass)throw new Error("repo is not an instance of Repo.");return new me({repo:n})}async function ut({body:n={},GeneralModel:e,UniqueKeyGenerator:t,resourceInfo:r}){const{resources:i,data:s,globalShared:a={},shared:o={},relationship:u={}}=n,l=r||n.resourceInfo;return _n(s,a,o),await Z(i,async(d,m)=>{const h=An(m,l,t,e);wn(s,u[m],d);const g=s[m],v=await h.saveAll({docs:[].concat(g)});return d[m]=Array.isArray(g)?v._data:v._data[0],d},{})}function _n(n,e={},t={}){Object.keys(t).forEach(r=>{const i=n[r];Array.isArray(i)?n[r]=i.map(s=>b.merge({},s,e,t[r]||{})):n[r]=b.merge({},i,e,t[r]||{})})}function wn(n,e={},t){Object.keys(e).forEach(r=>{const i=e[r],s=b.get(t,i);b.set(n,r,s)})}function An(n,e,t,r){const{collectionName:i,fields:s}=e[n],a=t.makeGenerator(s),o=new r({collectionName:i,uniqueKeyGenerator:a});return ye({repo:new X({model:o})})}function pe(n,e,t,r,i){const s=i||E;return!Array.isArray(n)||n.length===0?null:n.reduce((a,o)=>{const{key:u,type:l,value:c,restriction:d}=o;if(r&&typeof r=="function"?r({rule:d,data:e}):!0){let h=c;switch(l){case"array":{h=c.map(g=>t({keys:g.value.split("."),obj:e}));break}case"fromKeyValue":{const{dataPath:g,key:v}=c,D=t({keys:g.split("."),obj:e});h=s.getValuesByKey(D,v)[0];break}case"toKeyValue":{const g=t({keys:c.split("."),obj:e});h=s.fromObject(g);break}case"nested":{h=pe(c,e,t,r);break}case"path":{h=t({keys:c.split("."),obj:e});break}case"orgin":{h=c;break}case"origin":{h=c;break}default:{h=c;break}}return u?{...a,[u]:h}:typeof h=="string"?h:{...a,...h}}return a},{})}function ct(n,e){return!e||typeof e!="string"?{}:n.reduce((t,r)=>(t[r[e]]||(t[r[e]]=0),t[r[e]]++,t),{})}function T(n,e){if(e instanceof n)return e;try{const t=new n(e);return t.isValid!==!1?t:null}catch(t){return console.log(`init failed for class: ${n._classname||"no _classname"}`,t),null}}function B(n,e){return Array.isArray(e)?e.map(t=>T(n,t)):[]}function ee(n,e){return B(n,e).filter(t=>t)}function ft(n,e){const t=Array.isArray(n)?n:[],r=Array.isArray(e)?e:[],i=new Map,s=(a,o)=>a===void 0?o:Array.isArray(a)&&Array.isArray(o)?[...new Set([...a,...o])]:typeof a=="object"&&typeof o=="object"&&!Array.isArray(a)&&!Array.isArray(o)?{...a,...o}:o;return t.forEach(a=>{i.set(a.key,a.value)}),r.forEach(a=>{const o=i.get(a.key);i.set(a.key,s(o,a.value))}),Array.from(i.entries()).map(([a,o])=>({key:a,value:o}))}function ge(n,e=6){return n=n.toString(),n.length<e?ge(`0${n}`,e):n}async function _e(n,e,{concurrency:t=Number.POSITIVE_INFINITY,stopOnError:r=!0,signal:i}={}){return new Promise((s,a)=>{if(n[Symbol.iterator]===void 0&&n[Symbol.asyncIterator]===void 0)throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof n})`);if(typeof e!="function")throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(t)&&t>=1||t===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\` (${typeof t})`);const o=[],u=[],l=new Map;let c=!1,d=!1,m=!1,h=0,g=0;const v=n[Symbol.iterator]===void 0?n[Symbol.asyncIterator]():n[Symbol.iterator](),D=()=>{L(i.reason)},Tt=()=>{i==null||i.removeEventListener("abort",D)},It=R=>{s(R),Tt()},L=R=>{c=!0,d=!0,a(R),Tt()};i&&(i.aborted&&L(i.reason),i.addEventListener("abort",D,{once:!0}));const $e=async()=>{if(d)return;const R=await v.next(),q=g;if(g++,R.done){if(m=!0,h===0&&!d){if(!r&&u.length>0){L(new AggregateError(u));return}if(d=!0,l.size===0){It(o);return}const M=[];for(const[j,Vn]of o.entries())l.get(j)!==x&&M.push(Vn);It(M)}return}h++,(async()=>{try{const M=await R.value;if(d)return;const j=await e(M,q);j===x&&l.set(q,j),o[q]=j,h--,await $e()}catch(M){if(r)L(M);else{u.push(M),h--;try{await $e()}catch(j){L(j)}}}})()};(async()=>{for(let R=0;R<t;R++){try{await $e()}catch(q){L(q);break}if(m||c)break}})()})}function dt(n,e,{concurrency:t=Number.POSITIVE_INFINITY,backpressure:r=t}={}){if(n[Symbol.iterator]===void 0&&n[Symbol.asyncIterator]===void 0)throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof n})`);if(typeof e!="function")throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(t)&&t>=1||t===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\` (${typeof t})`);if(!(Number.isSafeInteger(r)&&r>=t||r===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`backpressure\` to be an integer from \`concurrency\` (${t}) and up or \`Infinity\`, got \`${r}\` (${typeof r})`);return{async*[Symbol.asyncIterator](){const i=n[Symbol.asyncIterator]===void 0?n[Symbol.iterator]():n[Symbol.asyncIterator](),s=[];let a=0,o=!1,u=0;function l(){if(o||!(a<t&&s.length<r))return;a++;const c=(async()=>{const{done:d,value:m}=await i.next();if(d)return a--,{done:!0};l();try{const h=await e(await m,u++);if(a--,h===x){const g=s.indexOf(c);g>0&&s.splice(g,1)}return l(),{done:!1,value:h}}catch(h){return a--,o=!0,{error:h}}})();s.push(c)}for(l();s.length>0;){const{error:c,done:d,value:m}=await s[0];if(s.shift(),c)throw c;if(d)return;l(),m!==x&&(yield m)}}}}const x=Symbol("skip");function ht({engine:n,template:e,value:t}={}){if(!e)return"";const r=n.init(t),i=/\{\{\s(.*?)\s\}\}/g;return e.replace(i,s=>{const a=r.pipe(s);return a==null?"":typeof a=="object"?JSON.stringify(a):a})}function mt({content:n,mapping:e}){let t=!1;typeof n=="object"&&n!==null&&(n=JSON.stringify(n),t=!0);const r=/\[\[\s*([^[\]]+?)\s*\]\]/g,i=n.replace(r,(s,a)=>{const o=a.trim();if(/^[\w.\-]+$/.test(o)){const u=o.split(".");let l=e;for(const c of u)if(c&&(l=l==null?void 0:l[c],l===void 0))break;if(l!==void 0)return l}return`<%= ${o} %>`});return t?JSON.parse(i):i}function yt(n,e={}){const{normalizeWhitespace:t=!0,removeNewlines:r=!1,trim:i=!0,preserveBasicWhitespace:s=!0,debug:a=!1}=e;if(typeof n!="string")return n;let o=n;if(a&&(console.log("Original input:",JSON.stringify(n)),console.log("Options:",{normalizeWhitespace:t,removeNewlines:r,trim:i,preserveBasicWhitespace:s})),s&&!r)if(a){const u=[];o=o.replace(/[\x00-\x08\v\f\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,l=>(u.push({char:l,code:l.charCodeAt(0),hex:`0x${l.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0")}`}),"")),u.length>0?(console.log("Phase 1 (preserve mode) - Removed characters:"),u.forEach(l=>{console.log(` - Character: ${JSON.stringify(l.char)}, Code: ${l.code}, Hex: ${l.hex}`)}),console.log(`Removed ${u.length} control character(s)`)):console.log("Phase 1 (preserve mode) - No control characters found")}else o=o.replace(/[\x00-\x08\v\f\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,"");else if(a){const u=[];o=o.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,l=>(u.push({char:l,code:l.charCodeAt(0),hex:`0x${l.charCodeAt(0).toString(16).toUpperCase().padStart(4,"0")}`}),"")),u.length>0?(console.log("Phase 1 (full removal mode) - Removed characters:"),u.forEach(l=>{console.log(` - Character: ${JSON.stringify(l.char)}, Code: ${l.code}, Hex: ${l.hex}`)}),console.log(`Removed ${u.length} control character(s)`)):console.log("Phase 1 (full removal mode) - No control characters found")}else o=o.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g,"");return a&&console.log("After Phase 1:",JSON.stringify(o)),r&&(a?(o=o.replace(/[\r\n]+/g," "),console.log("Phase 2 - Converted newlines to spaces")):o=o.replace(/[\r\n]+/g," ")),t&&(a?(o=o.replace(/[ \t]+/g," "),console.log("Phase 2 - Normalized whitespace")):o=o.replace(/[ \t]+/g," ")),a&&console.log("After Phase 2:",JSON.stringify(o)),i&&(a?(o=o.trim(),console.log("Phase 3 - Trimmed leading/trailing whitespace")):o=o.trim()),a&&(console.log("Final result:",JSON.stringify(o)),console.log("--- Sanitization complete ---")),o}function we(n){return n&&typeof n.toString=="function"?n.toString():n}function pt(n){const e=[...n];for(let t=e.length-1;t>=0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}return e}function U(n,e="_"){return n===null||typeof n>"u"||typeof n.toString>"u"?null:n.toString().trim().toUpperCase().replace("-",e).replace(" ",e)}function En(n,e=34){const t=Cn(e);return bn(n,t)}function bn(n,e){const{byCode:t}=e;if(n===0)return t[0];let r="";const i=e.length;for(;n>0;)r=t[n%i]+r,n=Math.floor(n/i);return r}function Cn(n){let e="9876543210ABCDEFGHJKLMNPQRSTUVWXYZ";return n===58&&(e="9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz"),$n(e)}function Sn(n){return gt(`${n}`).toLowerCase().split(" ").join("-")}function $n(n){const e={},t={},{length:r}=n;let i;for(let s=0;s<r;s++)i=n[s],e[s]=i,t[i]=s;return{byCode:e,byChar:t,length:r}}function vn(n,e){return typeof n!="string"||typeof e!="string"?!1:n.trim().toUpperCase()===e.trim().toUpperCase()}function gt(n){return n.replace(/\s+/g,"-").replace(/[.,\/#!$%\^&\*;:{}=\_`~()]/g,"")}function On({len:n=16,pattern:e="a1"}={}){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r="abcdefghijklmnopqrstuvwxyz",i="1234567890",s="~!@#$%^&*_+-=";let a="";e.includes("A")&&(a+=t),e.includes("a")&&(a+=r),e.includes("1")&&(a+=i),e.includes("#")&&(a+=s);const o=[...a];return[...new Array(n)].map(u=>o[Math.random()*o.length|0]).join``}function Rn(n){return(typeof n!="string"?n.toString():n).split("").reverse().join("")}function Tn(n){return typeof(n==null?void 0:n.toUpperCase)=="function"?n.toUpperCase():""}function In(n){let e=34,t=8;n===void 0||(typeof n=="number"?e=n:typeof n=="object"&&n!==null&&(e=n.base??e,t=n.len??t));const r=new Date().valueOf(),i=On({len:t,pattern:"1"}),s=Rn(`${r}${i}`);return En(s,e)}function Nn(n){return n?n.trim().split(/\s+/).map((e,t)=>e?t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():"").join(""):""}function Dn(n){return n?n.trim().toLowerCase():""}function Mn(n){return/[^\w\s]|_/g.test(n.replace(/_/g,""))?null:n.replace(/([a-z])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[\s\-\.]+/g,"_").toUpperCase().replace(/^_+|_+$/g,"").replace(/_{2,}/g,"_")}const te={getCssClass:Sn,isSame:vn,punctuationless:gt,safeToUpperCase:Tn,setCode:In,toCamelCase:Nn,toLowerCase:Dn,toScreamingSnakeCase:Mn};function Ae(n,e){n.add({meta:{active:{type:Boolean,default:!0},created:{type:Number},creator:{type:String},deleted:{type:Boolean,default:!1},modified:{type:Number},owner:{type:String}}}),n.pre("save",function(t){this.meta.modified=Date.now(),t()}),n.index({"meta.active":1,"meta.deleted":1},{name:"tracking_status_index",background:!0,partialFilterExpression:{"meta.active":!0,"meta.deleted":!1}})}function _t(n,e){n.path("meta")||Ae(n),n.add({metadata:[{type:Object}],remarks:[{type:Object}],tenantCode:{type:String,required:!0}}),n.index({tenantCode:1},{name:"tenant_core_index",background:!0}),n.indexes().some(i=>i.name==="tenant_status_index")||n.index({tenantCode:1,_type:1},{name:"tenant_status_index",background:!0,partialFilterExpression:{_type:"Tenant","meta.active":!0,"meta.deleted":!1}})}const jn=Object.freeze(Object.defineProperty({__proto__:null,authorize:S,calculateAge:I,changeCreatorOwner:ie,concatStringByArray:J,convertString:Qe,convertTimestampToString:et,detectControlCharacters:tt,displayName:rt,downloadFileByUrl:st,escapeRegex:at,expressHelper:ot,extractEmails:lt,formatDate:oe,generalPost:ut,getObjectByArr:pe,getValidation:C,getValueByKeys:_,groupArrayByKey:ct,init:T,initFromArray:B,initOnlyValidFromArray:ee,isConvertibleToNumber:z,mergeArraysByKey:ft,objectHelper:b,pMap:_e,pMapIterable:dt,pMapSkip:x,pReduce:Z,padZeros:ge,printControlCharReport:nt,renderByTemplate:ht,replacePlaceholders:mt,sanitizeText:yt,setId:we,shuffleArray:pt,stringFormatter:U,stringHelper:te,tenantPlugin:_t,trackingPlugin:Ae},Symbol.toStringTag,{value:"Module"}));class wt{constructor(e){e=e||{},this.expiration=e.expiration||null,this.s3Client=e.s3Client||null,this.getIdToken=e.getIdToken,this.region=e.region||"ap-east-1",this.roleArn=e.roleArn,this.roleSessionName=e.roleSessionName||"web-identity-session",this.durationSession=e.durationSession||3600,this.awsClientSts=e.awsClientSts,this.awsClientS3=e.awsClientS3}static dummyData(){return{getIdToken:()=>"mock-web-identity-token",roleArn:"arn:aws:iam::846252828949:role/oidcS3Jccpa",awsClientSts:{STSClient:class{},AssumeRoleWithWebIdentityCommand:class{}},awsClientS3:{S3Client:class{},PutObjectCommand:class{},GetObjectCommand:class{},DeleteObjectCommand:class{}}}}static init(e={}){if(e instanceof this)return e;try{const t=new this(e);return t.isValid?t:null}catch{return null}}get isExpired(){if(!this.expiration)return!0;const e=new Date,t=1*60*1e3;return e>=new Date(this.expiration.getTime()-t)}get isValid(){if(!this.getIdToken)throw new Error("Missing required configuration: getIdToken function");if(!this.roleArn)throw new Error("Missing required configuration: roleArn");if(!this.awsClientSts)throw new Error("Missing required AWS awsClientSts client configuration");if(!this.awsClientSts.STSClient)throw new Error("Missing STSClient in AWS awsClientSts client configuration");if(!this.awsClientSts.AssumeRoleWithWebIdentityCommand)throw new Error("Missing AssumeRoleWithWebIdentityCommand in AWS awsClientSts client configuration");if(!this.awsClientS3)throw new Error("Missing required AWS awsClientS3 client configuration");const e=["S3Client","PutObjectCommand","GetObjectCommand","DeleteObjectCommand"];for(const t of e)if(!this.awsClientS3[t])throw new Error(`Missing ${t} in AWS awsClientS3 client configuration`);return!0}async refreshCredentials(){try{if(!await this.getIdToken())throw new Error("getIdToken function returned empty or invalid token");const i=(await new this.awsClientSts.STSClient({region:this.region}).send(new this.awsClientSts.AssumeRoleWithWebIdentityCommand({RoleArn:this.roleArn,RoleSessionName:this.roleSessionName,WebIdentityToken:await this.getIdToken(),DurationSeconds:this.durationSession}))).Credentials;if(!i)throw new Error("No credentials returned from awsClientSts");return this.expiration=i.Expiration,this.s3Client=new this.awsClientS3.S3Client({region:this.region,credentials:{accessKeyId:i.AccessKeyId,secretAccessKey:i.SecretAccessKey,sessionToken:i.SessionToken}}),this}catch(e){throw new Error(`Failed to refresh credentials: ${e.message}`)}}async getS3Client(){return(this.isExpired||!this.s3Client)&&await this.refreshCredentials(),this.s3Client}async putObject(e){try{const t=await this.getS3Client(),r=new this.awsClientS3.PutObjectCommand(e);await t.send(r);const i=e.Key.split("/");return{url:`https://s3.${this.region}.amazonaws.com/${e.Bucket}/${e.Key}`,filename:i.pop(),folder:e.Bucket,subFolders:i}}catch(t){throw new Error(`Failed to put object: ${t.message}`)}}async getObject(e){try{const t=await this.getS3Client(),r=new this.awsClientS3.GetObjectCommand(e),i=await t.send(r);return{body:i.Body,contentType:i.ContentType,lastModified:i.LastModified,contentLength:i.ContentLength}}catch(t){throw new Error(`Failed to get object: ${t.message}`)}}async deleteObject(e){try{const t=await this.getS3Client(),r=new this.awsClientS3.DeleteObjectCommand(e);return await t.send(r),!0}catch(t){throw new Error(`Failed to delete object: ${t.message}`)}}}const Ee="_";class O extends E{static init(e={}){if(e instanceof this)return e;const t=new this({...e,key:U(e.key,Ee)});return t.isValid?t:null}static get _classname(){return"Metadata"}static mapToKeyValue(e=[],t="key",r="value"){return Array.isArray(e)?e.reduce((i,s)=>{if(s&&typeof s=="object"){const a=b.get(s,t),o=b.get(s,r);if(a!=null){const u=o!==void 0?te.toScreamingSnakeCase(String(o)):"";i.push(this.init({key:a,value:u}))}}return i},[]):[]}static merge(e,t){return(t||[]).map(r=>{const i=e.find(s=>At(s.key,r.key));return i?i.value=kn(r.value,i.value):e.push(r),r}),e}static sameKey(e,t){return At(e.key,t)}}function At(n,e){return U(n,Ee)===U(e,Ee)}function kn(n,e){return n===void 0?e:Array.isArray(n)&&Array.isArray(e)?[...new Set([...n,...e])]:typeof n=="object"&&typeof e=="object"&&!Array.isArray(n)&&!Array.isArray(e)?{...n,...e}:e}class K{constructor(e={}){var i,s,a,o,u,l;e=e||{};const t=e._id||e.id;this.id=we(t),this._type=e._type||"TrackedEntity";const r=Date.now();this.meta={active:((i=e.meta)==null?void 0:i.active)??e.active??!0,created:((s=e.meta)==null?void 0:s.created)??(e.created?new Date(e.created).getTime():r),creator:((a=e.meta)==null?void 0:a.creator)??e.creator??"",deleted:((o=e.meta)==null?void 0:o.deleted)??e.deleted??!1,modified:((u=e.meta)==null?void 0:u.modified)??(e.modified?new Date(e.modified).getTime():r),owner:((l=e.meta)==null?void 0:l.owner)??e.owner??""}}static dummyData(){const e=Date.now();return{meta:{active:!0,deleted:!1,created:e,creator:"creator",modified:e,owner:"owner"}}}static get _classname(){return"TrackedEntity"}static get _superclass(){return"TrackedEntity"}static init(e={}){return T(this,e)}static initFromArray(e=[]){return B(this,e)}static initOnlyValidFromArray(e=[]){return ee(this,e)}get __valid(){return{}}get isValid(){return!!this}get active(){var e;return((e=this.meta)==null?void 0:e.active)??this.active}get created(){var e;return((e=this.meta)==null?void 0:e.created)??this.created}get creator(){var e;return((e=this.meta)==null?void 0:e.creator)??this.creator}get deleted(){var e;return((e=this.meta)==null?void 0:e.deleted)??this.deleted}get modified(){var e;return((e=this.meta)==null?void 0:e.modified)??this.modified}get owner(){var e;return((e=this.meta)==null?void 0:e.owner)??this.owner}changeCreatorOwner({source:e,target:t}){return ie(this,{source:e,target:t}).setModified()}delete(){return this.setDeleted()}setActive(){return this.meta?this.meta.active=!0:this.active=!0,this}setDeleted(){return this.meta?this.meta.deleted=!0:this.deleted=!0,this}setModified(){const e=Date.now();return this.meta?this.meta.modified=e:this.modified=e,this}setOwner(e){return e?(this.meta?this.meta.owner=e:this.owner=e,this):this}unsetActive(){return this.meta?this.meta.active=!1:this.active=!1,this}unsetDeleted(){return this.meta?this.meta.deleted=!1:this.deleted=!1,this}update(e){const t=this.constructor.ALLOWED_META_PROPS,r={...this.meta};return e.meta&&t.forEach(i=>{e.meta.hasOwnProperty(i)&&(r[i]=e.meta[i])}),t.forEach(i=>{e.hasOwnProperty(i)&&(r[i]=e[i])}),JSON.stringify(this.meta)!==JSON.stringify(r)&&(this.meta=r),this.setModified()}}Nt(K,"ALLOWED_META_PROPS",["active","deleted","owner"]);class Et extends K{constructor(e){e=e||{},super(e),this.id=e.id,this.body=e.body,this.data=e.data,this.dirty=e.dirty,this.metadata=O.initOnlyValidFromArray(e.metadata),this.remarks=E.initOnlyValidFromArray(e.remarks),this.threadID=e.threadID,this.title=e.title}static get _classname(){return"PushEnvelope"}static get _superclass(){return"PushEnvelope"}static init(e={}){return T(this,e)}get _classname(){return"PushEnvelope"}get _superclass(){return"PushEnvelope"}get isValid(){return super.isValid&&this.data}}const A={trace:{weight:10,name:"TRACE"},debug:{weight:20,name:"DEBUG"},info:{weight:30,name:"INFO"},warn:{weight:40,name:"WARN"},error:{weight:50,name:"ERROR"},critical:{weight:60,name:"CRITICAL"},alert:{weight:70,name:"ALERT"},emergency:{weight:80,name:"EMERGENCY"}};class be{constructor(e={}){e=e||{},this.data=e.data,this.level=e.level,this.timestamp=e.timestamp,this.stackTrace=xn(e),this.name=e.name??"",this.zone=e.zone}toString(){return`[${this.logName(this)}] ${this.serialize(this)}
10
- ${this.stackTrace||""}
11
- ${this.zone||""}`}logName(){let e=`${this.timestamp}`;return this.level.name&&(e+=`>${this.level.name}`),this.name&&(e+=`>${this.name}`),e}serialize(){var e;return this.data instanceof Error||typeof((e=this.data)==null?void 0:e.message)<"u"?this.data.message:this.data===null?"null":this.data===void 0?"undefined":typeof this.data=="object"?JSON.stringify(this.data):this.data.toString()}}function xn(n){var e;return n.stackTrace?n.stackTrace:n.data instanceof Error||typeof((e=n.data)==null?void 0:e.stack)<"u"?n.data.stack:null}let Ce;class F{constructor(e={}){const{level:t}=e;this._level=t??A.debug,this._handlers=new Map}static getInstance(e){return Ce||(Ce=new F(e)),Ce}setLevel(e){return this._level=e,this}addHandler(e){return e instanceof F&&this._handlers.set(e.constructor,e),this}removeHandler(e){return this._handlers.delete(e),this}receive({record:e}){var t,r;((t=e.level)==null?void 0:t.weight)<((r=this._level)==null?void 0:r.weight)||(this._handlers.forEach(i=>{i.receive({record:e})}),this.logBody(e))}logBody(e){}trace(e,t){return this._log({level:A.trace,object:t,options:e})}debug(e,t){return this._log({level:A.debug,object:t,options:e})}info(e,t){return this._log({level:A.info,object:t,options:e})}warn(e,t){return this._log({level:A.warn,object:t,options:e})}error(e,t){return this._log({level:A.error,object:t,options:e})}critical(e,t){return this._log({level:A.critical,object:t,options:e})}_log({level:e,object:t,options:r}){typeof t>"u"&&(t=r,r="");const i=Date.now(),s=new be({data:t,level:e,timestamp:i,stackTrace:(t==null?void 0:t.stack)??(r==null?void 0:r.stack)??null,name:r??""});return this.receive({record:s})}}class bt extends F{constructor(e={}){const{format:t}=e;super(e),this.format=t}logBody(e){const t=e.logName(),r=this.format?this.format(e):e.serialize();switch(e.level){case A.error:case A.critical:case A.alert:case A.emergency:console.error(`[${t}] ${r}`,e.stackTrace||"");break;case A.warn:console.warn(`[${t}] ${r}`,e.stackTrace||"");break;case A.info:console.error(`[${t}] ${r}`,e.stackTrace||"");break;case A.debug:console.error(`[${t}] ${r}`,e.stackTrace||"");break;default:console.error(`[${t}] ${r}`,e.stackTrace||"")}}}const ne={debug:{name:"DEBUG"},production:{name:"PRODUCTION"}};function Ct(n){const e=n.toLowerCase();return ne[e]?ne[e]:null}const Fn=["attributes","ref"];class H{constructor(e={}){e=e||{},this.attributes=E.initOnlyValidFromArray(e.attributes),this.ref=e.ref||{}}static get _classname(){return"QMeta"}static get _superclass(){return"QMeta"}static init(e={}){return e instanceof H?e:new H(e)}addAttribute(e){const t=E.init(e);if(!t)throw new Error("invalid meta attribute");return this.attributes.push(t),this}update(e){return Object.keys(e).forEach(t=>{Fn.includes(t)&&(t==="attributes"?this[t]=E.initOnlyValidFromArray(e[t]):this[t]=e[t])}),this}}class re{constructor(e){e=e||{};const{_Actor:t}=e._constructor||{};this._Actor=t,this._actor=e._actor,this.actorCode=typeof e=="number"?null:e.actorCode||null,this.timestamp=typeof e=="number"?e:e.timestamp||null}static get _classname(){return"ActionRecord"}static get _superclass(){return"ActionRecord"}static dummyData(){return{timestamp:new Date().valueOf()}}static init(e={}){return T(this,e)}get _classname(){return"ActionRecord"}get _superclass(){return"ActionRecord"}get actor(){return this._Actor&&typeof this._Actor.init=="function"?this._Actor.init(this._actor):this._actor}get isValid(){return!!this.timestamp}update(e){return typeof e=="number"?(this.timestamp=e,this):(Object.keys(e).forEach(t=>{this[t]=e[t]}),this)}}const Pn=["_ActionRecord","created"];class Se{constructor(e){e=e||{};const{_ActionRecord:t}=e._constructor||{};this._ActionRecord=t&&t._superclass===re._superclass?t:re,this.created=this._ActionRecord.init(e.created||{timestamp:new Date().valueOf()})}static get _classname(){return"Status"}static get _superclass(){return"Status"}static dummyData(){return{}}static init(e={}){return T(this,e)}static initFromArray(e=[]){return B(this,e)}static initOnlyValidFromArray(e=[]){return ee(this,e)}get _classname(){return"Status"}get _superclass(){return"Status"}get isCreated(){var e;return((e=this.created)==null?void 0:e.timestamp)!==null}get isValid(){return!!this}setValue(e,t,r){const i=e||Date.now();return this[r]=this[r]instanceof this._ActionRecord?this[r].update({actorCode:t,timestamp:i}):this._ActionRecord.init({actorCode:t,timestamp:i}),this}update(e){return Object.keys(e).forEach(t=>{Pn.includes(t)||(this[t]=this[t]instanceof this._ActionRecord?this[t].update(e[t]):this._ActionRecord.init(e[t]))}),this}}class St extends Se{constructor(e){e=e||{},super(e),this.archived=this._ActionRecord.init(e.archived),this.completed=this._ActionRecord.init(e.completed),this.discarded=this._ActionRecord.init(e.discarded),this.drafted=this._ActionRecord.init(e.drafted)}static get _classname(){return"StatusDocument"}get _classname(){return"StatusDocument"}get isArchived(){var e;return((e=this.created)==null?void 0:e.timestamp)!==null}get isCompleted(){var e;return((e=this.completed)==null?void 0:e.timestamp)!==null}get isDiscarded(){var e;return((e=this.discarded)==null?void 0:e.timestamp)!==null}get isDrafted(){var e;return((e=this.drafted)==null?void 0:e.timestamp)!==null}get isValid(){return super.isValid}setArchived(e,t){return this.setValue(e,t,"archived")}setCompleted(e,t){return this.setValue(e,t,"completed")}setDiscarded(e,t){return this.setValue(e,t,"discarded")}setDrafted(e,t){return this.setValue(e,t,"drafted")}}class $t extends K{constructor(e={}){e=e||{},super(e),this._type=e._type||"TenantAwareEntity",this._tenant=e._tenant,this.metadata=O.initOnlyValidFromArray(e.metadata),this.remarks=E.initOnlyValidFromArray(e.remarks),this.tenantCode=e.tenantCode}static dummyData(){return{...super.dummyData(),metadata:[],remarks:[],tenantCode:"tenantCode"}}static get _classname(){return"TenantAwareEntity"}static get _superclass(){return"TenantAwareEntity"}get __valid(){return{...super.__valid,tenantCode:this.tenantCode}}get isValid(){return super.isValid&&!!this.tenantCode}insertOrUpdateMetadata(e,t){return this.metadata=O.insertOrUpdateRecord(this.metadata,e,t),this}getMetadata(){return this.metadata}getMetadataByKey(e){return O.foundByKey(this.metadata,e)}getMetadataValueByKey(e){const t=this.getMetadataByKey(e);return t?t.value:null}getMetadataValueByKeys(e,t){if(!Array.isArray(e))return null;if(t=t||this.metadata,e.length===0)return t;const r=e.shift(),i=O.getMetadataValueByKeyAsArray(t,r);return this.getMetadataValueByKeys(e,i)}getMetadataValueByKeyAsArray(e){return O.getMetadataValueByKeyAsArray(this.metadata,e)}getRemarks(){return this.remarks}getRemarkByKey(e){return E.foundByKey(this.remarks,e)}getRemarksValueByKey(e){const t=this.getRemarkByKey(e);return t?t.value:null}getTenantCode(){return this.tenantCode}update(e){return e.metadata&&Array.isArray(e.metadata)&&(this.metadata=O.initOnlyValidFromArray(e.metadata)),e.remarks&&Array.isArray(e.remarks)&&(this.remarks=E.initOnlyValidFromArray(e.remarks)),super.update(e)}}class vt{static get _classname(){return"UniqueKeyGenerator"}static get _superclass(){return"UniqueKeyGenerator"}static makeFormatter({fieldName:e,format:t,options:r}){switch(t){case"set_code":return Ot(e);default:return Ot(e)}}static makeGenerator(e){const t=e.map(r=>this.makeFormatter(r));return async r=>await Z(t,async(s,a)=>{const o=await a(r);return Object.assign(s,o)},r)}}function Ot(n,e){return async(t={})=>t[n]?{}:{[n]:te.setCode()}}class W{constructor(e={}){this.blockUI=e.blockUI??!1,this.callback=e.callback??null,this.data=e.data??null,this.event=e.event??null,this.reloadPage=e.reloadPage??!1,this.sessionId=e.sessionId??null,this.timeout=e.timeout??3e4}static get _classname(){return"WebAppRequest"}static get _superclass(){return"WebAppRequest"}static init(e){if(e instanceof W)return e;const t=new W(e);return t.isValid?t:null}static dummyData(){return{data:null,sessionId:"sessionId"}}get isValid(){return!!this.sessionId}getId(){try{return this.sessionId}catch{return null}}}const Rt={EXCUTE_EVENT_ERROR:"EXCUTE_EVENT_ERROR",NOT_FOUND:"NOT_FOUND",SERVER_ERROR:"SERVER_ERROR",TIMEOUT:"TIMEOUT",UNAUTHORIZED:"UNAUTHORIZED",VALIDATION_ERROR:"VALIDATION_ERROR"};class P{constructor(e={}){this.code=e.code??null,this.message=e.message??"",this.timestamp=e.timestamp??null}static init(e){if(e instanceof P)return e;const t=new P(e);return t.isValid?t:null}get isValid(){return!!this.code}}class Y{constructor(e={}){this.data=e.data??null,this.errorDetail=P.init(e.errorDetail),this.sessionId=e.sessionId??null,this.success=e.success??!1}static get _classname(){return"WebAppResponse"}static get _superclass(){return"WebAppResponse"}static init(e){if(e instanceof Y)return e;const t=new Y(e);return t.isValid?t:null}static dummyData(){return{data:null,errorDetail:null,sessionId:"sessionId",success:!1}}get isValid(){return!!this.sessionId}getId(){try{return this.sessionId}catch{return null}}}const Ln={...jn,...Object.freeze(Object.defineProperty({__proto__:null,ActionRecord:re,ApiResponse:he,AwsStsS3Client:wt,ConsoleLog:bt,ERROR_CODES:Rt,ErrorDetail:P,KeyValueObject:E,LogRecord:be,Metadata:O,PushEnvelope:Et,QLog:F,QLogEnv:ne,QLogLevel:A,QMeta:H,Repo:X,Service:me,Status:Se,StatusDocument:St,TemplateCompiler:ce,TenantAwareEntity:$t,TrackedEntity:K,UniqueKeyGenerator:vt,WebAppRequest:W,WebAppResponse:Y,getQLogEnv:Ct,makeApiResponse:N,makeService:ye},Symbol.toStringTag,{value:"Module"}))};f.ActionRecord=re,f.ApiResponse=he,f.AwsStsS3Client=wt,f.ConsoleLog=bt,f.ERROR_CODES=Rt,f.ErrorDetail=P,f.KeyValueObject=E,f.LogRecord=be,f.Metadata=O,f.PushEnvelope=Et,f.QLog=F,f.QLogEnv=ne,f.QLogLevel=A,f.QMeta=H,f.Repo=X,f.Service=me,f.Status=Se,f.StatusDocument=St,f.TemplateCompiler=ce,f.TenantAwareEntity=$t,f.TrackedEntity=K,f.UniqueKeyGenerator=vt,f.WebAppRequest=W,f.WebAppResponse=Y,f.authorize=S,f.calculateAge=I,f.changeCreatorOwner=ie,f.concatStringByArray=J,f.convertString=Qe,f.convertTimestampToString=et,f.default=Ln,f.detectControlCharacters=tt,f.displayName=rt,f.downloadFileByUrl=st,f.escapeRegex=at,f.expressHelper=ot,f.extractEmails=lt,f.formatDate=oe,f.generalPost=ut,f.getObjectByArr=pe,f.getQLogEnv=Ct,f.getValidation=C,f.getValueByKeys=_,f.groupArrayByKey=ct,f.init=T,f.initFromArray=B,f.initOnlyValidFromArray=ee,f.isConvertibleToNumber=z,f.makeApiResponse=N,f.makeService=ye,f.mergeArraysByKey=ft,f.objectHelper=b,f.pMap=_e,f.pMapIterable=dt,f.pMapSkip=x,f.pReduce=Z,f.padZeros=ge,f.printControlCharReport=nt,f.renderByTemplate=ht,f.replacePlaceholders=mt,f.sanitizeText=yt,f.setId=we,f.shuffleArray=pt,f.stringFormatter=U,f.stringHelper=te,f.tenantPlugin=_t,f.trackingPlugin=Ae,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})})(this.qUtilities=this.qUtilities||{});
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ (function(exports) {
5
+ "use strict";
6
+ function authorize({ allowCoordinator, allowOwner, query = {}, required, user }) {
7
+ if (!user) {
8
+ throw new Error("Require login.");
9
+ }
10
+ if (!user.permission) ;
11
+ const scopes = user.permission.getScopes(required || {}) || [];
12
+ if (!scopes || scopes.length === 0) ;
13
+ if (!scopes.includes("*")) {
14
+ query.tenantCode = user.tenantCode;
15
+ }
16
+ if (!scopes.includes("TENANT")) {
17
+ query.eventShortCode = user.eventShortCode;
18
+ }
19
+ if (allowCoordinator) {
20
+ if (query.registrationGroupCode && user.myManagedRegistrationGroupCodes.includes(query.registrationGroupCode)) {
21
+ query.__ALLOW_COORDINATOR = true;
22
+ } else {
23
+ if (!scopes.includes("EVENT")) {
24
+ query.eventRegistrationCode = user.eventRegistrationCode;
25
+ }
26
+ }
27
+ } else {
28
+ if (!scopes.includes("EVENT")) {
29
+ query.eventRegistrationCode = user.eventRegistrationCode;
30
+ }
31
+ }
32
+ if (allowOwner) {
33
+ query.__ALLOW_OWNER = true;
34
+ }
35
+ const excludedFields = user.getExcludedFields(required);
36
+ if (excludedFields.length > 0) {
37
+ query.__EXCLUDED_FIELDS = excludedFields;
38
+ }
39
+ query.__LOGIN_SUBJECT_CODE = user.loginSubjectCode;
40
+ return query;
41
+ }
42
+ function calculateAge(timestamp, reference) {
43
+ const birthDate = new Date(timestamp);
44
+ const refDate = reference ? new Date(reference) : /* @__PURE__ */ new Date();
45
+ if (isNaN(birthDate.getTime())) {
46
+ return null;
47
+ }
48
+ if (isNaN(refDate.getTime())) {
49
+ return null;
50
+ }
51
+ if (birthDate > refDate) {
52
+ return null;
53
+ }
54
+ let age = refDate.getFullYear() - birthDate.getFullYear();
55
+ const monthDiff = refDate.getMonth() - birthDate.getMonth();
56
+ if (monthDiff < 0 || monthDiff === 0 && refDate.getDate() < birthDate.getDate()) {
57
+ age--;
58
+ }
59
+ return age;
60
+ }
61
+ function changeCreatorOwner(that, { source, target }) {
62
+ if (that.meta) {
63
+ if (!that.meta.creator || that.meta.creator === source.getId()) {
64
+ that.meta.creator = target.getId();
65
+ }
66
+ if (!that.meta.owner || that.meta.owner === source.getId()) {
67
+ that.meta.owner = target.getId();
68
+ }
69
+ } else {
70
+ if (!that.creator || that.creator === source.getId()) {
71
+ that.creator = target.getId();
72
+ }
73
+ if (!that.owner || that.owner === source.getId()) {
74
+ that.owner = target.getId();
75
+ }
76
+ }
77
+ return that;
78
+ }
79
+ function isConvertibleToNumber(value) {
80
+ return value !== null && value !== void 0 && typeof value !== "boolean" && String(value).trim() !== "" && !isNaN(Number(value));
81
+ }
82
+ function getValueByKeys(keys, data) {
83
+ let _keys = keys;
84
+ let _data = data;
85
+ if (typeof keys === "string") {
86
+ _keys = _keys.split(".");
87
+ }
88
+ if (!Array.isArray(keys) && typeof keys === "object") {
89
+ const { keys: keyArr, obj } = keys;
90
+ _keys = keyArr;
91
+ _data = obj;
92
+ }
93
+ if (_keys.length === 0) {
94
+ return _data;
95
+ }
96
+ const firstKey = _keys.shift();
97
+ if (_data && Object.prototype.hasOwnProperty.call(_data, firstKey)) {
98
+ return getValueByKeys(_keys, _data[firstKey]);
99
+ }
100
+ if (_data && firstKey) {
101
+ if (_keys.length > 0) {
102
+ return getValueByKeys(_keys, _data[firstKey]);
103
+ }
104
+ return _data[firstKey];
105
+ }
106
+ return _data;
107
+ }
108
+ function expandDotNotation(obj) {
109
+ const result = {};
110
+ for (const [key, value] of Object.entries(obj)) {
111
+ const typeMatch = key.match(/^(.*?)\|(boolean|date|html|number|string)$/);
112
+ let actualKey = key;
113
+ let type = null;
114
+ if (typeMatch) {
115
+ actualKey = typeMatch[1];
116
+ type = typeMatch[2];
117
+ }
118
+ const keys = actualKey.split(".");
119
+ let current = result;
120
+ for (let i = 0; i < keys.length - 1; i++) {
121
+ const part = keys[i];
122
+ if (!current[part] || typeof current[part] !== "object") {
123
+ current[part] = {};
124
+ }
125
+ current = current[part];
126
+ }
127
+ const lastKey = keys[keys.length - 1];
128
+ if (type === "boolean") {
129
+ if (value === 1 || value === "1" || value === true || value === "true" || value === "TRUE") {
130
+ current[lastKey] = true;
131
+ } else if (value === 0 || value === "0" || value === false || value === "false" || value === "FALSE") {
132
+ current[lastKey] = false;
133
+ } else {
134
+ current[lastKey] = Boolean(value);
135
+ }
136
+ } else if (type === "number") {
137
+ current[lastKey] = Number(value) || 0;
138
+ } else if (type === "date") {
139
+ current[lastKey] = new Date(value);
140
+ } else if (type === "html") {
141
+ if (value && typeof value === "string") {
142
+ let paragraphs = [];
143
+ if (value.includes("\n\n") || value.includes("\r\n\r\n")) {
144
+ paragraphs = value.split(/\r?\n\s*\r?\n/).filter((p) => p.trim() !== "");
145
+ } else {
146
+ paragraphs = value.split(/\r?\n/).filter((p) => p.trim() !== "");
147
+ }
148
+ if (paragraphs.length > 0) {
149
+ current[lastKey] = paragraphs.map((p) => `<div>${p.trim()}</div>`).join("");
150
+ } else {
151
+ current[lastKey] = value ? `<div>${value}</div>` : "";
152
+ }
153
+ } else {
154
+ current[lastKey] = value ? `<div>${value.toString()}</div>` : "";
155
+ }
156
+ } else {
157
+ if (value === null || value === void 0) {
158
+ current[lastKey] = "";
159
+ } else if (typeof value === "number") {
160
+ current[lastKey] = value;
161
+ } else if (typeof value === "string" && value.trim() !== "") {
162
+ const trimmed = value.trim();
163
+ if (/^-?\d+$/.test(trimmed)) {
164
+ current[lastKey] = Number.parseInt(trimmed, 10);
165
+ } else if (/^-?\d+\.\d+$/.test(trimmed)) {
166
+ current[lastKey] = Number.parseFloat(trimmed);
167
+ } else {
168
+ current[lastKey] = value;
169
+ }
170
+ } else {
171
+ current[lastKey] = (value == null ? void 0 : value.toString()) || "";
172
+ }
173
+ }
174
+ }
175
+ return result;
176
+ }
177
+ function get(obj, path) {
178
+ const parts = path.split(".");
179
+ return parts.reduce((acc, part) => {
180
+ if (part.endsWith("[]")) {
181
+ const key = part.slice(0, -2);
182
+ if (Array.isArray(acc[key])) {
183
+ return acc[key];
184
+ }
185
+ return [];
186
+ }
187
+ if (part.includes("[") && part.includes("]")) {
188
+ const arrayMatch = part.match(/(\w+)\[(\d+)\]/);
189
+ if (arrayMatch) {
190
+ const key = arrayMatch[1];
191
+ const index2 = arrayMatch[2];
192
+ return acc && acc[key] && acc[key][index2];
193
+ }
194
+ } else if (acc && Array.isArray(acc)) {
195
+ return acc.map((item) => item[part]);
196
+ } else {
197
+ return acc && acc[part];
198
+ }
199
+ }, obj);
200
+ }
201
+ function getNestedValue(obj, path) {
202
+ return path.split(".").reduce((current, key) => {
203
+ return current && current[key] !== void 0 ? current[key] : void 0;
204
+ }, obj);
205
+ }
206
+ function isPlainObject(value) {
207
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp) && // Optional: exclude other built-in objects
208
+ Object.prototype.toString.call(value) === "[object Object]";
209
+ }
210
+ function merge(target, ...sources) {
211
+ if (!sources.length)
212
+ return target;
213
+ const source = sources.shift();
214
+ if (_isObject(target) && _isObject(source)) {
215
+ for (const key in source) {
216
+ if (_isObject(source[key])) {
217
+ if (!target[key]) {
218
+ target[key] = {};
219
+ }
220
+ merge(target[key], source[key]);
221
+ } else {
222
+ target[key] = source[key];
223
+ }
224
+ }
225
+ }
226
+ return merge(target, ...sources);
227
+ }
228
+ function set(obj, path, value) {
229
+ const parts = path.split(".");
230
+ let current = obj;
231
+ for (let i = 0; i < parts.length - 1; i++) {
232
+ const part = parts[i];
233
+ let key, index2;
234
+ const arrayMatch2 = part.match(/^(\w+)\[(\d+)\]$/);
235
+ if (arrayMatch2) {
236
+ key = arrayMatch2[1];
237
+ index2 = Number.parseInt(arrayMatch2[2], 10);
238
+ if (!current[key] || !Array.isArray(current[key])) {
239
+ current[key] = [];
240
+ }
241
+ while (current[key].length <= index2) {
242
+ current[key].push(void 0);
243
+ }
244
+ if (current[key][index2] == null) {
245
+ current[key][index2] = {};
246
+ }
247
+ current = current[key][index2];
248
+ } else {
249
+ if (!current[part]) {
250
+ current[part] = {};
251
+ }
252
+ current = current[part];
253
+ }
254
+ }
255
+ const lastPart = parts[parts.length - 1];
256
+ const arrayMatch = lastPart.match(/^(\w+)\[(\d+)\]$/);
257
+ if (arrayMatch) {
258
+ const key = arrayMatch[1];
259
+ const index2 = Number.parseInt(arrayMatch[2], 10);
260
+ if (!current[key] || !Array.isArray(current[key])) {
261
+ current[key] = [];
262
+ }
263
+ while (current[key].length <= index2) {
264
+ current[key].push(void 0);
265
+ }
266
+ current[key][index2] = value;
267
+ } else {
268
+ current[lastPart] = value;
269
+ }
270
+ }
271
+ function _isObject(obj) {
272
+ return obj && typeof obj === "object" && !Array.isArray(obj);
273
+ }
274
+ const objectHelper = {
275
+ expandDotNotation,
276
+ get,
277
+ getNestedValue,
278
+ isPlainObject,
279
+ merge,
280
+ set
281
+ };
282
+ class KeyValueObject {
283
+ constructor(options = {}) {
284
+ options = options || {};
285
+ this.key = options.key || null;
286
+ this.value = typeof options.value !== "undefined" ? options.value : "";
287
+ }
288
+ // Class methods
289
+ static init(options = {}) {
290
+ if (options instanceof this) {
291
+ return options;
292
+ }
293
+ const instance2 = new this(options);
294
+ return instance2.isValid ? instance2 : null;
295
+ }
296
+ static initFromArray(arr = []) {
297
+ if (Array.isArray(arr)) {
298
+ return arr.map((a) => this.init(a));
299
+ }
300
+ return [];
301
+ }
302
+ static initOnlyValidFromArray(arr = []) {
303
+ return this.initFromArray(arr).filter((i) => i);
304
+ }
305
+ static get _classname() {
306
+ return "KeyValueObject";
307
+ }
308
+ static get _superclass() {
309
+ return "KeyValueObject";
310
+ }
311
+ static addItem(arr, key, value) {
312
+ arr.push(this.init({ key, value }));
313
+ }
314
+ static addRecord(arr = [], key, value) {
315
+ if (!this.hasKeyValue(arr, key, value)) {
316
+ arr.push(this.init({ key, value }));
317
+ }
318
+ return arr;
319
+ }
320
+ static appendRecord(arr = [], key, value) {
321
+ return arr.map((item) => {
322
+ if (this.sameKey(item, key)) {
323
+ item.value = [...item.value, ...value];
324
+ }
325
+ return item;
326
+ });
327
+ }
328
+ static appendValueArray(arr = [], key, value) {
329
+ return arr.map((item) => {
330
+ if (this.sameKey(item, key)) {
331
+ item.value = [...item.value, ...value];
332
+ }
333
+ return item;
334
+ });
335
+ }
336
+ static foundByKey(arr = [], key) {
337
+ const found = arr.find((m) => {
338
+ return this.sameKey(m, key);
339
+ });
340
+ return found || null;
341
+ }
342
+ static foundValueByKey(arr = [], key) {
343
+ const found = this.foundByKey(arr, key);
344
+ return found ? found.value : null;
345
+ }
346
+ static fromObject(options = {}) {
347
+ return Object.keys(options).reduce((acc, key) => {
348
+ acc.push(this.init({ key, value: options[key] }));
349
+ return acc;
350
+ }, []);
351
+ }
352
+ static getValueByKey(arr = [], key) {
353
+ return this.foundValueByKey(arr, key);
354
+ }
355
+ static getMetadataValueByKeyAsArray(arr = [], key) {
356
+ const _value = this.getValueByKey(arr, key);
357
+ if (!_value) {
358
+ return [];
359
+ }
360
+ if (objectHelper.isPlainObject(_value)) {
361
+ return Object.keys(_value).reduce((acc, key2) => {
362
+ acc.push({ key: key2, value: _value[key2] });
363
+ return acc;
364
+ }, []);
365
+ }
366
+ return _value;
367
+ }
368
+ static getValueByKeyFromArray(arr = [], key) {
369
+ if (arr.length === 0) {
370
+ return null;
371
+ }
372
+ const firstArr = arr.shift();
373
+ const found = firstArr.find((i) => {
374
+ return this.sameKey(i, key);
375
+ });
376
+ if (found && found.value) {
377
+ return found.value;
378
+ }
379
+ return this.getValueByKeyFromArray(arr, key);
380
+ }
381
+ static getValuesByKey(arr = [], key) {
382
+ return arr.reduce((acc, item) => {
383
+ if (this.sameKey(item, key)) {
384
+ acc.push(item.value);
385
+ }
386
+ return acc;
387
+ }, []);
388
+ }
389
+ static hasKeyValue(arr = [], key, value) {
390
+ if (typeof value === "undefined") {
391
+ return arr.filter((item) => this.sameKey(item, key)).length > 0;
392
+ }
393
+ return arr.filter((item) => this.sameKey(item, key) && _isSame$1(item.value, value)).length > 0;
394
+ }
395
+ static insertOrUpdateRecord(arr = [], key, value) {
396
+ let copy = [...arr];
397
+ if (!this.hasKeyValue(arr, key)) {
398
+ copy.push(this.init({ key, value }));
399
+ } else {
400
+ copy = this.updateRecord(arr, key, value);
401
+ }
402
+ return copy;
403
+ }
404
+ static keys(arr = []) {
405
+ if (Array.isArray(arr)) {
406
+ return arr.reduce((acc, item) => {
407
+ acc.push(item.key);
408
+ return acc;
409
+ }, []);
410
+ }
411
+ return [];
412
+ }
413
+ static mapToKeyValue(arr = [], keyPath = "key", valuePath = "value") {
414
+ if (!Array.isArray(arr)) {
415
+ return [];
416
+ }
417
+ return arr.reduce((acc, item) => {
418
+ if (item && typeof item === "object") {
419
+ const key = objectHelper.get(item, keyPath);
420
+ const value = objectHelper.get(item, valuePath);
421
+ if (key !== void 0 && key !== null) {
422
+ acc.push(this.init({
423
+ key,
424
+ value: value !== void 0 ? value : ""
425
+ }));
426
+ }
427
+ }
428
+ return acc;
429
+ }, []);
430
+ }
431
+ static merge(toArr, fromArr) {
432
+ (fromArr || []).map((from) => {
433
+ const found = toArr.find((to) => {
434
+ return to.key === from.key;
435
+ });
436
+ if (found) {
437
+ found.value = _mergeValues$1(from.value, found.value);
438
+ } else {
439
+ toArr.push(from);
440
+ }
441
+ });
442
+ return toArr;
443
+ }
444
+ static removeByKey(arr, key) {
445
+ return arr.reduce((acc, item) => {
446
+ if (!this.sameKey(item, key)) {
447
+ acc.push(item);
448
+ }
449
+ return acc;
450
+ }, []);
451
+ }
452
+ static removeByKeys(arr, keys) {
453
+ return arr.reduce((acc, item) => {
454
+ if (!keys.includes(item.key)) {
455
+ acc.push(item);
456
+ }
457
+ return acc;
458
+ }, []);
459
+ }
460
+ static sameKey(item, key) {
461
+ if (item) {
462
+ return _isSame$1(item.key, key);
463
+ }
464
+ return false;
465
+ }
466
+ static toObject(arr = []) {
467
+ if (Array.isArray(arr)) {
468
+ return arr.reduce((acc, item) => {
469
+ acc[item.key] = item.value;
470
+ return acc;
471
+ }, {});
472
+ }
473
+ return {};
474
+ }
475
+ static toString(arr = [], delimiter = "; ") {
476
+ if (Array.isArray(arr)) {
477
+ return arr.reduce((acc, item) => {
478
+ acc.push(`${item.key}: ${item.value}`);
479
+ return acc;
480
+ }, []).join(delimiter);
481
+ }
482
+ return "";
483
+ }
484
+ static updateRecord(arr = [], key, value) {
485
+ return arr.map((item) => {
486
+ if (this.sameKey(item, key)) {
487
+ return {
488
+ ...item,
489
+ value
490
+ };
491
+ }
492
+ return item;
493
+ });
494
+ }
495
+ static updateOrInsertRecord(arr = [], key, value) {
496
+ return this.insertOrUpdateRecord(arr, key, value);
497
+ }
498
+ static updateRecordsFromArray(arr = [], updateArr = []) {
499
+ if (Array.isArray(arr) && Array.isArray(updateArr)) {
500
+ const obj1 = this.toObject(arr);
501
+ const obj2 = this.toObject(updateArr);
502
+ return this.fromObject({
503
+ ...obj1,
504
+ ...obj2
505
+ });
506
+ }
507
+ return [];
508
+ }
509
+ static values(arr = []) {
510
+ if (Array.isArray(arr)) {
511
+ return arr.reduce((acc, item) => {
512
+ acc.push(item.value);
513
+ return acc;
514
+ }, []);
515
+ }
516
+ return [];
517
+ }
518
+ // getters
519
+ get isValid() {
520
+ return !!this.key;
521
+ }
522
+ get toObject() {
523
+ const obj = {};
524
+ if (this.isValid) {
525
+ obj[this.key] = this.value;
526
+ }
527
+ return obj;
528
+ }
529
+ }
530
+ function _mergeValues$1(existingValue, newValue) {
531
+ if (existingValue === void 0)
532
+ return newValue;
533
+ if (Array.isArray(existingValue) && Array.isArray(newValue)) {
534
+ return [.../* @__PURE__ */ new Set([...existingValue, ...newValue])];
535
+ }
536
+ if (typeof existingValue === "object" && typeof newValue === "object" && !Array.isArray(existingValue) && !Array.isArray(newValue)) {
537
+ return { ...existingValue, ...newValue };
538
+ }
539
+ return newValue;
540
+ }
541
+ function _isSame$1(key1, key2) {
542
+ return key1 === key2;
543
+ }
544
+ function getValidation(rule, data, getDataByKey = _getDataByKey, KeyValueObject$1 = KeyValueObject) {
545
+ if (!rule) {
546
+ return true;
547
+ }
548
+ if (typeof getDataByKey !== "function" || KeyValueObject$1 && typeof KeyValueObject$1 !== "function") {
549
+ return false;
550
+ }
551
+ const { key = "", value, placeholder, keyValuePath = "" } = rule;
552
+ const [valueAttribute] = Object.keys(value);
553
+ if (!key && typeof placeholder === "undefined") {
554
+ switch (valueAttribute) {
555
+ case "$and": {
556
+ return value.$and.reduce((acc, item) => acc && getValidation(item, data, getDataByKey, KeyValueObject$1), true);
557
+ }
558
+ case "$or": {
559
+ return value.$or.reduce((acc, item) => acc || getValidation(item, data, getDataByKey, KeyValueObject$1), false);
560
+ }
561
+ default:
562
+ return false;
563
+ }
564
+ }
565
+ let rowValue = typeof placeholder === "undefined" ? getDataByKey(key, data) : placeholder;
566
+ if (keyValuePath) {
567
+ const rowValueData = KeyValueObject$1.toObject(rowValue);
568
+ rowValue = getDataByKey(keyValuePath, rowValueData);
569
+ }
570
+ switch (valueAttribute) {
571
+ case "$after": {
572
+ if (isConvertibleToNumber(value == null ? void 0 : value.$after)) {
573
+ const _value = Number(String(value == null ? void 0 : value.$after));
574
+ return Date.now() > _value;
575
+ }
576
+ return false;
577
+ }
578
+ case "$before": {
579
+ if (isConvertibleToNumber(value == null ? void 0 : value.$before)) {
580
+ const _value = Number(String(value == null ? void 0 : value.$before));
581
+ return Date.now() < _value;
582
+ }
583
+ return false;
584
+ }
585
+ case "$empty": {
586
+ const isEmpty = rowValue === null || rowValue === void 0;
587
+ return isEmpty === value.$empty;
588
+ }
589
+ case "$eq": {
590
+ return rowValue === value.$eq;
591
+ }
592
+ case "$gt": {
593
+ return rowValue > value.$gt;
594
+ }
595
+ case "$gte": {
596
+ return rowValue >= value.$gte;
597
+ }
598
+ case "$hasOverlap": {
599
+ return _hasOverlap(rowValue, value.$hasOverlap);
600
+ }
601
+ case "$lt": {
602
+ return rowValue < value.$lt;
603
+ }
604
+ case "$lte": {
605
+ return rowValue <= value.$lte;
606
+ }
607
+ case "$in": {
608
+ if (Array.isArray(rowValue)) {
609
+ return !!rowValue.find((e) => value.$in.includes(e));
610
+ }
611
+ if (typeof rowValue !== "object") {
612
+ return !!value.$in.includes(rowValue);
613
+ }
614
+ return false;
615
+ }
616
+ case "$includes": {
617
+ if (Array.isArray(rowValue)) {
618
+ return rowValue.includes(value.$includes);
619
+ }
620
+ return false;
621
+ }
622
+ case "$intervalTimeGt": {
623
+ const now = (/* @__PURE__ */ new Date()).getTime();
624
+ const timestamp = new Date(rowValue).getTime();
625
+ return now - timestamp > value.$intervalTimeGt;
626
+ }
627
+ case "$intervalTimeLt": {
628
+ const now = (/* @__PURE__ */ new Date()).getTime();
629
+ const timestamp = new Date(rowValue).getTime();
630
+ return now - timestamp < value.$intervalTimeLt;
631
+ }
632
+ case "$inValue": {
633
+ const result = getDataByKey(value.$inValue, data);
634
+ const _value = Array.isArray(result) ? result : [];
635
+ if (Array.isArray(rowValue)) {
636
+ return !!rowValue.find((e) => _value.includes(e));
637
+ }
638
+ if (typeof rowValue === "string") {
639
+ return !!_value.includes(rowValue);
640
+ }
641
+ return false;
642
+ }
643
+ case "$isToday": {
644
+ const currentDate = /* @__PURE__ */ new Date();
645
+ const start = currentDate.setHours(0, 0, 0, 0);
646
+ const end = currentDate.setHours(23, 59, 59, 59);
647
+ const dateValue = new Date(rowValue).getTime();
648
+ return (start <= dateValue && end >= dateValue) === value.$isToday;
649
+ }
650
+ case "$ne": {
651
+ return rowValue !== value.$ne;
652
+ }
653
+ case "$notIn": {
654
+ if (Array.isArray(rowValue)) {
655
+ return !rowValue.find((e) => value.$notIn.includes(e));
656
+ }
657
+ if (typeof rowValue !== "object") {
658
+ return !value.$notIn.includes(rowValue);
659
+ }
660
+ return false;
661
+ }
662
+ case "$notInValue": {
663
+ const result = getDataByKey(value.$notInValue, data);
664
+ const _value = Array.isArray(result) ? result : [];
665
+ if (Array.isArray(rowValue)) {
666
+ return !rowValue.find((e) => _value.includes(e));
667
+ }
668
+ if (typeof rowValue !== "object") {
669
+ return !_value.includes(rowValue);
670
+ }
671
+ return false;
672
+ }
673
+ case "$range": {
674
+ const [min, max] = value.$range;
675
+ if (typeof min === "number" && typeof max === "number" && rowValue >= min && rowValue <= max) {
676
+ return true;
677
+ }
678
+ return false;
679
+ }
680
+ default:
681
+ return false;
682
+ }
683
+ }
684
+ function _getDataByKey(key, data) {
685
+ return getValueByKeys(key.split("."), data);
686
+ }
687
+ function _hasOverlap(item1, item2) {
688
+ let arr1 = item1;
689
+ let arr2 = item2;
690
+ if (typeof arr1 === "string") {
691
+ arr1 = arr1.split(",");
692
+ }
693
+ if (typeof arr2 === "string") {
694
+ arr2 = arr2.split(",");
695
+ }
696
+ const set1 = new Set(arr1);
697
+ return arr2.find((i) => set1.has(i));
698
+ }
699
+ function formatDate(date, format) {
700
+ const _date = date && date instanceof Date ? date : new Date(date);
701
+ const dayMapChi = ["日", "一", "二", "三", "四", "五", "六"];
702
+ const dayMapEng = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
703
+ const dayMapEngShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
704
+ const _format = format || "YYYY/MM/DD hh:mm";
705
+ const e = _date.getDay();
706
+ const ee = dayMapEngShort[e];
707
+ const eee = dayMapChi[e];
708
+ const eeee = dayMapEng[e];
709
+ const y = _date.getFullYear();
710
+ const m = _date.getMonth() + 1;
711
+ const d = _date.getDate();
712
+ const h = _date.getHours();
713
+ const mm = _date.getMinutes();
714
+ const s = _date.getSeconds();
715
+ return _format.replace("YYYY", y).replace("MM", padding$1(m)).replace("MM", padding$1(m)).replace("DD", padding$1(d)).replace("hh", padding$1(h)).replace("mm", padding$1(mm)).replace("ss", padding$1(s)).replace("M", m).replace("D", d).replace("h", h).replace("m", mm).replace("s", s).replace("EEEE", padding$1(eeee)).replace("EEE", padding$1(eee)).replace("EE", padding$1(ee)).replace("E", padding$1(e));
716
+ }
717
+ function padding$1(m) {
718
+ return m < 10 ? `0${m}` : m;
719
+ }
720
+ const TEMPLATE_COMPILER_EXCEPTION_TYPE = {
721
+ argumentEmptyException: "Argument is empty",
722
+ argumentFormatException: "Incorrect number or format of argument",
723
+ invalidFuntionException: "Function Name is invalid",
724
+ invalidRegExpException: "Invalid regular expression",
725
+ isNotAFunctionException: "Is not a function",
726
+ notExistException: "Key does not exist",
727
+ resultEmptyException: "Result is empty",
728
+ resultMoreThanOneException: "More than one result"
729
+ };
730
+ class TemplateCompilerException extends Error {
731
+ constructor(message) {
732
+ super(message);
733
+ this.message = message;
734
+ }
735
+ }
736
+ const _EMPTY = "_EMPTY";
737
+ const _FN_NAMES = [
738
+ "concatIf",
739
+ "divide",
740
+ "eq",
741
+ "exec",
742
+ "filterAll",
743
+ "filterOne",
744
+ "formatDate",
745
+ "get",
746
+ "gt",
747
+ "gte",
748
+ "isEmpty",
749
+ "isNotEmpty",
750
+ "join",
751
+ "lt",
752
+ "lte",
753
+ "map",
754
+ "neq",
755
+ "removeHtml",
756
+ "replaceChar",
757
+ "sum",
758
+ "toLowerCase",
759
+ "toUpperCase"
760
+ ];
761
+ const _HIDE = "_HIDE";
762
+ const _NOT_EMPTY = "_NOT_EMPTY";
763
+ const _SELF = "_SELF";
764
+ const TAGS_EJS = ["<%=", "%>"];
765
+ const TAGS_HANDLEBAR = ["{{", "}}"];
766
+ function _concatIf(data, args) {
767
+ if (typeof data !== "string") {
768
+ throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string :${data.join(", ")}`);
769
+ }
770
+ if (args.length !== 3) {
771
+ throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
772
+ }
773
+ if (data === null || typeof data === "undefined") {
774
+ return null;
775
+ }
776
+ const [condition, success, failover] = args;
777
+ const validConditions = [_EMPTY, _NOT_EMPTY];
778
+ if (validConditions.includes(condition) || success.length !== 2) {
779
+ throw new TemplateCompilerException(`concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException}: ${condition}, ${success}`);
780
+ }
781
+ if (data === "" && failover.includes(_HIDE)) {
782
+ return "";
783
+ }
784
+ if (data !== "" && (data !== null || data !== void 0) && failover.includes(_HIDE)) {
785
+ return `${success[0]}${data}${success[success.length - 1]}`;
786
+ }
787
+ return failover;
788
+ }
789
+ function _divide(value, divisor) {
790
+ try {
791
+ if (Number.isNaN(value)) {
792
+ return value;
793
+ }
794
+ return value / divisor;
795
+ } catch (e) {
796
+ throw e;
797
+ }
798
+ }
799
+ function _eq(data, args) {
800
+ if (args.length !== 3) {
801
+ throw new TemplateCompilerException(`eq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
802
+ }
803
+ if (data === null || typeof data === "undefined") {
804
+ return null;
805
+ }
806
+ if (args.includes(_SELF)) {
807
+ args = args.map((arg) => {
808
+ return arg === _SELF ? data : arg;
809
+ });
810
+ }
811
+ const expected = args[0];
812
+ return data === expected ? args[1] : args[2];
813
+ }
814
+ function _exec(data, args) {
815
+ try {
816
+ const [methodName, ..._args] = args;
817
+ return data[methodName](..._args);
818
+ } catch (e) {
819
+ throw e;
820
+ }
821
+ }
822
+ function _filterAll(data, args) {
823
+ try {
824
+ if (!Array.isArray(args) || args.length === 0) {
825
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException);
826
+ }
827
+ if (!Array.isArray(data) || data.length === 0) {
828
+ return [];
829
+ }
830
+ if (typeof data[0] === "object") {
831
+ return _existObject(data, args);
832
+ }
833
+ if (typeof data[0] === "string" || typeof data[0] === "number") {
834
+ return _exist(data, args);
835
+ }
836
+ return [];
837
+ } catch (e) {
838
+ throw e;
839
+ }
840
+ }
841
+ function _exist(data, args) {
842
+ const _args = args.flat();
843
+ return data.filter((e) => _args.some((arg) => _performOperation(arg, e)));
844
+ }
845
+ function _existObject(data, args) {
846
+ if (args.length === 1) {
847
+ const arg = args[0];
848
+ return data.filter((e) => {
849
+ if (arg.includes(".")) {
850
+ return getValueByKeys(arg.split("."), e);
851
+ }
852
+ return Object.prototype.hasOwnProperty.call(e, arg);
853
+ });
854
+ }
855
+ if (args.length > 2) {
856
+ let res = data;
857
+ for (let i = 0; i < args.length; i += 2) {
858
+ const group = [args[i], args[i + 1]];
859
+ res = _existObject(res, group);
860
+ }
861
+ return res;
862
+ }
863
+ const [key, ..._argsArr] = args;
864
+ const _args = _argsArr.flat();
865
+ return data.filter((e) => {
866
+ const value = key.includes(".") ? getValueByKeys(key.split("."), e) : e[key];
867
+ return _args.some((arg) => _performOperation(arg, value));
868
+ });
869
+ }
870
+ function _performOperation(arg, value) {
871
+ if (arg === void 0 && value === void 0)
872
+ return true;
873
+ if (arg === null && value === null)
874
+ return true;
875
+ if (typeof arg === "boolean") {
876
+ return arg === value;
877
+ }
878
+ if (arg === "" || arg === "*") {
879
+ if (value === null || value === void 0) {
880
+ return false;
881
+ }
882
+ if (typeof value === "string") {
883
+ return arg === "" ? value === "" : value !== "";
884
+ }
885
+ if (Array.isArray(value)) {
886
+ return arg === "" ? value.length === 0 : value.length !== 0;
887
+ }
888
+ return arg !== "";
889
+ }
890
+ if (_isPureStringOrNumber(arg)) {
891
+ return arg === value;
892
+ }
893
+ if (arg.startsWith("[") && arg.endsWith("]")) {
894
+ if (arg === "[]") {
895
+ return Array.isArray(value) && value.length === 0;
896
+ }
897
+ if (arg === "[*]") {
898
+ return Array.isArray(value) && value.length !== 0;
899
+ }
900
+ return false;
901
+ }
902
+ const { operator, value: argValue } = _splitOperator(arg);
903
+ if (!operator || argValue !== 0 && !argValue) {
904
+ return false;
905
+ }
906
+ switch (operator) {
907
+ case ">":
908
+ return value > argValue;
909
+ case "<":
910
+ return value < argValue;
911
+ case "!=":
912
+ return value !== argValue;
913
+ case ">=":
914
+ return value >= argValue;
915
+ case "<=":
916
+ return value <= argValue;
917
+ default:
918
+ return false;
919
+ }
920
+ }
921
+ function _isPureStringOrNumber(input) {
922
+ if (typeof input === "string") {
923
+ if (input.startsWith("[") && input.endsWith("]")) {
924
+ return false;
925
+ }
926
+ if (/!=|>=|<=|>|</.test(input)) {
927
+ return false;
928
+ }
929
+ return true;
930
+ }
931
+ return !Number.isNaN(input);
932
+ }
933
+ function _splitOperator(str) {
934
+ const operators = ["!=", ">=", "<=", ">", "<"];
935
+ const matchedOp = operators.find((op) => str.startsWith(op));
936
+ if (!matchedOp)
937
+ return { operator: null, value: null };
938
+ const remaining = str.slice(matchedOp.length);
939
+ if (/^[a-z]*$/i.test(remaining) && matchedOp !== "!=") {
940
+ return { operator: null, value: null };
941
+ }
942
+ const value = !Number.isNaN(Number.parseFloat(remaining)) && !Number.isNaN(remaining) ? Number(remaining) : remaining;
943
+ return {
944
+ operator: matchedOp,
945
+ value
946
+ };
947
+ }
948
+ function _filterOne(data, args) {
949
+ try {
950
+ const list = _filterAll(data, args);
951
+ if (list.length === 1) {
952
+ return list[0];
953
+ }
954
+ if (list.length === 0) {
955
+ return null;
956
+ }
957
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.resultMoreThanOneException);
958
+ } catch (e) {
959
+ throw e;
960
+ }
961
+ }
962
+ function _formatDate(timestamp, format) {
963
+ if (format.length === 0) {
964
+ throw new TemplateCompilerException(`_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: format parts must be not empty array`);
965
+ }
966
+ if (timestamp === null || timestamp === void 0) {
967
+ return null;
968
+ }
969
+ const date = new Date(timestamp);
970
+ const partsMap = {
971
+ yyyy: String(date.getFullYear()),
972
+ mm: String(date.getMonth() + 1).padStart(2, "0"),
973
+ dd: String(date.getDate()).padStart(2, "0")
974
+ };
975
+ const validTokens = ["yyyy", "mm", "dd"];
976
+ const invalidTokens = format.filter((part) => part.length > 1 && !validTokens.includes(part));
977
+ if (invalidTokens.length > 0) {
978
+ throw new TemplateCompilerException(
979
+ `_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the format type is not valid: ${format.join(", ")}`
980
+ );
981
+ }
982
+ return format.reduce((result, part) => result + (partsMap[part] || part), "");
983
+ }
984
+ function _get(data, key, failover = null) {
985
+ try {
986
+ if (key === null || typeof key === "undefined" || key === "") {
987
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException);
988
+ }
989
+ if (data === null) {
990
+ return null;
991
+ }
992
+ if (key.includes(".")) {
993
+ const parts = key.split(".");
994
+ if (parts.length > 1) {
995
+ const first = parts.shift();
996
+ const remainingKey = parts.join(".");
997
+ if (typeof data[first] !== "undefined") {
998
+ return _get(data[first], remainingKey, failover);
999
+ }
1000
+ return _handleFailover(key, failover);
1001
+ }
1002
+ }
1003
+ if (typeof data[key] !== "undefined") {
1004
+ return data[key];
1005
+ }
1006
+ return _handleFailover(key, failover);
1007
+ } catch (e) {
1008
+ throw e;
1009
+ }
1010
+ }
1011
+ function _handleFailover(key, failover) {
1012
+ if (failover !== null) {
1013
+ return failover;
1014
+ }
1015
+ return null;
1016
+ }
1017
+ function _gt(data, args) {
1018
+ if (args.length !== 3) {
1019
+ throw new TemplateCompilerException(`_gt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1020
+ }
1021
+ if (data === null || typeof data === "undefined") {
1022
+ return null;
1023
+ }
1024
+ if (args.includes(_SELF)) {
1025
+ args = args.map((arg) => {
1026
+ return arg === _SELF ? data : arg;
1027
+ });
1028
+ }
1029
+ const expected = args[0];
1030
+ return data > expected ? args[1] : args[2];
1031
+ }
1032
+ function _gte(data, args) {
1033
+ if (args.length !== 3) {
1034
+ throw new TemplateCompilerException(`_gte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1035
+ }
1036
+ if (data === null || typeof data === "undefined") {
1037
+ return null;
1038
+ }
1039
+ if (args.includes(_SELF)) {
1040
+ args = args.map((arg) => {
1041
+ return arg === _SELF ? data : arg;
1042
+ });
1043
+ }
1044
+ const expected = args[0];
1045
+ return data >= expected ? args[1] : args[2];
1046
+ }
1047
+ function _isEmpty(data, args) {
1048
+ if (args.length !== 2) {
1049
+ throw new TemplateCompilerException(`_isEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1050
+ }
1051
+ if (args.includes(_SELF)) {
1052
+ args = args.map((arg) => {
1053
+ return arg === _SELF ? data : arg;
1054
+ });
1055
+ }
1056
+ if (data !== null && typeof data === "object" && Object.keys(data).length === 0) {
1057
+ return args[0];
1058
+ }
1059
+ return data === "" || data === null || data === void 0 || data.length === 0 ? args[0] : args[1];
1060
+ }
1061
+ function _isNotEmpty(data, args) {
1062
+ if (args.length !== 2) {
1063
+ throw new TemplateCompilerException(`_isNotEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1064
+ }
1065
+ if (args.includes(_SELF)) {
1066
+ args = args.map((arg) => {
1067
+ return arg === _SELF ? data : arg;
1068
+ });
1069
+ }
1070
+ if (data !== null && typeof data === "object" && Object.keys(data).length === 0) {
1071
+ return args[1];
1072
+ }
1073
+ if (Array.isArray(data) && data.length === 0) {
1074
+ return args[1];
1075
+ }
1076
+ if (typeof data === "string" && data === "") {
1077
+ return args[1];
1078
+ }
1079
+ if (data === null || data === void 0) {
1080
+ return args[1];
1081
+ }
1082
+ return args[0];
1083
+ }
1084
+ function _join(data, delimiter) {
1085
+ try {
1086
+ if (data.length === 0)
1087
+ return "";
1088
+ if (data.length === 1)
1089
+ return _stringifyObject(data[0]);
1090
+ return data.map((item) => _stringifyObject(item)).join(delimiter);
1091
+ } catch (e) {
1092
+ throw e;
1093
+ }
1094
+ }
1095
+ function _stringifyObject(obj) {
1096
+ return JSON.stringify(obj).replace(/"([^"]+)":/g, "$1: ").replace(/"([^"]+)"/g, "$1").replace(/,/g, ", ");
1097
+ }
1098
+ function _lt(data, args) {
1099
+ if (args.length !== 3) {
1100
+ throw new TemplateCompilerException(`_lt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1101
+ }
1102
+ if (data === null || typeof data === "undefined") {
1103
+ return null;
1104
+ }
1105
+ if (args.includes(_SELF)) {
1106
+ args = args.map((arg) => {
1107
+ return arg === _SELF ? data : arg;
1108
+ });
1109
+ }
1110
+ const expected = args[0];
1111
+ return data < expected ? args[1] : args[2];
1112
+ }
1113
+ function _lte(data, args) {
1114
+ if (args.length !== 3) {
1115
+ throw new TemplateCompilerException(`_lte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1116
+ }
1117
+ if (data === null || typeof data === "undefined") {
1118
+ return null;
1119
+ }
1120
+ if (args.includes(_SELF)) {
1121
+ args = args.map((arg) => {
1122
+ return arg === _SELF ? data : arg;
1123
+ });
1124
+ }
1125
+ const expected = args[0];
1126
+ return data <= expected ? args[1] : args[2];
1127
+ }
1128
+ function _map(data, args) {
1129
+ try {
1130
+ if (args.length === 0) {
1131
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException);
1132
+ }
1133
+ if (data === null || typeof data === "undefined") {
1134
+ return null;
1135
+ }
1136
+ const result = data.reduce((acc, item) => {
1137
+ if (args.length === 1 && Array.isArray(args[0])) {
1138
+ args = args[0];
1139
+ acc.hasFormat = true;
1140
+ }
1141
+ const list = args.map((key) => {
1142
+ if (key.includes(".")) {
1143
+ const parts = key.split(".");
1144
+ const first = parts[0];
1145
+ parts.shift();
1146
+ const remainingKey = parts.join(".");
1147
+ return _get(item[first], remainingKey);
1148
+ }
1149
+ if (typeof item[key] !== "undefined") {
1150
+ return item[key];
1151
+ }
1152
+ return null;
1153
+ });
1154
+ if (acc.hasFormat) {
1155
+ acc.content.push(list);
1156
+ } else {
1157
+ acc.content = acc.content.concat(list);
1158
+ }
1159
+ return acc;
1160
+ }, {
1161
+ content: [],
1162
+ hasFormat: false
1163
+ });
1164
+ return result.content;
1165
+ } catch (e) {
1166
+ throw e;
1167
+ }
1168
+ }
1169
+ function _neq(data, args) {
1170
+ if (args.length !== 3) {
1171
+ throw new TemplateCompilerException(`_neq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1172
+ }
1173
+ if (data === null || typeof data === "undefined") {
1174
+ return null;
1175
+ }
1176
+ if (args.includes(_SELF)) {
1177
+ args = args.map((arg) => {
1178
+ return arg === _SELF ? data : arg;
1179
+ });
1180
+ }
1181
+ const expected = args[0];
1182
+ return data !== expected ? args[1] : args[2];
1183
+ }
1184
+ function _removeHtml(html, args) {
1185
+ if (html === null || html === void 0) {
1186
+ return null;
1187
+ }
1188
+ if (!Array.isArray(args)) {
1189
+ throw new TemplateCompilerException(`_removeHtml: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: args parts must be array`);
1190
+ }
1191
+ return _htmlToPlainText(html, args[0]);
1192
+ }
1193
+ function _htmlToPlainText(html, delimiter = "\n") {
1194
+ if (typeof delimiter !== "string") {
1195
+ delimiter = "\n";
1196
+ }
1197
+ const decodedHtml = html.replace(/&nbsp;/g, " ").replace(/\s+/g, " ");
1198
+ let text = decodedHtml.replace(/<\/?(p|div|h[1-6]|ul|ol|li|pre|section|article|table|tr|td|th)(\s[^>]*)?>/gi, "~~~").replace(/<br\s*\/?>/gi, "~~~").replace(/<[^>]+>/g, "").replace(/~{3,}/g, delimiter).trim();
1199
+ if (delimiter === "") {
1200
+ text = text.replace(/\s+/g, " ");
1201
+ } else {
1202
+ text = text.replace(new RegExp(`${escapeRegExp(delimiter)}+`, "g"), delimiter);
1203
+ text = text.replace(new RegExp(`^${escapeRegExp(delimiter)}|${escapeRegExp(delimiter)}$`, "g"), "");
1204
+ }
1205
+ return text;
1206
+ }
1207
+ function escapeRegExp(string) {
1208
+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1209
+ }
1210
+ function _replaceChar(str, args) {
1211
+ if (str === null || str === void 0) {
1212
+ return null;
1213
+ }
1214
+ if (!Array.isArray(args)) {
1215
+ throw new TemplateCompilerException(`_replaceChar: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: args parts must be array`);
1216
+ }
1217
+ return _findAndReplace(str, args[0], args[1]);
1218
+ }
1219
+ function _findAndReplace(str, find, replace) {
1220
+ if (!str || !find) {
1221
+ return str;
1222
+ }
1223
+ return str.replace(new RegExp(find, "g"), replace);
1224
+ }
1225
+ function _sum(data, args) {
1226
+ if (Number.isNaN(data) || data === null || typeof data === "undefined" || data === "") {
1227
+ return data;
1228
+ }
1229
+ return args.reduce((acc, e) => acc + e, data);
1230
+ }
1231
+ function _toLowerCase(data, args) {
1232
+ if (args !== void 0) {
1233
+ throw new TemplateCompilerException(`_toLowerCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(", ")}`);
1234
+ }
1235
+ if (data === null || typeof data === "undefined" || typeof data !== "string") {
1236
+ return null;
1237
+ }
1238
+ return String(data).toLowerCase();
1239
+ }
1240
+ function _toUpperCase(data, args) {
1241
+ if (typeof data !== "string") {
1242
+ throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string: ${data}`);
1243
+ }
1244
+ if (args !== void 0) {
1245
+ throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the argument must be empty: ${args.join(", ")}`);
1246
+ }
1247
+ if (data === null || typeof data === "undefined" || typeof data !== "string") {
1248
+ return null;
1249
+ }
1250
+ return String(data).toUpperCase();
1251
+ }
1252
+ class TemplateCompiler {
1253
+ constructor(data) {
1254
+ this.data = data;
1255
+ }
1256
+ static init(options) {
1257
+ return new this(options);
1258
+ }
1259
+ static initFromArray(arr = []) {
1260
+ if (Array.isArray(arr)) {
1261
+ return arr.map((a) => this.init(a));
1262
+ }
1263
+ return [];
1264
+ }
1265
+ static initOnlyValidFromArray(arr = []) {
1266
+ return this.initFromArray(arr).filter((i) => i);
1267
+ }
1268
+ static concatIf(data, args) {
1269
+ return _concatIf(data, args);
1270
+ }
1271
+ static divide(data, args) {
1272
+ return _divide(data, args);
1273
+ }
1274
+ static eq(data, args) {
1275
+ return _eq(data, args);
1276
+ }
1277
+ static filterAll(data, args) {
1278
+ return _filterAll(data, args);
1279
+ }
1280
+ static formatDate(data, args) {
1281
+ return _formatDate(data, args);
1282
+ }
1283
+ static get(data, key, failover = null) {
1284
+ return _get(data, key, failover);
1285
+ }
1286
+ static gt(data, args) {
1287
+ return _gt(data, args);
1288
+ }
1289
+ static gte(data, args) {
1290
+ return _gte(data, args);
1291
+ }
1292
+ static isEmpty(data, args) {
1293
+ return _isEmpty(data, args);
1294
+ }
1295
+ static isNotEmpty(data, args) {
1296
+ return _isNotEmpty(data, args);
1297
+ }
1298
+ static join(data, separator = "") {
1299
+ return _join(data, separator);
1300
+ }
1301
+ static lt(data, args) {
1302
+ return _lt(data, args);
1303
+ }
1304
+ static lte(data, args) {
1305
+ return _lte(data, args);
1306
+ }
1307
+ static map(data, args = []) {
1308
+ return _map(data, args);
1309
+ }
1310
+ static neq(data, args) {
1311
+ return _neq(data, args);
1312
+ }
1313
+ static removeHtml(data, args) {
1314
+ return _removeHtml(data, args);
1315
+ }
1316
+ static replaceChar(data, args) {
1317
+ return _replaceChar(data, args);
1318
+ }
1319
+ static sum(data, args) {
1320
+ return _sum(data, args);
1321
+ }
1322
+ static toLowerCase(data, args) {
1323
+ return _toLowerCase(data, args);
1324
+ }
1325
+ static toUpperCase(data, args) {
1326
+ return _toUpperCase(data, args);
1327
+ }
1328
+ static parseFunction(expression) {
1329
+ return _parseFunction(expression, _FN_NAMES);
1330
+ }
1331
+ static parseParams(parameters) {
1332
+ return _parseParams(parameters);
1333
+ }
1334
+ pipe(expression = "") {
1335
+ this.delimiters = expression.substring(0, 2) === "{{" ? TAGS_HANDLEBAR : TAGS_EJS;
1336
+ const regex = new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`);
1337
+ const match = expression.match(regex);
1338
+ if (match !== null) {
1339
+ try {
1340
+ const functionList = _parseFunction(match[1], _FN_NAMES);
1341
+ return functionList.reduce((acc, fn) => {
1342
+ return _callFunction(acc, fn.name, fn.args);
1343
+ }, this.data);
1344
+ } catch (e) {
1345
+ throw new TemplateCompilerException(`TemplateCompiler engine error: ${e.message}`);
1346
+ }
1347
+ }
1348
+ throw new TemplateCompilerException(`TemplateCompiler engine error: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.invalidRegExpException}`);
1349
+ }
1350
+ }
1351
+ function _parseFunction(expression, existFunctionNames) {
1352
+ const functionRegex = /(\w+)\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)/;
1353
+ let parts;
1354
+ if (expression.includes("|")) {
1355
+ parts = [];
1356
+ let currentPart = "";
1357
+ let parenCount = 0;
1358
+ let quoteChar = null;
1359
+ for (let i = 0; i < expression.length; i++) {
1360
+ const char = expression[i];
1361
+ if ((char === '"' || char === "'") && (i === 0 || expression[i - 1] !== "\\")) {
1362
+ if (quoteChar === char) {
1363
+ quoteChar = null;
1364
+ } else if (quoteChar === null) {
1365
+ quoteChar = char;
1366
+ }
1367
+ currentPart += char;
1368
+ continue;
1369
+ }
1370
+ if (quoteChar === null) {
1371
+ if (char === "(") {
1372
+ parenCount++;
1373
+ } else if (char === ")") {
1374
+ parenCount--;
1375
+ }
1376
+ }
1377
+ if (char === "|" && parenCount === 0 && quoteChar === null) {
1378
+ parts.push(currentPart);
1379
+ currentPart = "";
1380
+ } else {
1381
+ currentPart += char;
1382
+ }
1383
+ }
1384
+ if (currentPart) {
1385
+ parts.push(currentPart);
1386
+ }
1387
+ } else {
1388
+ parts = [expression];
1389
+ }
1390
+ return parts.reduce((acc, part) => {
1391
+ const match = part.match(functionRegex);
1392
+ if (match !== null) {
1393
+ const functionName = match[1];
1394
+ const parameters = match[2];
1395
+ const paramList = _parseParams(parameters);
1396
+ if (existFunctionNames.includes(functionName)) {
1397
+ acc.push({
1398
+ name: functionName,
1399
+ args: paramList
1400
+ });
1401
+ } else {
1402
+ throw new TemplateCompilerException(`${functionName} is not a valid function`);
1403
+ }
1404
+ }
1405
+ return acc;
1406
+ }, []);
1407
+ }
1408
+ function _parseParams(parameters) {
1409
+ const _parameters = parameters.trim();
1410
+ if (!_parameters) return [];
1411
+ if (_parameters.includes(",")) {
1412
+ const parts = _splitParamsRespectingContext(_parameters);
1413
+ return parts.map((part) => _parseSinglePart(part.trim()));
1414
+ }
1415
+ return [_parseSinglePart(_parameters)];
1416
+ }
1417
+ function _splitParamsRespectingContext(str) {
1418
+ const parts = [];
1419
+ let current = "";
1420
+ let bracketDepth = 0;
1421
+ let parenDepth = 0;
1422
+ let quoteChar = null;
1423
+ for (let i = 0; i < str.length; i++) {
1424
+ const char = str[i];
1425
+ if ((char === '"' || char === "'") && (i === 0 || str[i - 1] !== "\\")) {
1426
+ if (quoteChar === char) {
1427
+ quoteChar = null;
1428
+ } else if (quoteChar === null) {
1429
+ quoteChar = char;
1430
+ }
1431
+ current += char;
1432
+ continue;
1433
+ }
1434
+ if (quoteChar !== null) {
1435
+ current += char;
1436
+ continue;
1437
+ }
1438
+ if (char === "[") {
1439
+ bracketDepth++;
1440
+ } else if (char === "]") {
1441
+ bracketDepth--;
1442
+ } else if (char === "(") {
1443
+ parenDepth++;
1444
+ } else if (char === ")") {
1445
+ parenDepth--;
1446
+ }
1447
+ if (char === "," && quoteChar === null && bracketDepth === 0 && parenDepth === 0) {
1448
+ parts.push(current);
1449
+ current = "";
1450
+ } else {
1451
+ current += char;
1452
+ }
1453
+ }
1454
+ if (current) {
1455
+ parts.push(current);
1456
+ }
1457
+ return parts;
1458
+ }
1459
+ function _parseSinglePart(input) {
1460
+ if (typeof input !== "string") {
1461
+ return input;
1462
+ }
1463
+ const trimmed = input.trim();
1464
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
1465
+ return trimmed.substring(1, trimmed.length - 1);
1466
+ }
1467
+ const basicType = _toBasicType(trimmed);
1468
+ if (typeof basicType !== "string") {
1469
+ return basicType;
1470
+ }
1471
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
1472
+ return _parseArrayContent(trimmed);
1473
+ }
1474
+ return input;
1475
+ }
1476
+ function _parseArrayContent(arrayStr) {
1477
+ const content = arrayStr.substring(1, arrayStr.length - 1).trim();
1478
+ if (!content) return [];
1479
+ const items = [];
1480
+ let current = "";
1481
+ let quoteChar = null;
1482
+ for (let i = 0; i < content.length; i++) {
1483
+ const char = content[i];
1484
+ if ((char === '"' || char === "'") && (i === 0 || content[i - 1] !== "\\")) {
1485
+ if (quoteChar === char) {
1486
+ quoteChar = null;
1487
+ } else if (quoteChar === null) {
1488
+ quoteChar = char;
1489
+ }
1490
+ current += char;
1491
+ continue;
1492
+ }
1493
+ if (char === "," && quoteChar === null) {
1494
+ if (current.trim()) {
1495
+ items.push(current.trim());
1496
+ }
1497
+ current = "";
1498
+ } else {
1499
+ current += char;
1500
+ }
1501
+ }
1502
+ if (current.trim()) {
1503
+ items.push(current.trim());
1504
+ }
1505
+ return items.map((item) => _parseSinglePart(item));
1506
+ }
1507
+ function _toBasicType(input) {
1508
+ if (input.startsWith('"') && input.endsWith('"')) {
1509
+ return input.substring(1, input.length - 1);
1510
+ }
1511
+ if (input.startsWith("'") && input.endsWith("'")) {
1512
+ return input.substring(1, input.length - 1);
1513
+ }
1514
+ if (input === "true") {
1515
+ return true;
1516
+ }
1517
+ if (input === "false") {
1518
+ return false;
1519
+ }
1520
+ if (input === "undefined") {
1521
+ return void 0;
1522
+ }
1523
+ if (input === "null") {
1524
+ return null;
1525
+ }
1526
+ if (!Number.isNaN(input) && !Number.isNaN(Number.parseFloat(input))) {
1527
+ return Number(input);
1528
+ }
1529
+ return input;
1530
+ }
1531
+ function _callFunction(data, functionName, parameters) {
1532
+ try {
1533
+ let failover;
1534
+ switch (functionName) {
1535
+ case "concatIf":
1536
+ return _concatIf(data, parameters);
1537
+ case "divide":
1538
+ return _divide(data, parameters);
1539
+ case "eq":
1540
+ return _eq(data, parameters);
1541
+ case "exec":
1542
+ return _exec(data, parameters);
1543
+ case "filterAll":
1544
+ return _filterAll(data, parameters);
1545
+ case "filterOne":
1546
+ return _filterOne(data, parameters);
1547
+ case "formatDate":
1548
+ return _formatDate(data, parameters);
1549
+ case "get":
1550
+ if (parameters.length > 2) {
1551
+ throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException);
1552
+ }
1553
+ if (parameters.length === 2) {
1554
+ failover = parameters[parameters.length - 1];
1555
+ }
1556
+ return _get(data, parameters[0], failover);
1557
+ case "gt":
1558
+ return _gt(data, parameters);
1559
+ case "gte":
1560
+ return _gte(data, parameters);
1561
+ case "isEmpty":
1562
+ return _isEmpty(data, parameters);
1563
+ case "isNotEmpty":
1564
+ return _isNotEmpty(data, parameters);
1565
+ case "join":
1566
+ return _join(data, parameters[0]);
1567
+ case "lt":
1568
+ return _lt(data, parameters);
1569
+ case "lte":
1570
+ return _lte(data, parameters);
1571
+ case "map":
1572
+ return _map(data, parameters);
1573
+ case "neq":
1574
+ return _neq(data, parameters);
1575
+ case "removeHtml":
1576
+ return _removeHtml(data, parameters);
1577
+ case "replaceChar":
1578
+ return _replaceChar(data, parameters);
1579
+ case "sum":
1580
+ return _sum(data, parameters);
1581
+ case "toLowerCase":
1582
+ return _toLowerCase(data);
1583
+ case "toUpperCase":
1584
+ return _toUpperCase(data);
1585
+ default:
1586
+ throw new Error(`${functionName} is not a valid function`);
1587
+ }
1588
+ } catch (e) {
1589
+ throw e;
1590
+ }
1591
+ }
1592
+ function concatStringByArray(arrTemplate, data) {
1593
+ return arrTemplate.reduce((acc, item) => {
1594
+ const { type, value = "", restriction, template, format, showMinutes } = item;
1595
+ switch (type) {
1596
+ case "array": {
1597
+ if (getValidation(restriction, data, getValueByKeys)) {
1598
+ const _value = getValueByKeys(value.split("."), data) || [];
1599
+ acc += _value.reduce((_acc, item2) => {
1600
+ return _acc += concatStringByArray(template, item2);
1601
+ }, "");
1602
+ }
1603
+ break;
1604
+ }
1605
+ case "date": {
1606
+ if (getValidation(restriction, data, getValueByKeys)) {
1607
+ const _value = getValueByKeys(value.split("."), data) || "";
1608
+ acc += formatDate(_value, format).toString();
1609
+ }
1610
+ break;
1611
+ }
1612
+ case "ellipsis": {
1613
+ if (getValidation(restriction, data, getValueByKeys)) {
1614
+ const { maxLength } = item;
1615
+ const _value = getValueByKeys(value.split("."), data) || "";
1616
+ if (_value.length <= maxLength) {
1617
+ acc += _value.toString();
1618
+ } else {
1619
+ acc += `${_value.substr(0, maxLength)}...`;
1620
+ }
1621
+ }
1622
+ break;
1623
+ }
1624
+ case "group": {
1625
+ if (getValidation(restriction, data, getValueByKeys)) {
1626
+ return concatStringByArray(value, data);
1627
+ }
1628
+ break;
1629
+ }
1630
+ case "label": {
1631
+ if (getValidation(restriction, data, getValueByKeys)) {
1632
+ acc += value.toString();
1633
+ }
1634
+ break;
1635
+ }
1636
+ case "templateCompiler": {
1637
+ if (getValidation(restriction, data, getValueByKeys)) {
1638
+ const templateCompiler = new TemplateCompiler({ data });
1639
+ acc += templateCompiler.pipe(value);
1640
+ }
1641
+ break;
1642
+ }
1643
+ case "value": {
1644
+ if (getValidation(restriction, data, getValueByKeys)) {
1645
+ const _value = getValueByKeys(value.split("."), data) || "";
1646
+ acc += _value.toString();
1647
+ }
1648
+ break;
1649
+ }
1650
+ }
1651
+ return acc;
1652
+ }, "");
1653
+ }
1654
+ function convertString(string, patternMatch = /\$\{(.+?)\}/g, value, getValueByKeys$1) {
1655
+ if (!string) {
1656
+ return "";
1657
+ }
1658
+ const _getValueByKeys = typeof getValueByKeys$1 === "function" ? getValueByKeys$1 : getValueByKeys;
1659
+ const reg = new RegExp(patternMatch, "g");
1660
+ return string.replace(reg, (match, key) => {
1661
+ const result = _getValueByKeys({ keys: key.split("."), obj: value });
1662
+ if (result === null || result === void 0) {
1663
+ return "";
1664
+ }
1665
+ return typeof result === "object" ? JSON.stringify(result) : result;
1666
+ });
1667
+ }
1668
+ function create(str, timezoneOffset = 0) {
1669
+ try {
1670
+ if (typeof str === "number") {
1671
+ if (str.toString().length === 10) {
1672
+ str = str * 1e3;
1673
+ }
1674
+ return new Date(str);
1675
+ }
1676
+ if (typeof str === "string" && str.length === 8) {
1677
+ const year = Number.parseInt(str.slice(0, 4), 10);
1678
+ const month = Number.parseInt(str.slice(4, 6), 10) - 1;
1679
+ const day = Number.parseInt(str.slice(6, 8), 10);
1680
+ return new Date(year, month, day);
1681
+ }
1682
+ return new Date(str);
1683
+ } catch (e) {
1684
+ throw new Error("input does not meet the requirements");
1685
+ }
1686
+ }
1687
+ class Handler {
1688
+ constructor({ date, isUTC, is24Hour, timezoneOffset = 0 } = {}) {
1689
+ this.date = date;
1690
+ this.isUTC = isUTC;
1691
+ this.is24Hour = is24Hour;
1692
+ this.timezoneOffset = timezoneOffset;
1693
+ }
1694
+ // Get date component with timezone offset applied
1695
+ getDateComponent(methodName) {
1696
+ if (this.timezoneOffset !== 0) {
1697
+ const offsetMs = this.timezoneOffset * 60 * 1e3;
1698
+ const adjustedDate = new Date(this.date.getTime() + offsetMs);
1699
+ return adjustedDate[`getUTC${methodName}`]();
1700
+ } else if (this.isUTC) {
1701
+ return this.date[`getUTC${methodName}`]();
1702
+ } else {
1703
+ return this.date[`get${methodName}`]();
1704
+ }
1705
+ }
1706
+ process(dateFormat) {
1707
+ return dateFormat;
1708
+ }
1709
+ }
1710
+ function padding(num, char = "0") {
1711
+ if (typeof num !== "number") {
1712
+ throw new TypeError("Parameter must be of number");
1713
+ }
1714
+ return num < 10 ? `${char}${num}` : num;
1715
+ }
1716
+ class HandlerDate extends Handler {
1717
+ process(dateFormat) {
1718
+ const day = this.getDateComponent("Date");
1719
+ dateFormat = dateFormat.replace("DD", padding(day));
1720
+ return dateFormat;
1721
+ }
1722
+ }
1723
+ const MONTH_ENG_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1724
+ class HandlerMonth extends Handler {
1725
+ process(dateFormat) {
1726
+ const month = this.getDateComponent("Month");
1727
+ dateFormat = dateFormat.replace("MMM", MONTH_ENG_SHORT[month]);
1728
+ dateFormat = dateFormat.replace("MM", padding(month + 1));
1729
+ return dateFormat;
1730
+ }
1731
+ }
1732
+ class HandlerYear extends Handler {
1733
+ process(dateFormat) {
1734
+ const year = this.getDateComponent("FullYear");
1735
+ dateFormat = dateFormat.replace("yyyy", year);
1736
+ dateFormat = dateFormat.replace("YYYY", year);
1737
+ dateFormat = dateFormat.replace("yy", year.toString().slice(-2));
1738
+ dateFormat = dateFormat.replace("YY", year.toString().slice(-2));
1739
+ return dateFormat;
1740
+ }
1741
+ }
1742
+ class HandlerTime extends Handler {
1743
+ process(dateFormat) {
1744
+ let hours = this.getDateComponent("Hours");
1745
+ const is12Hour = !this.is24Hour;
1746
+ if (is12Hour && hours > 12) {
1747
+ hours -= 12;
1748
+ }
1749
+ if (is12Hour && hours === 0) {
1750
+ hours = 12;
1751
+ }
1752
+ dateFormat = dateFormat.replace("HH", padding(this.getDateComponent("Hours")));
1753
+ dateFormat = dateFormat.replace("hh", padding(hours));
1754
+ if (!this.is24Hour) {
1755
+ if (dateFormat.includes("A")) {
1756
+ const ampm = this.getDateComponent("Hours") >= 12 ? "PM" : "AM";
1757
+ dateFormat = dateFormat.replace(/\bA\b/g, ampm);
1758
+ }
1759
+ if (dateFormat.includes("a")) {
1760
+ const ampm = this.getDateComponent("Hours") >= 12 ? "pm" : "am";
1761
+ dateFormat = dateFormat.replace(/\ba\b/g, ampm);
1762
+ }
1763
+ } else {
1764
+ dateFormat = dateFormat.replace(/\s*\bA\b\s*/g, " ");
1765
+ dateFormat = dateFormat.replace(/\s*\ba\b\s*/g, " ");
1766
+ dateFormat = dateFormat.replace(/\s+/g, " ").trim();
1767
+ }
1768
+ dateFormat = dateFormat.replace("mm", padding(this.getDateComponent("Minutes")));
1769
+ dateFormat = dateFormat.replace("ss", padding(this.getDateComponent("Seconds")));
1770
+ return dateFormat;
1771
+ }
1772
+ }
1773
+ class HandlerTimezone extends Handler {
1774
+ process(dateFormat) {
1775
+ if (dateFormat.includes("Z")) {
1776
+ if (this.isUTC) {
1777
+ dateFormat = dateFormat.replace("Z", "+0000");
1778
+ } else {
1779
+ const offsetMinutes = this.date.getTimezoneOffset();
1780
+ const sign = offsetMinutes > 0 ? "-" : "+";
1781
+ const absOffset = Math.abs(offsetMinutes);
1782
+ const hours = Math.floor(absOffset / 60);
1783
+ const minutes = absOffset % 60;
1784
+ const offsetString = `${sign}${hours.toString().padStart(2, "0")}${minutes.toString().padStart(2, "0")}`;
1785
+ dateFormat = dateFormat.replace("Z", offsetString);
1786
+ }
1787
+ }
1788
+ if (dateFormat.includes("ddd")) {
1789
+ const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
1790
+ const dayIndex = this.getDateComponent("Day");
1791
+ dateFormat = dateFormat.replace("ddd", days[dayIndex]);
1792
+ }
1793
+ if (dateFormat.includes("dd")) {
1794
+ const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1795
+ const dayIndex = this.getDateComponent("Day");
1796
+ dateFormat = dateFormat.replace("dd", days[dayIndex]);
1797
+ }
1798
+ return dateFormat;
1799
+ }
1800
+ }
1801
+ function handle({ date, format, isUTC, is24Hour, timezoneOffset = 0 }) {
1802
+ return [
1803
+ HandlerTimezone,
1804
+ HandlerDate,
1805
+ HandlerMonth,
1806
+ HandlerYear,
1807
+ HandlerTime
1808
+ ].reduce((acc, Handler2) => {
1809
+ const handler = new Handler2({ date, isUTC, is24Hour, timezoneOffset });
1810
+ return handler.process(acc);
1811
+ }, format);
1812
+ }
1813
+ function convertTimestampToString(timestamp, dateFormat) {
1814
+ const format = dateFormat || "YYYY/MM/DD hh:mm";
1815
+ const is24Hour = format.includes("HH");
1816
+ let timezoneOffset = null;
1817
+ if (format.includes("Z")) {
1818
+ timezoneOffset = 0;
1819
+ } else if (format.includes("+")) {
1820
+ const offsetMatch = format.match(/[+-]\d{2}:?\d{2}/);
1821
+ if (offsetMatch) {
1822
+ const offsetStr = offsetMatch[0];
1823
+ const sign = offsetStr[0] === "+" ? 1 : -1;
1824
+ const hours = parseInt(offsetStr.slice(1, 3), 10);
1825
+ const minutes = offsetStr.includes(":") ? parseInt(offsetStr.slice(4, 6), 10) : parseInt(offsetStr.slice(3, 5), 10);
1826
+ timezoneOffset = sign * (hours * 60 + minutes);
1827
+ }
1828
+ }
1829
+ const date = create(timestamp, timezoneOffset === null ? 0 : timezoneOffset);
1830
+ return handle({ date, format, isUTC: timezoneOffset !== null, is24Hour, timezoneOffset: timezoneOffset === null ? 0 : timezoneOffset });
1831
+ }
1832
+ function detectControlCharacters(input, options = {}) {
1833
+ const {
1834
+ preserveBasicWhitespace = true,
1835
+ removeNewlines = false
1836
+ } = options;
1837
+ if (typeof input !== "string") {
1838
+ return {
1839
+ hasControlChars: false,
1840
+ matches: [],
1841
+ inputType: typeof input,
1842
+ message: "Input is not a string"
1843
+ };
1844
+ }
1845
+ const matches = [];
1846
+ let regex;
1847
+ if (preserveBasicWhitespace && !removeNewlines) {
1848
+ regex = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g;
1849
+ } else {
1850
+ regex = /[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g;
1851
+ }
1852
+ input.replace(regex, (match, offset) => {
1853
+ matches.push({
1854
+ character: match,
1855
+ code: match.charCodeAt(0),
1856
+ hex: "0x" + match.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0"),
1857
+ position: offset,
1858
+ context: getContext(input, offset, 10)
1859
+ // Show surrounding text
1860
+ });
1861
+ return "";
1862
+ });
1863
+ return {
1864
+ hasControlChars: matches.length > 0,
1865
+ matches,
1866
+ totalFound: matches.length,
1867
+ inputPreview: input.length > 50 ? input.substring(0, 50) + "..." : input,
1868
+ inputLength: input.length,
1869
+ optionsUsed: { preserveBasicWhitespace },
1870
+ regexPattern: regex.toString()
1871
+ };
1872
+ }
1873
+ function getContext(str, position, contextLength = 10) {
1874
+ const start = Math.max(0, position - contextLength);
1875
+ const end = Math.min(str.length, position + contextLength + 1);
1876
+ let context = str.substring(start, end);
1877
+ context = context.replace(/[\x00-\x1F\x7F-\x9F]/g, (match) => {
1878
+ return "\\u" + match.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0");
1879
+ });
1880
+ return context;
1881
+ }
1882
+ function printControlCharReport(report) {
1883
+ console.log("=== Control Character Detection Report ===");
1884
+ console.log(`Input: "${report.inputPreview}" (${report.inputLength} chars)`);
1885
+ console.log(`Options: preserveBasicWhitespace = ${report.optionsUsed.preserveBasicWhitespace}`);
1886
+ console.log(`Regex pattern: ${report.regexPattern}`);
1887
+ console.log(`Control characters found: ${report.totalFound}`);
1888
+ if (report.hasControlChars) {
1889
+ console.log("\n📋 Matches found:");
1890
+ report.matches.forEach((match, index2) => {
1891
+ console.log(`
1892
+ ${index2 + 1}. Character: ${JSON.stringify(match.character)}`);
1893
+ console.log(` Code: ${match.code} (${match.hex})`);
1894
+ console.log(` Position: ${match.position}`);
1895
+ console.log(` Context: "...${match.context}..."`);
1896
+ });
1897
+ } else {
1898
+ console.log("✅ No control characters detected in Phase 1 range");
1899
+ }
1900
+ console.log("=== End Report ===");
1901
+ }
1902
+ function displayName(user, options) {
1903
+ user = user || {};
1904
+ options = options || {};
1905
+ const { firstName, middleName, noFirstName, prefix, title, upperCaseLastName = true } = options;
1906
+ options.hasAsianCharacters = false;
1907
+ let parts = [];
1908
+ if ((prefix || title) && user.prefix) {
1909
+ const _prefixHandler = _makeHandler(options);
1910
+ parts = _prefixHandler(parts, user.prefix);
1911
+ parts = _prefixHandler(parts, user.title);
1912
+ }
1913
+ if (firstName !== false && !noFirstName) {
1914
+ const _firstNameHandler = _makeHandler(options);
1915
+ parts = _firstNameHandler(parts, user.firstName);
1916
+ parts = _firstNameHandler(parts, user.givenName);
1917
+ }
1918
+ if (middleName === true && user.middleName) {
1919
+ options.hasAsianCharacters = options.hasAsianCharacters || _test(user.middleName.toString());
1920
+ parts.push(user.middleName.toString());
1921
+ }
1922
+ const _lastNameHandler = _makeHandler(options, upperCaseLastName);
1923
+ parts = _lastNameHandler(parts, user.lastName);
1924
+ parts = _lastNameHandler(parts, user.familyName);
1925
+ parts = _lastNameHandler(parts, user.surname);
1926
+ if (options.hasAsianCharacters) {
1927
+ return parts.reverse().join("");
1928
+ }
1929
+ return parts.join(" ");
1930
+ }
1931
+ function _makeHandler(options = {}, upperCaseLastName = false) {
1932
+ let match = false;
1933
+ return (parts, field) => {
1934
+ if (!match && field) {
1935
+ match = true;
1936
+ options.hasAsianCharacters = options.hasAsianCharacters || _test(field.toString());
1937
+ const _field = upperCaseLastName ? field.toString().toUpperCase() : field.toString();
1938
+ parts.push(_field);
1939
+ }
1940
+ return parts;
1941
+ };
1942
+ }
1943
+ function _test(str) {
1944
+ return /[\u3400-\u9FBF]/.test(str);
1945
+ }
1946
+ function downloadFileByUrl({ dataUrl = "", filename = "" } = {}) {
1947
+ const link = document.createElement("a");
1948
+ link.download = filename;
1949
+ link.href = dataUrl;
1950
+ document.body.appendChild(link);
1951
+ link.click();
1952
+ document.body.removeChild(link);
1953
+ }
1954
+ function escapeRegex(string) {
1955
+ return String(string).replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
1956
+ }
1957
+ class CheckResult {
1958
+ constructor(opts) {
1959
+ this.dataSets = [];
1960
+ this.dataSets = (opts == null ? void 0 : opts.dataSets) || [];
1961
+ }
1962
+ addDataSet(dataSet) {
1963
+ this.dataSets.push(dataSet);
1964
+ }
1965
+ getDataSetByName(name) {
1966
+ return this.dataSets.find((dataSet) => dataSet.name === name);
1967
+ }
1968
+ getSummary() {
1969
+ return this.dataSets.map((dataSet) => ({
1970
+ name: dataSet.name,
1971
+ hidden: dataSet.checkResultConfig.hidden,
1972
+ summary: {
1973
+ total: dataSet.data.length,
1974
+ valid: dataSet.data.filter((row) => row.errorLogs.length === 0 && !row.ignoreLog).length,
1975
+ ignored: dataSet.data.filter((row) => row.ignoreLog).length,
1976
+ invalid: dataSet.data.filter((row) => row.errorLogs.length > 0 && !row.errorLogs.some((detail) => detail.type === "DUPLICATED")).length,
1977
+ duplicated: dataSet.data.filter((row) => row.errorLogs.some((detail) => detail.type === "DUPLICATED")).length
1978
+ }
1979
+ }));
1980
+ }
1981
+ getDuplicatedDetails() {
1982
+ return this.dataSets.map((dataSet) => ({
1983
+ name: dataSet.name,
1984
+ hidden: dataSet.checkResultConfig.hidden,
1985
+ logs: dataSet.data.filter((row) => row.errorLogs.some((detail) => detail.type === "DUPLICATED")).reduce((acc, row) => {
1986
+ return [...acc, ...row.errorLogs];
1987
+ }, [])
1988
+ }));
1989
+ }
1990
+ getIgnoredDetails() {
1991
+ return this.dataSets.map((dataSet) => ({
1992
+ name: dataSet.name,
1993
+ hidden: dataSet.checkResultConfig.hidden,
1994
+ logs: dataSet.data.filter((row) => row.ignoreLog).reduce((acc, row) => {
1995
+ return [...acc, row.ignoreLog];
1996
+ }, [])
1997
+ }));
1998
+ }
1999
+ getInvalidDetails() {
2000
+ return this.dataSets.map((dataSet) => ({
2001
+ name: dataSet.name,
2002
+ hidden: dataSet.checkResultConfig.hidden,
2003
+ logs: dataSet.data.filter((row) => row.errorLogs.length > 0 && !row.errorLogs.some((detail) => detail.type === "DUPLICATED")).reduce((acc, row) => {
2004
+ return [...acc, ...row.errorLogs];
2005
+ }, [])
2006
+ }));
2007
+ }
2008
+ getValidDetails() {
2009
+ return this.dataSets.reduce((acc, dataSet) => {
2010
+ acc[dataSet.name] = dataSet.data.filter((row) => row.errorLogs.length === 0).reduce((acc2, row) => {
2011
+ return [...acc2, row];
2012
+ }, []);
2013
+ return acc;
2014
+ }, {});
2015
+ }
2016
+ hasInvalidData() {
2017
+ return this.dataSets.some((dataSet) => dataSet.data.some((row) => row.errorLogs.length > 0 && !row.errorLogs.some((detail) => detail.type === "DUPLICATED")));
2018
+ }
2019
+ }
2020
+ class SaveResult {
2021
+ constructor(opt) {
2022
+ this.dataSets = [];
2023
+ opt = opt || {};
2024
+ this.dataSets = opt.dataSets || [];
2025
+ }
2026
+ addDataSet(dataSet) {
2027
+ this.dataSets.push(dataSet);
2028
+ return this;
2029
+ }
2030
+ getSaveDetails() {
2031
+ return this.dataSets.map((dataSet) => {
2032
+ var _a;
2033
+ const returnDetail = (_a = dataSet.saveResultConfig) == null ? void 0 : _a.returnDetail;
2034
+ return {
2035
+ name: dataSet.name,
2036
+ hidden: dataSet.saveResultConfig.hidden,
2037
+ details: {
2038
+ failed: (returnDetail == null ? void 0 : returnDetail.failed) ? dataSet.data.filter((row) => row.status.failed) : null,
2039
+ inserted: (returnDetail == null ? void 0 : returnDetail.inserted) ? dataSet.data.filter((row) => row.status.inserted) : null,
2040
+ skipped: (returnDetail == null ? void 0 : returnDetail.skipped) ? dataSet.data.filter((row) => row.status.skipped) : null,
2041
+ updated: (returnDetail == null ? void 0 : returnDetail.updated) ? dataSet.data.filter((row) => row.status.updated) : null
2042
+ }
2043
+ };
2044
+ });
2045
+ }
2046
+ getSaveSummary() {
2047
+ return this.dataSets.map((dataSet) => ({
2048
+ name: dataSet.name,
2049
+ hidden: dataSet.saveResultConfig.hidden,
2050
+ summary: {
2051
+ total: dataSet.data.length,
2052
+ failed: dataSet.data.filter((row) => row.status.failed).length,
2053
+ inserted: dataSet.data.filter((row) => row.status.inserted).length,
2054
+ skipped: dataSet.data.filter((row) => row.status.skipped).length,
2055
+ updated: dataSet.data.filter((row) => row.status.updated).length
2056
+ }
2057
+ }));
2058
+ }
2059
+ }
2060
+ class DataSet {
2061
+ constructor(opts) {
2062
+ opts = opts || {};
2063
+ this.name = opts.name || "";
2064
+ this.data = opts.data || [];
2065
+ this.checkResultConfig = opts.checkResultConfig ? { ...opts.checkResultConfig } : {};
2066
+ this.checkResultConfig.hidden = this.checkResultConfig.hidden ?? false;
2067
+ this.saveResultConfig = opts.saveResultConfig ? { ...opts.saveResultConfig } : {};
2068
+ this.saveResultConfig.hidden = this.saveResultConfig.hidden ?? false;
2069
+ }
2070
+ add(data) {
2071
+ this.data.push(data);
2072
+ return this;
2073
+ }
2074
+ getExistedData() {
2075
+ return this.data.filter((item) => {
2076
+ var _a;
2077
+ return item.isValid() && ((_a = item.status) == null ? void 0 : _a.existed);
2078
+ });
2079
+ }
2080
+ getInvalidData() {
2081
+ return this.data.filter((item) => !item.isValid());
2082
+ }
2083
+ getNotExistedData() {
2084
+ return this.data.filter((item) => {
2085
+ var _a;
2086
+ return item.isValid() && !((_a = item.status) == null ? void 0 : _a.existed);
2087
+ });
2088
+ }
2089
+ }
2090
+ const DATAWRAPPER_STATUS = {
2091
+ EXISTED: "existed",
2092
+ FAILED: "failed",
2093
+ INSERTED: "inserted",
2094
+ SKIPPED: "skipped",
2095
+ UPDATED: "updated"
2096
+ };
2097
+ class DataWrapper {
2098
+ constructor(opts) {
2099
+ this.data = opts.data || {};
2100
+ this.errorLogs = opts.errorLogs || [];
2101
+ this.ignoreLog = opts.ignoreLog;
2102
+ this.rawData = opts.rawData || {};
2103
+ this.rowIndex = opts.rowIndex || 0;
2104
+ this.status = opts.status || {
2105
+ existed: null,
2106
+ failed: null,
2107
+ inserted: null,
2108
+ updated: null
2109
+ };
2110
+ this.transformedData = opts.transformedData || {};
2111
+ }
2112
+ addError(detail) {
2113
+ this.errorLogs.push(detail);
2114
+ return this;
2115
+ }
2116
+ addInsertError(msg) {
2117
+ this.addError({
2118
+ rowIndex: this.rowIndex,
2119
+ column: "",
2120
+ message: msg,
2121
+ type: "INSERT_ERROR"
2122
+ });
2123
+ return this;
2124
+ }
2125
+ addUpdateError(msg) {
2126
+ this.addError({
2127
+ rowIndex: this.rowIndex,
2128
+ column: "",
2129
+ message: msg,
2130
+ type: "UPDATE_ERROR"
2131
+ });
2132
+ return this;
2133
+ }
2134
+ isValid() {
2135
+ return this.errorLogs.length === 0 && !this.ignoreLog;
2136
+ }
2137
+ setIgnoreLog(detail) {
2138
+ this.ignoreLog = detail;
2139
+ return this;
2140
+ }
2141
+ setData(data) {
2142
+ this.data = data;
2143
+ return this;
2144
+ }
2145
+ setExisted() {
2146
+ this.setStatus("EXISTED");
2147
+ return this;
2148
+ }
2149
+ setFailed() {
2150
+ this.setStatus("FAILED");
2151
+ return this;
2152
+ }
2153
+ setInserted() {
2154
+ this.setStatus("INSERTED");
2155
+ return this;
2156
+ }
2157
+ setRawData(rawData) {
2158
+ this.rawData = rawData;
2159
+ return this;
2160
+ }
2161
+ setSkipped() {
2162
+ this.setStatus("SKIPPED");
2163
+ return this;
2164
+ }
2165
+ setStatus(status) {
2166
+ this.status[DATAWRAPPER_STATUS[status]] = Date.now();
2167
+ return this;
2168
+ }
2169
+ setTransformedData(transformedData) {
2170
+ this.transformedData = transformedData;
2171
+ return this;
2172
+ }
2173
+ setUpdated() {
2174
+ this.setStatus("UPDATED");
2175
+ return this;
2176
+ }
2177
+ }
2178
+ class ExcelImportHelper {
2179
+ static async check(params) {
2180
+ const result = new CheckResult();
2181
+ const { config, excelData, context: userContext } = params;
2182
+ const context = userContext || {};
2183
+ if (typeof config.beforeCheck === "function") {
2184
+ await config.beforeCheck({ context, excelData, result });
2185
+ }
2186
+ for (const excelDataByWorksheet of excelData) {
2187
+ const { headers, worksheetName, data: worksheetData } = excelDataByWorksheet;
2188
+ if (!worksheetData) continue;
2189
+ const worksheet = config.worksheets.find((item) => item.name === worksheetName);
2190
+ const dataSources = (worksheet == null ? void 0 : worksheet.dataSources) || [];
2191
+ const { headerRow = 1, dataStartRow = 2 } = worksheet || {};
2192
+ for (const dataSource of dataSources) {
2193
+ if (!dataSource.headerConfigs || !dataSource.name) continue;
2194
+ const seenPrimaryKeys = /* @__PURE__ */ new Map();
2195
+ const dataSet = new DataSet({
2196
+ name: dataSource.name,
2197
+ data: [],
2198
+ checkResultConfig: dataSource.checkResultConfig,
2199
+ saveResultConfig: dataSource.saveResultConfig
2200
+ });
2201
+ for (let rowIndex = 0; rowIndex < worksheetData.length; rowIndex++) {
2202
+ const row = worksheetData[rowIndex];
2203
+ const rawData = this.getRawDataFromHeaders(row, dataSource.headerConfigs);
2204
+ let excelRow = this.createExcelRow(rawData, rowIndex + dataStartRow);
2205
+ const ctx = Object.assign({ dataSets: result.dataSets }, context);
2206
+ const handlers = [
2207
+ (row2) => this.checkDuplicated(row2, dataSource, seenPrimaryKeys),
2208
+ (row2) => this.isIgnore(row2, ctx, dataSource.isIgnore),
2209
+ (row2) => this.transform(row2, dataSource.headerConfigs, headers),
2210
+ (row2) => this.convert(row2, ctx, dataSource.converter)
2211
+ ];
2212
+ for (const handler of handlers) {
2213
+ excelRow = handler(excelRow);
2214
+ if (excelRow.errorLogs.length > 0 || excelRow.ignoreLog) {
2215
+ break;
2216
+ }
2217
+ }
2218
+ const dataWrapper = new DataWrapper(excelRow);
2219
+ dataSet.add(dataWrapper);
2220
+ }
2221
+ result.addDataSet(dataSet);
2222
+ }
2223
+ }
2224
+ return result;
2225
+ }
2226
+ static createExcelRow(row, rowIndex) {
2227
+ return new DataWrapper({
2228
+ // data: { ...row },
2229
+ rawData: row,
2230
+ rowIndex,
2231
+ errorLogs: []
2232
+ });
2233
+ }
2234
+ static getRawDataFromHeaders(excelRow, headerConfigs = []) {
2235
+ const rawData = {};
2236
+ for (const config of headerConfigs) {
2237
+ rawData[config.name] = excelRow[config.name];
2238
+ }
2239
+ return rawData;
2240
+ }
2241
+ static isIgnore(row, ctx, isIgnore) {
2242
+ if (!isIgnore) {
2243
+ return row;
2244
+ }
2245
+ const { ignore, reason } = isIgnore({ rawData: row.rawData, rowIndex: row.rowIndex, ctx });
2246
+ if (ignore) {
2247
+ row.setIgnoreLog({
2248
+ rowIndex: row.rowIndex,
2249
+ column: "",
2250
+ message: reason || "",
2251
+ type: "IGNORE"
2252
+ });
2253
+ }
2254
+ return row;
2255
+ }
2256
+ static checkDuplicated(row, dataSource, seenPrimaryKeys) {
2257
+ const primaryKey = dataSource.primaryKeys.map((key) => row.rawData[key]).join("-");
2258
+ if (seenPrimaryKeys.has(primaryKey)) {
2259
+ row.addError({
2260
+ rowIndex: row.rowIndex,
2261
+ // column: getPrimaryKeyColumn(dataSource.primaryKeys, headers),
2262
+ column: "",
2263
+ message: `Duplicated with row ${seenPrimaryKeys.get(primaryKey) || 0}`,
2264
+ type: "DUPLICATED"
2265
+ });
2266
+ } else {
2267
+ seenPrimaryKeys.set(primaryKey, row.rowIndex);
2268
+ }
2269
+ return row;
2270
+ }
2271
+ static transform(row, headerConfigs = [], headers = []) {
2272
+ const rawData = { ...row.rawData };
2273
+ const transformedData = {};
2274
+ for (const config of headerConfigs) {
2275
+ const value = rawData[config.name];
2276
+ let hasRequiredError = false;
2277
+ if (config.required && (value === null || value === void 0 || value === "")) {
2278
+ row.addError({
2279
+ rowIndex: row.rowIndex,
2280
+ column: getExcelColumnName(headers.indexOf(config.name)),
2281
+ message: `${config.name} is required`,
2282
+ type: "REQUIRED"
2283
+ });
2284
+ hasRequiredError = true;
2285
+ }
2286
+ if (hasRequiredError) continue;
2287
+ try {
2288
+ transformedData[config.name] = typeof config.transform === "function" ? config.transform(rawData[config.name]) : rawData[config.name];
2289
+ } catch (error) {
2290
+ row.addError({
2291
+ rowIndex: row.rowIndex,
2292
+ column: getExcelColumnName(headers.indexOf(config.name)),
2293
+ message: `transform ${config.name} failed`,
2294
+ type: "TRANSFORM"
2295
+ });
2296
+ }
2297
+ }
2298
+ return row.setTransformedData(transformedData);
2299
+ }
2300
+ static convert(row, ctx, converter) {
2301
+ if (row.errorLogs.length > 0) {
2302
+ return row;
2303
+ }
2304
+ if (!converter) {
2305
+ return row.setData(row.transformedData);
2306
+ }
2307
+ try {
2308
+ const result = converter({ transformedData: row.transformedData, rowIndex: row.rowIndex, ctx });
2309
+ return row.setData(result);
2310
+ } catch (error) {
2311
+ row.addError({
2312
+ rowIndex: row.rowIndex,
2313
+ column: "",
2314
+ message: `convert failed`,
2315
+ type: "CONVERT"
2316
+ });
2317
+ }
2318
+ return row;
2319
+ }
2320
+ static async save(params) {
2321
+ const saveResult = new SaveResult();
2322
+ const { result, config, context: userContext } = params;
2323
+ if (!result || !config) {
2324
+ return saveResult;
2325
+ }
2326
+ const context = userContext || {};
2327
+ if (typeof config.beforeSave === "function") {
2328
+ await config.beforeSave({ context, checkResult: result, result: saveResult });
2329
+ }
2330
+ for (const worksheet of config.worksheets) {
2331
+ for (const dataSource of worksheet.dataSources) {
2332
+ const { checkExisted, handleData } = dataSource;
2333
+ let updatedDataSet = result.getDataSetByName(dataSource.name || "");
2334
+ if (!updatedDataSet) {
2335
+ continue;
2336
+ }
2337
+ const ctx = Object.assign({ dataSets: result.dataSets }, context);
2338
+ if (checkExisted && typeof checkExisted === "function") {
2339
+ updatedDataSet = await checkExisted({ dataSet: updatedDataSet, ctx });
2340
+ }
2341
+ if (handleData && typeof handleData === "function") {
2342
+ updatedDataSet = await handleData({ dataSet: updatedDataSet, dataSource, ctx });
2343
+ } else {
2344
+ updatedDataSet.data.forEach((row) => {
2345
+ row.setStatus("FAILED");
2346
+ });
2347
+ }
2348
+ saveResult.addDataSet(updatedDataSet);
2349
+ }
2350
+ }
2351
+ return saveResult;
2352
+ }
2353
+ }
2354
+ function getExcelColumnName(columnIndex) {
2355
+ let result = "";
2356
+ let index2 = columnIndex;
2357
+ while (index2 >= 0) {
2358
+ result = String.fromCharCode(65 + index2 % 26) + result;
2359
+ index2 = Math.floor(index2 / 26) - 1;
2360
+ }
2361
+ return result;
2362
+ }
2363
+ function customHandler({ responseHelper, handler, ignoreError = false }) {
2364
+ return async (reqOrCtx, resOrNext, nextInExpress) => {
2365
+ const isKoa = typeof resOrNext === "function" && !nextInExpress;
2366
+ const ctx = isKoa ? reqOrCtx : null;
2367
+ const req = isKoa ? reqOrCtx.request : reqOrCtx;
2368
+ const res = isKoa ? reqOrCtx.response : resOrNext;
2369
+ const next = isKoa ? resOrNext : nextInExpress;
2370
+ try {
2371
+ await handler({ req, res });
2372
+ if (isKoa) {
2373
+ return await next();
2374
+ } else {
2375
+ return next();
2376
+ }
2377
+ } catch (err) {
2378
+ if (ignoreError) {
2379
+ return isKoa ? await next() : next();
2380
+ }
2381
+ if (!responseHelper) {
2382
+ if (isKoa) {
2383
+ throw err;
2384
+ }
2385
+ return next(err);
2386
+ }
2387
+ const status = err.status || 400;
2388
+ const message = err.message || "An error occurred";
2389
+ const formattedResponse = responseHelper.standardizeResponse({ err, message });
2390
+ if (isKoa) {
2391
+ ctx.status = status;
2392
+ ctx.body = formattedResponse;
2393
+ } else {
2394
+ res.status(status).json(formattedResponse);
2395
+ }
2396
+ }
2397
+ };
2398
+ }
2399
+ function findAllResult({ responseHelper, service }) {
2400
+ return async (req, res, next) => {
2401
+ try {
2402
+ const { query } = req;
2403
+ const result = await service.findAll({ query });
2404
+ res.locals.findAllResult = result;
2405
+ await next();
2406
+ } catch (err) {
2407
+ res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }));
2408
+ }
2409
+ };
2410
+ }
2411
+ function findOneResult({ responseHelper, service }) {
2412
+ return async (req, res, next) => {
2413
+ try {
2414
+ const { params, query } = req;
2415
+ const { id } = params;
2416
+ const result = await service.findOne({
2417
+ query: {
2418
+ ...query,
2419
+ id
2420
+ }
2421
+ });
2422
+ res.locals.findOneResult = result;
2423
+ await next();
2424
+ } catch (err) {
2425
+ res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }));
2426
+ }
2427
+ };
2428
+ }
2429
+ function hideSensitiveFields(aggregation, { query = {} } = {}) {
2430
+ if (!query.__EXCLUDED_FIELDS || Array.isArray(query.__EXCLUDED_FIELDS) && query.__EXCLUDED_FIELDS.length === 0) {
2431
+ return;
2432
+ }
2433
+ aggregation.push({
2434
+ $set: {
2435
+ __originalEmail: "$_eventRegistration.email",
2436
+ __originalPhone: "$_eventRegistration.phone",
2437
+ // 1. Force __queryArr to be an array even if query.__EXCLUDED_FIELDS is undefined/missing
2438
+ __queryArr: { $ifNull: [query.__EXCLUDED_FIELDS || [], []] },
2439
+ __isMyself: { $eq: ["$_eventRegistration.loginSubjectCode", query.__LOGIN_SUBJECT_CODE] },
2440
+ __isGroupCoordinator: !!query.__ALLOW_COORDINATOR,
2441
+ __hasEventRegistration: { $ne: ["$_eventRegistration", null] }
2442
+ }
2443
+ });
2444
+ aggregation.push({
2445
+ $set: {
2446
+ __shouldShowEmail: {
2447
+ $and: [
2448
+ "$__hasEventRegistration",
2449
+ {
2450
+ $or: [
2451
+ "$__isMyself",
2452
+ "$__isGroupCoordinator",
2453
+ // Only hide if 'email' is explicitly in the exclusion array
2454
+ { $not: { $in: ["email", "$__queryArr"] } }
2455
+ ]
2456
+ }
2457
+ ]
2458
+ },
2459
+ __shouldShowPhone: {
2460
+ $and: [
2461
+ "$__hasEventRegistration",
2462
+ {
2463
+ $or: [
2464
+ "$__isMyself",
2465
+ "$__isGroupCoordinator",
2466
+ { $not: { $in: ["phone", "$__queryArr"] } }
2467
+ ]
2468
+ }
2469
+ ]
2470
+ }
2471
+ }
2472
+ });
2473
+ aggregation.push({
2474
+ $set: {
2475
+ "_eventRegistration.email": {
2476
+ $cond: ["$__shouldShowEmail", "$__originalEmail", "$$REMOVE"]
2477
+ },
2478
+ "_eventRegistration.phone": {
2479
+ $cond: ["$__shouldShowPhone", "$__originalPhone", "$$REMOVE"]
2480
+ }
2481
+ }
2482
+ });
2483
+ aggregation.push({
2484
+ $unset: [
2485
+ "__originalEmail",
2486
+ "__originalPhone",
2487
+ "__isMyself",
2488
+ "__isGroupCoordinator",
2489
+ "__queryArr",
2490
+ "__hasEventRegistration",
2491
+ "__shouldShowEmail",
2492
+ "__shouldShowPhone"
2493
+ ]
2494
+ });
2495
+ }
2496
+ function postResult({ responseHelper, service }) {
2497
+ return async (req, res, next) => {
2498
+ try {
2499
+ const { body } = req;
2500
+ let result;
2501
+ if (Array.isArray(body)) {
2502
+ result = await service.saveAll({ docs: body });
2503
+ } else {
2504
+ result = await service.saveOne({ doc: body });
2505
+ }
2506
+ res.locals.postResult = result;
2507
+ await next();
2508
+ } catch (err) {
2509
+ res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }));
2510
+ }
2511
+ };
2512
+ }
2513
+ function updateOneResult({ responseHelper, service }) {
2514
+ return async (req, res, next) => {
2515
+ try {
2516
+ const { body, params } = req;
2517
+ const { id } = params;
2518
+ if (id !== body.id) {
2519
+ throw new Error("id in params and body must be same");
2520
+ }
2521
+ const { data } = await service.findOne({ query: { id } });
2522
+ const doc = data[0];
2523
+ doc.update(body);
2524
+ const result = await service.saveOne({ doc });
2525
+ res.locals.updateOneResult = result;
2526
+ await next();
2527
+ } catch (err) {
2528
+ res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }));
2529
+ }
2530
+ };
2531
+ }
2532
+ const expressHelper = {
2533
+ customHandler,
2534
+ findAllResult,
2535
+ findOneResult,
2536
+ hideSensitiveFields,
2537
+ postResult,
2538
+ updateOneResult
2539
+ };
2540
+ function extractEmails(dirtyArray) {
2541
+ const emailRegex = /[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi;
2542
+ const emails = /* @__PURE__ */ new Set();
2543
+ if (!dirtyArray)
2544
+ return [];
2545
+ dirtyArray.forEach((entry) => {
2546
+ if (!entry || typeof entry !== "string" || !entry.trim())
2547
+ return;
2548
+ try {
2549
+ const cleanEntry = entry.replace(/[\u200B-\u200D\uFEFF\u202A-\u202E]/g, "").replace(/[<>]/g, " ").replace(/\s+/g, " ").trim();
2550
+ const matches = cleanEntry.match(emailRegex);
2551
+ if (matches) {
2552
+ matches.forEach((email) => emails.add(email.toLowerCase()));
2553
+ }
2554
+ } catch (e) {
2555
+ console.warn("Failed to process entry:", entry, e);
2556
+ }
2557
+ });
2558
+ return Array.from(emails).sort((a, b) => a.localeCompare(b));
2559
+ }
2560
+ async function pReduce(iterable, reducer, initialValue) {
2561
+ return new Promise((resolve, reject) => {
2562
+ const iterator = iterable[Symbol.iterator]();
2563
+ let index2 = 0;
2564
+ const next = async (total) => {
2565
+ const element = iterator.next();
2566
+ if (element.done) {
2567
+ resolve(total);
2568
+ return;
2569
+ }
2570
+ try {
2571
+ const [resolvedTotal, resolvedValue] = await Promise.all([total, element.value]);
2572
+ next(reducer(resolvedTotal, resolvedValue, index2++));
2573
+ } catch (error) {
2574
+ reject(error);
2575
+ }
2576
+ };
2577
+ next(initialValue);
2578
+ });
2579
+ }
2580
+ class Repo {
2581
+ constructor(options) {
2582
+ options = options || {};
2583
+ this.model = options.model;
2584
+ this._sharedOptions = options._sharedOptions;
2585
+ this._queryOptions = options._queryOptions;
2586
+ this._saveOptions = options._saveOptions;
2587
+ this._Class = options._constructor && options._constructor._Class ? options._constructor._Class : null;
2588
+ }
2589
+ static init(options = {}) {
2590
+ return init(this, options);
2591
+ }
2592
+ static get _classname() {
2593
+ return "Repo";
2594
+ }
2595
+ static get _superclass() {
2596
+ return "Repo";
2597
+ }
2598
+ get _classname() {
2599
+ return "Repo";
2600
+ }
2601
+ get _superclass() {
2602
+ return "Repo";
2603
+ }
2604
+ get isValid() {
2605
+ return this.model && typeof this.model.deleteOne === "function" && typeof this.model.findAll === "function" && typeof this.model.saveOne === "function";
2606
+ }
2607
+ get queryOptions() {
2608
+ return {
2609
+ ...this._sharedOptions,
2610
+ ...this._queryOptions
2611
+ };
2612
+ }
2613
+ get saveOptions() {
2614
+ return {
2615
+ ...this._sharedOptions,
2616
+ ...this._saveOptions
2617
+ };
2618
+ }
2619
+ init(options) {
2620
+ if (this._Class && typeof this._Class.init === "function") {
2621
+ return this._Class.init(options);
2622
+ }
2623
+ return options;
2624
+ }
2625
+ async deleteOne({ id }) {
2626
+ try {
2627
+ const result = await this.model.deleteOne({ _id: id });
2628
+ return {
2629
+ ...result,
2630
+ // { message: 'ok', total }
2631
+ isNew: false,
2632
+ data: []
2633
+ };
2634
+ } catch (err) {
2635
+ throw err;
2636
+ }
2637
+ }
2638
+ // systemLog is optional
2639
+ findAll({ config = {}, query, systemLog }) {
2640
+ const log = _makeLog({
2641
+ systemLog,
2642
+ label: "REPO_READ",
2643
+ message: `fn ${this._classname}.prototype.findAll`,
2644
+ input: [{ query: { ...query }, systemLog: { ...systemLog } }]
2645
+ });
2646
+ const queryOptions = {
2647
+ ...this.queryOptions,
2648
+ ...config
2649
+ };
2650
+ return new Promise((resolve, reject) => {
2651
+ this.model.findAll(query, queryOptions, (err, data, total) => {
2652
+ if (err) {
2653
+ log({ level: "warn", output: err.toString() });
2654
+ reject(err);
2655
+ } else {
2656
+ const result = {
2657
+ isNew: false,
2658
+ data,
2659
+ total: total || data.length
2660
+ };
2661
+ log({ level: "info", output: { ...result } });
2662
+ resolve(result);
2663
+ }
2664
+ });
2665
+ });
2666
+ }
2667
+ findOne({ config = {}, query, systemLog }) {
2668
+ const log = _makeLog({
2669
+ systemLog,
2670
+ label: "REPO_READ",
2671
+ message: `fn ${this._classname}.prototype.findOne`,
2672
+ input: [{ query: { ...query }, systemLog: { ...systemLog } }]
2673
+ });
2674
+ const queryOptions = {
2675
+ ...this.queryOptions,
2676
+ ...config
2677
+ };
2678
+ return new Promise((resolve, reject) => {
2679
+ this.model.findAll(query, queryOptions, (err, data) => {
2680
+ if (err) {
2681
+ reject(err);
2682
+ } else if (data.length === 1) {
2683
+ const result = {
2684
+ isNew: false,
2685
+ data,
2686
+ total: 1
2687
+ };
2688
+ log({ level: "info", output: { ...result } });
2689
+ resolve(result);
2690
+ } else if (data.length === 0) {
2691
+ reject(new Error("record not found"));
2692
+ } else {
2693
+ reject(new Error("more than one is found"));
2694
+ }
2695
+ });
2696
+ }).catch((err) => {
2697
+ log({ level: "warn", output: err.toString() });
2698
+ throw err;
2699
+ });
2700
+ }
2701
+ saveAll({ config = {}, docs, systemLog }) {
2702
+ let isNew;
2703
+ const log = _makeLog({
2704
+ systemLog,
2705
+ label: "REPO_WRITE",
2706
+ message: `fn ${this._classname}.prototype.saveAll`,
2707
+ input: [{ config, docs: [...docs], systemLog: { ...systemLog } }]
2708
+ });
2709
+ const promise = typeof this.model.saveAll === "function" ? this.model.saveAll({ config, docs }) : _saveAll({ config, docs, service: this });
2710
+ return promise.then((savedData) => {
2711
+ if (savedData.length !== 1)
2712
+ isNew = null;
2713
+ const result = {
2714
+ data: savedData,
2715
+ isNew,
2716
+ total: savedData.length
2717
+ };
2718
+ log({ level: "info", output: { ...result } });
2719
+ return result;
2720
+ }).catch((err) => {
2721
+ log({ level: "warn", output: err.toString() });
2722
+ throw err;
2723
+ });
2724
+ }
2725
+ saveOne({ config = {}, doc, systemLog }) {
2726
+ const log = _makeLog({
2727
+ systemLog,
2728
+ label: "REPO_WRITE",
2729
+ message: `fn ${this._classname}.prototype.saveOne`,
2730
+ input: [{ config, doc: { ...doc }, systemLog: { ...systemLog } }]
2731
+ });
2732
+ const saveOptions = {
2733
+ ...this.saveOptions,
2734
+ ...config
2735
+ };
2736
+ return new Promise((resolve, reject) => {
2737
+ this.model.saveOne(doc, saveOptions, (err, result) => {
2738
+ if (err) {
2739
+ log({ level: "warn", output: err.toString() });
2740
+ reject(err);
2741
+ } else {
2742
+ log({ level: "info", output: { ...result } });
2743
+ resolve(result);
2744
+ }
2745
+ });
2746
+ });
2747
+ }
2748
+ }
2749
+ function _makeLog({ systemLog, label, message: message1, input } = {}) {
2750
+ return ({ level, messgae: massage2, output } = {}) => {
2751
+ if (systemLog && systemLog.systemLogHelper) {
2752
+ systemLog.systemLogHelper.log({
2753
+ batchId: systemLog.batchId,
2754
+ label,
2755
+ level,
2756
+ message: massage2 || message1,
2757
+ data: {
2758
+ payload: {
2759
+ input,
2760
+ output
2761
+ }
2762
+ }
2763
+ });
2764
+ }
2765
+ };
2766
+ }
2767
+ async function _saveAll({ config = {}, docs, service }) {
2768
+ let _result = null;
2769
+ if (config.session || service.saveOptions.session) {
2770
+ _result = await pMap(docs, async (doc) => {
2771
+ if (doc) {
2772
+ const result = await service.saveOne({ config, doc });
2773
+ const _data = result._data || result.data;
2774
+ return _data[0];
2775
+ }
2776
+ return null;
2777
+ }, { concurrency: 1 });
2778
+ } else {
2779
+ _result = await Promise.all(docs.map(async (doc) => {
2780
+ if (doc) {
2781
+ const result = await service.saveOne({ config, doc });
2782
+ const _data = result._data || result.data;
2783
+ return _data[0];
2784
+ }
2785
+ return null;
2786
+ }));
2787
+ }
2788
+ return _result;
2789
+ }
2790
+ class ApiResponse {
2791
+ constructor(options = {}) {
2792
+ options = options || {};
2793
+ this._data = options.data || options._data || [];
2794
+ this.err = options.err;
2795
+ this.isNew = options.isNew || false;
2796
+ this.message = options.message;
2797
+ this.total = options.total || 0;
2798
+ this._instanceBuilder = options._instanceBuilder;
2799
+ }
2800
+ static init(options = {}) {
2801
+ if (options instanceof this) {
2802
+ return options;
2803
+ }
2804
+ const instance2 = new this(options);
2805
+ return instance2;
2806
+ }
2807
+ static get _classname() {
2808
+ return "ApiResponse";
2809
+ }
2810
+ static get _superclass() {
2811
+ return "ApiResponse";
2812
+ }
2813
+ // getters
2814
+ get data() {
2815
+ if (this._instanceBuilder && typeof this._instanceBuilder === "function") {
2816
+ return this._data.map(this._instanceBuilder);
2817
+ }
2818
+ return this._data;
2819
+ }
2820
+ }
2821
+ function makeApiResponse({ repo, result }) {
2822
+ return ApiResponse.init({
2823
+ ...result,
2824
+ _instanceBuilder: (i) => {
2825
+ return repo.init(i);
2826
+ }
2827
+ });
2828
+ }
2829
+ class Service {
2830
+ constructor({ repo }) {
2831
+ this.repo = repo;
2832
+ }
2833
+ static get _classname() {
2834
+ return "Service";
2835
+ }
2836
+ static get _superclass() {
2837
+ return "Service";
2838
+ }
2839
+ async deleteOne({ id }) {
2840
+ const result = await this.repo.deleteOne({ id });
2841
+ return makeApiResponse({
2842
+ repo: this.repo,
2843
+ result
2844
+ });
2845
+ }
2846
+ async findAll({ config = {}, query = {}, systemLog } = {}) {
2847
+ const result = await this.repo.findAll({ config, query, systemLog });
2848
+ return makeApiResponse({
2849
+ repo: this.repo,
2850
+ result
2851
+ });
2852
+ }
2853
+ async findOne({ config = {}, query = {}, systemLog } = {}) {
2854
+ const result = await this.repo.findOne({ config, query, systemLog });
2855
+ return makeApiResponse({
2856
+ repo: this.repo,
2857
+ result
2858
+ });
2859
+ }
2860
+ init(options) {
2861
+ return this.repo.init(options);
2862
+ }
2863
+ initFromArray(arr = []) {
2864
+ if (Array.isArray(arr)) {
2865
+ return arr.map((a) => this.init(a));
2866
+ }
2867
+ return [];
2868
+ }
2869
+ initOnlyValidFromArray(arr = []) {
2870
+ return this.initFromArray(arr).filter((i) => i);
2871
+ }
2872
+ async saveAll({ config = {}, docs = [], systemLog } = {}) {
2873
+ const copies = docs.map((doc) => {
2874
+ return config.skipInit ? doc : this.init(doc);
2875
+ });
2876
+ const result = await this.repo.saveAll({ config, docs: copies, systemLog });
2877
+ return makeApiResponse({
2878
+ repo: this.repo,
2879
+ result
2880
+ });
2881
+ }
2882
+ // set skipInit to true if we want to use POST for query
2883
+ async saveOne({ config = {}, doc = {}, systemLog } = {}) {
2884
+ const copy = config.skipInit ? doc : this.init(doc);
2885
+ if (copy) {
2886
+ const result = await this.repo.saveOne({ config, doc: copy, systemLog });
2887
+ return makeApiResponse({
2888
+ repo: this.repo,
2889
+ result
2890
+ });
2891
+ }
2892
+ return {
2893
+ isNew: null,
2894
+ data: [],
2895
+ err: new Error("doc is not a valid instance")
2896
+ };
2897
+ }
2898
+ }
2899
+ function makeService({ repo }) {
2900
+ if (repo === void 0) {
2901
+ throw new Error("repo is required.");
2902
+ }
2903
+ if (repo._superclass !== Repo._superclass) {
2904
+ throw new Error("repo is not an instance of Repo.");
2905
+ }
2906
+ return new Service({ repo });
2907
+ }
2908
+ async function generalPost({ body = {}, GeneralModel, UniqueKeyGenerator: UniqueKeyGenerator2, resourceInfo }) {
2909
+ const { resources, data, globalShared = {}, shared = {}, relationship = {} } = body;
2910
+ const _resourceInfo = resourceInfo || body.resourceInfo;
2911
+ _attachShared(data, globalShared, shared);
2912
+ const obj = await pReduce(resources, async (acc, resource) => {
2913
+ const service = _makeService(resource, _resourceInfo, UniqueKeyGenerator2, GeneralModel);
2914
+ _createRelationship(data, relationship[resource], acc);
2915
+ const _data = data[resource];
2916
+ const result = await service.saveAll({ docs: [].concat(_data) });
2917
+ acc[resource] = Array.isArray(_data) ? result._data : result._data[0];
2918
+ return acc;
2919
+ }, {});
2920
+ return obj;
2921
+ }
2922
+ function _attachShared(data, globalShared = {}, shared = {}) {
2923
+ Object.keys(shared).forEach((key) => {
2924
+ const _data = data[key];
2925
+ if (Array.isArray(_data)) {
2926
+ data[key] = _data.map((_dataItem) => {
2927
+ return objectHelper.merge({}, _dataItem, globalShared, shared[key] || {});
2928
+ });
2929
+ } else {
2930
+ data[key] = objectHelper.merge({}, _data, globalShared, shared[key] || {});
2931
+ }
2932
+ });
2933
+ }
2934
+ function _createRelationship(data, relationship = {}, object) {
2935
+ Object.keys(relationship).forEach((key) => {
2936
+ const path = relationship[key];
2937
+ const val = objectHelper.get(object, path);
2938
+ objectHelper.set(data, key, val);
2939
+ });
2940
+ }
2941
+ function _makeService(resource, resourceInfo, UniqueKeyGenerator2, GeneralModel) {
2942
+ const { collectionName, fields } = resourceInfo[resource];
2943
+ const uniqueKeyGenerator = UniqueKeyGenerator2.makeGenerator(fields);
2944
+ const model = new GeneralModel({ collectionName, uniqueKeyGenerator });
2945
+ return makeService({
2946
+ repo: new Repo({ model })
2947
+ });
2948
+ }
2949
+ function getObjectByArr(arr, data, getValueByKeys2, getValidation2, KeyValueObject$1) {
2950
+ const _KeyValueObject = KeyValueObject$1 || KeyValueObject;
2951
+ if (!Array.isArray(arr) || arr.length === 0) {
2952
+ return null;
2953
+ }
2954
+ return arr.reduce((acc, e) => {
2955
+ const { key, type, value, restriction } = e;
2956
+ const isValid = getValidation2 && typeof getValidation2 === "function" ? getValidation2({ rule: restriction, data }) : true;
2957
+ if (isValid) {
2958
+ let _value = value;
2959
+ switch (type) {
2960
+ case "array": {
2961
+ _value = value.map((el) => {
2962
+ const result = getValueByKeys2({ keys: el.value.split("."), obj: data });
2963
+ return result;
2964
+ });
2965
+ break;
2966
+ }
2967
+ case "fromKeyValue": {
2968
+ const { dataPath, key: valueKey } = value;
2969
+ const keyValues = getValueByKeys2({ keys: dataPath.split("."), obj: data });
2970
+ _value = _KeyValueObject.getValuesByKey(keyValues, valueKey)[0];
2971
+ break;
2972
+ }
2973
+ case "toKeyValue": {
2974
+ const keyValues = getValueByKeys2({ keys: value.split("."), obj: data });
2975
+ _value = _KeyValueObject.fromObject(keyValues);
2976
+ break;
2977
+ }
2978
+ case "nested": {
2979
+ _value = getObjectByArr(value, data, getValueByKeys2, getValidation2);
2980
+ break;
2981
+ }
2982
+ case "path": {
2983
+ _value = getValueByKeys2({ keys: value.split("."), obj: data });
2984
+ break;
2985
+ }
2986
+ case "orgin": {
2987
+ _value = value;
2988
+ break;
2989
+ }
2990
+ case "origin": {
2991
+ _value = value;
2992
+ break;
2993
+ }
2994
+ default: {
2995
+ _value = value;
2996
+ break;
2997
+ }
2998
+ }
2999
+ if (key) {
3000
+ return {
3001
+ ...acc,
3002
+ [key]: _value
3003
+ };
3004
+ }
3005
+ if (typeof _value === "string") {
3006
+ return _value;
3007
+ }
3008
+ return {
3009
+ ...acc,
3010
+ ..._value
3011
+ };
3012
+ }
3013
+ return acc;
3014
+ }, {});
3015
+ }
3016
+ function groupArrayByKey(arr, key) {
3017
+ if (!key || typeof key !== "string") {
3018
+ return {};
3019
+ }
3020
+ return arr.reduce((acc, curr) => {
3021
+ if (!acc[curr[key]]) {
3022
+ acc[curr[key]] = 0;
3023
+ }
3024
+ acc[curr[key]]++;
3025
+ return acc;
3026
+ }, {});
3027
+ }
3028
+ function init(_class, options) {
3029
+ if (options instanceof _class) {
3030
+ return options;
3031
+ }
3032
+ try {
3033
+ const instance2 = new _class(options);
3034
+ return instance2.isValid !== false ? instance2 : null;
3035
+ } catch (e) {
3036
+ console.log(`init failed for class: ${_class._classname || "no _classname"}`, e);
3037
+ return null;
3038
+ }
3039
+ }
3040
+ function initFromArray(_class, arr) {
3041
+ if (Array.isArray(arr)) {
3042
+ return arr.map((a) => init(_class, a));
3043
+ }
3044
+ return [];
3045
+ }
3046
+ function initOnlyValidFromArray(_class, arr) {
3047
+ return initFromArray(_class, arr).filter((i) => i);
3048
+ }
3049
+ function mergeArraysByKey(arr1, arr2) {
3050
+ const safeArr1 = Array.isArray(arr1) ? arr1 : [];
3051
+ const safeArr2 = Array.isArray(arr2) ? arr2 : [];
3052
+ const mergedMap = /* @__PURE__ */ new Map();
3053
+ const mergeValues = (existingValue, newValue) => {
3054
+ if (existingValue === void 0)
3055
+ return newValue;
3056
+ if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3057
+ return [.../* @__PURE__ */ new Set([...existingValue, ...newValue])];
3058
+ }
3059
+ if (typeof existingValue === "object" && typeof newValue === "object" && !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3060
+ return { ...existingValue, ...newValue };
3061
+ }
3062
+ return newValue;
3063
+ };
3064
+ safeArr1.forEach((item) => {
3065
+ mergedMap.set(item.key, item.value);
3066
+ });
3067
+ safeArr2.forEach((item) => {
3068
+ const existingValue = mergedMap.get(item.key);
3069
+ mergedMap.set(item.key, mergeValues(existingValue, item.value));
3070
+ });
3071
+ return Array.from(mergedMap.entries()).map(([key, value]) => ({
3072
+ key,
3073
+ value
3074
+ }));
3075
+ }
3076
+ function padZeros(num, minLength = 6) {
3077
+ num = num.toString();
3078
+ if (num.length < minLength) {
3079
+ return padZeros(`0${num}`, minLength);
3080
+ }
3081
+ return num;
3082
+ }
3083
+ async function pMap(iterable, mapper, {
3084
+ concurrency = Number.POSITIVE_INFINITY,
3085
+ stopOnError = true,
3086
+ signal
3087
+ } = {}) {
3088
+ return new Promise((resolve_, reject_) => {
3089
+ if (iterable[Symbol.iterator] === void 0 && iterable[Symbol.asyncIterator] === void 0) {
3090
+ throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
3091
+ }
3092
+ if (typeof mapper !== "function") {
3093
+ throw new TypeError("Mapper function is required");
3094
+ }
3095
+ if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === Number.POSITIVE_INFINITY)) {
3096
+ throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
3097
+ }
3098
+ const result = [];
3099
+ const errors = [];
3100
+ const skippedIndexesMap = /* @__PURE__ */ new Map();
3101
+ let isRejected = false;
3102
+ let isResolved = false;
3103
+ let isIterableDone = false;
3104
+ let resolvingCount = 0;
3105
+ let currentIndex = 0;
3106
+ const iterator = iterable[Symbol.iterator] === void 0 ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
3107
+ const signalListener = () => {
3108
+ reject(signal.reason);
3109
+ };
3110
+ const cleanup = () => {
3111
+ signal == null ? void 0 : signal.removeEventListener("abort", signalListener);
3112
+ };
3113
+ const resolve = (value) => {
3114
+ resolve_(value);
3115
+ cleanup();
3116
+ };
3117
+ const reject = (reason) => {
3118
+ isRejected = true;
3119
+ isResolved = true;
3120
+ reject_(reason);
3121
+ cleanup();
3122
+ };
3123
+ if (signal) {
3124
+ if (signal.aborted) {
3125
+ reject(signal.reason);
3126
+ }
3127
+ signal.addEventListener("abort", signalListener, { once: true });
3128
+ }
3129
+ const next = async () => {
3130
+ if (isResolved) {
3131
+ return;
3132
+ }
3133
+ const nextItem = await iterator.next();
3134
+ const index2 = currentIndex;
3135
+ currentIndex++;
3136
+ if (nextItem.done) {
3137
+ isIterableDone = true;
3138
+ if (resolvingCount === 0 && !isResolved) {
3139
+ if (!stopOnError && errors.length > 0) {
3140
+ reject(new AggregateError(errors));
3141
+ return;
3142
+ }
3143
+ isResolved = true;
3144
+ if (skippedIndexesMap.size === 0) {
3145
+ resolve(result);
3146
+ return;
3147
+ }
3148
+ const pureResult = [];
3149
+ for (const [index3, value] of result.entries()) {
3150
+ if (skippedIndexesMap.get(index3) === pMapSkip) {
3151
+ continue;
3152
+ }
3153
+ pureResult.push(value);
3154
+ }
3155
+ resolve(pureResult);
3156
+ }
3157
+ return;
3158
+ }
3159
+ resolvingCount++;
3160
+ (async () => {
3161
+ try {
3162
+ const element = await nextItem.value;
3163
+ if (isResolved) {
3164
+ return;
3165
+ }
3166
+ const value = await mapper(element, index2);
3167
+ if (value === pMapSkip) {
3168
+ skippedIndexesMap.set(index2, value);
3169
+ }
3170
+ result[index2] = value;
3171
+ resolvingCount--;
3172
+ await next();
3173
+ } catch (error) {
3174
+ if (stopOnError) {
3175
+ reject(error);
3176
+ } else {
3177
+ errors.push(error);
3178
+ resolvingCount--;
3179
+ try {
3180
+ await next();
3181
+ } catch (error2) {
3182
+ reject(error2);
3183
+ }
3184
+ }
3185
+ }
3186
+ })();
3187
+ };
3188
+ (async () => {
3189
+ for (let index2 = 0; index2 < concurrency; index2++) {
3190
+ try {
3191
+ await next();
3192
+ } catch (error) {
3193
+ reject(error);
3194
+ break;
3195
+ }
3196
+ if (isIterableDone || isRejected) {
3197
+ break;
3198
+ }
3199
+ }
3200
+ })();
3201
+ });
3202
+ }
3203
+ function pMapIterable(iterable, mapper, {
3204
+ concurrency = Number.POSITIVE_INFINITY,
3205
+ backpressure = concurrency
3206
+ } = {}) {
3207
+ if (iterable[Symbol.iterator] === void 0 && iterable[Symbol.asyncIterator] === void 0) {
3208
+ throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
3209
+ }
3210
+ if (typeof mapper !== "function") {
3211
+ throw new TypeError("Mapper function is required");
3212
+ }
3213
+ if (!(Number.isSafeInteger(concurrency) && concurrency >= 1 || concurrency === Number.POSITIVE_INFINITY)) {
3214
+ throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
3215
+ }
3216
+ if (!(Number.isSafeInteger(backpressure) && backpressure >= concurrency || backpressure === Number.POSITIVE_INFINITY)) {
3217
+ throw new TypeError(`Expected \`backpressure\` to be an integer from \`concurrency\` (${concurrency}) and up or \`Infinity\`, got \`${backpressure}\` (${typeof backpressure})`);
3218
+ }
3219
+ return {
3220
+ async *[Symbol.asyncIterator]() {
3221
+ const iterator = iterable[Symbol.asyncIterator] === void 0 ? iterable[Symbol.iterator]() : iterable[Symbol.asyncIterator]();
3222
+ const promises = [];
3223
+ let pendingPromisesCount = 0;
3224
+ let isDone = false;
3225
+ let index2 = 0;
3226
+ function trySpawn() {
3227
+ if (isDone || !(pendingPromisesCount < concurrency && promises.length < backpressure)) {
3228
+ return;
3229
+ }
3230
+ pendingPromisesCount++;
3231
+ const promise = (async () => {
3232
+ const { done, value } = await iterator.next();
3233
+ if (done) {
3234
+ pendingPromisesCount--;
3235
+ return { done: true };
3236
+ }
3237
+ trySpawn();
3238
+ try {
3239
+ const returnValue = await mapper(await value, index2++);
3240
+ pendingPromisesCount--;
3241
+ if (returnValue === pMapSkip) {
3242
+ const index3 = promises.indexOf(promise);
3243
+ if (index3 > 0) {
3244
+ promises.splice(index3, 1);
3245
+ }
3246
+ }
3247
+ trySpawn();
3248
+ return { done: false, value: returnValue };
3249
+ } catch (error) {
3250
+ pendingPromisesCount--;
3251
+ isDone = true;
3252
+ return { error };
3253
+ }
3254
+ })();
3255
+ promises.push(promise);
3256
+ }
3257
+ trySpawn();
3258
+ while (promises.length > 0) {
3259
+ const { error, done, value } = await promises[0];
3260
+ promises.shift();
3261
+ if (error) {
3262
+ throw error;
3263
+ }
3264
+ if (done) {
3265
+ return;
3266
+ }
3267
+ trySpawn();
3268
+ if (value === pMapSkip) {
3269
+ continue;
3270
+ }
3271
+ yield value;
3272
+ }
3273
+ }
3274
+ };
3275
+ }
3276
+ const pMapSkip = Symbol("skip");
3277
+ function renderByTemplate({ engine, template, value } = {}) {
3278
+ if (!template) {
3279
+ return "";
3280
+ }
3281
+ const _model = engine.init(value);
3282
+ const regex = /\{\{\s(.*?)\s\}\}/g;
3283
+ return template.replace(regex, (match) => {
3284
+ const result = _model.pipe(match);
3285
+ if (result === null || result === void 0) {
3286
+ return "";
3287
+ }
3288
+ return typeof result === "object" ? JSON.stringify(result) : result;
3289
+ });
3290
+ }
3291
+ function replacePlaceholders({ content, mapping }) {
3292
+ let isObjectMode = false;
3293
+ if (typeof content === "object" && content !== null) {
3294
+ content = JSON.stringify(content);
3295
+ isObjectMode = true;
3296
+ }
3297
+ const regex = /\[\[\s*([^[\]]+?)\s*\]\]/g;
3298
+ const result = content.replace(regex, (match, expression) => {
3299
+ const trimmedExpr = expression.trim();
3300
+ if (/^[\w.\-]+$/.test(trimmedExpr)) {
3301
+ const keys = trimmedExpr.split(".");
3302
+ let value = mapping;
3303
+ for (const key of keys) {
3304
+ if (!key) continue;
3305
+ value = value == null ? void 0 : value[key];
3306
+ if (value === void 0) break;
3307
+ }
3308
+ if (value !== void 0) {
3309
+ return value;
3310
+ }
3311
+ }
3312
+ return `<%= ${trimmedExpr} %>`;
3313
+ });
3314
+ if (isObjectMode) {
3315
+ return JSON.parse(result);
3316
+ }
3317
+ return result;
3318
+ }
3319
+ function sanitizeText(input, options = {}) {
3320
+ const {
3321
+ normalizeWhitespace = true,
3322
+ removeNewlines = false,
3323
+ trim = true,
3324
+ preserveBasicWhitespace = true,
3325
+ debug = false
3326
+ // new option for debugging
3327
+ } = options;
3328
+ if (typeof input !== "string") {
3329
+ return input;
3330
+ }
3331
+ let result = input;
3332
+ if (debug) {
3333
+ console.log("Original input:", JSON.stringify(input));
3334
+ console.log("Options:", { normalizeWhitespace, removeNewlines, trim, preserveBasicWhitespace });
3335
+ }
3336
+ if (preserveBasicWhitespace && !removeNewlines) {
3337
+ if (debug) {
3338
+ const matches = [];
3339
+ result = result.replace(/[\x00-\x08\v\f\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, (match) => {
3340
+ matches.push({
3341
+ char: match,
3342
+ code: match.charCodeAt(0),
3343
+ hex: `0x${match.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`
3344
+ });
3345
+ return "";
3346
+ });
3347
+ if (matches.length > 0) {
3348
+ console.log("Phase 1 (preserve mode) - Removed characters:");
3349
+ matches.forEach((m) => {
3350
+ console.log(` - Character: ${JSON.stringify(m.char)}, Code: ${m.code}, Hex: ${m.hex}`);
3351
+ });
3352
+ console.log(`Removed ${matches.length} control character(s)`);
3353
+ } else {
3354
+ console.log("Phase 1 (preserve mode) - No control characters found");
3355
+ }
3356
+ } else {
3357
+ result = result.replace(/[\x00-\x08\v\f\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, "");
3358
+ }
3359
+ } else {
3360
+ if (debug) {
3361
+ const matches = [];
3362
+ result = result.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, (match) => {
3363
+ matches.push({
3364
+ char: match,
3365
+ code: match.charCodeAt(0),
3366
+ hex: `0x${match.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`
3367
+ });
3368
+ return "";
3369
+ });
3370
+ if (matches.length > 0) {
3371
+ console.log("Phase 1 (full removal mode) - Removed characters:");
3372
+ matches.forEach((m) => {
3373
+ console.log(` - Character: ${JSON.stringify(m.char)}, Code: ${m.code}, Hex: ${m.hex}`);
3374
+ });
3375
+ console.log(`Removed ${matches.length} control character(s)`);
3376
+ } else {
3377
+ console.log("Phase 1 (full removal mode) - No control characters found");
3378
+ }
3379
+ } else {
3380
+ result = result.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, "");
3381
+ }
3382
+ }
3383
+ if (debug) {
3384
+ console.log("After Phase 1:", JSON.stringify(result));
3385
+ }
3386
+ if (removeNewlines) {
3387
+ if (debug) {
3388
+ result = result.replace(/[\r\n]+/g, " ");
3389
+ console.log("Phase 2 - Converted newlines to spaces");
3390
+ } else {
3391
+ result = result.replace(/[\r\n]+/g, " ");
3392
+ }
3393
+ }
3394
+ if (normalizeWhitespace) {
3395
+ if (debug) {
3396
+ result = result.replace(/[ \t]+/g, " ");
3397
+ console.log("Phase 2 - Normalized whitespace");
3398
+ } else {
3399
+ result = result.replace(/[ \t]+/g, " ");
3400
+ }
3401
+ }
3402
+ if (debug) {
3403
+ console.log("After Phase 2:", JSON.stringify(result));
3404
+ }
3405
+ if (trim) {
3406
+ if (debug) {
3407
+ result = result.trim();
3408
+ console.log("Phase 3 - Trimmed leading/trailing whitespace");
3409
+ } else {
3410
+ result = result.trim();
3411
+ }
3412
+ }
3413
+ if (debug) {
3414
+ console.log("Final result:", JSON.stringify(result));
3415
+ console.log("--- Sanitization complete ---");
3416
+ }
3417
+ return result;
3418
+ }
3419
+ function setId(id) {
3420
+ if (id && typeof id.toString === "function") {
3421
+ return id.toString();
3422
+ }
3423
+ return id;
3424
+ }
3425
+ function shuffleArray(array) {
3426
+ const arr = [...array];
3427
+ for (let i = arr.length - 1; i >= 0; i--) {
3428
+ const j = Math.floor(Math.random() * (i + 1));
3429
+ [arr[i], arr[j]] = [arr[j], arr[i]];
3430
+ }
3431
+ return arr;
3432
+ }
3433
+ function stringFormatter(str, delimiter = "_") {
3434
+ if (str === null || typeof str === "undefined" || typeof str.toString === "undefined") {
3435
+ return null;
3436
+ }
3437
+ return str.toString().trim().toUpperCase().replace("-", delimiter).replace(" ", delimiter);
3438
+ }
3439
+ function baseXEncode(num, base = 34) {
3440
+ const charset = getBaseCharset(base);
3441
+ return encode(num, charset);
3442
+ }
3443
+ function encode(int, charset) {
3444
+ const { byCode } = charset;
3445
+ if (int === 0) {
3446
+ return byCode[0];
3447
+ }
3448
+ let res = "";
3449
+ const max = charset.length;
3450
+ while (int > 0) {
3451
+ res = byCode[int % max] + res;
3452
+ int = Math.floor(int / max);
3453
+ }
3454
+ return res;
3455
+ }
3456
+ function getBaseCharset(base) {
3457
+ let charset = "9876543210ABCDEFGHJKLMNPQRSTUVWXYZ";
3458
+ if (base === 58) {
3459
+ charset = "9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";
3460
+ }
3461
+ return indexCharset(charset);
3462
+ }
3463
+ function getCssClass(str) {
3464
+ return punctuationless(`${str}`).toLowerCase().split(" ").join("-");
3465
+ }
3466
+ function indexCharset(str) {
3467
+ const byCode = {};
3468
+ const byChar = {};
3469
+ const { length } = str;
3470
+ let char;
3471
+ for (let i = 0; i < length; i++) {
3472
+ char = str[i];
3473
+ byCode[i] = char;
3474
+ byChar[char] = i;
3475
+ }
3476
+ return { byCode, byChar, length };
3477
+ }
3478
+ function isSame(str1, str2) {
3479
+ if (typeof str1 !== "string" || typeof str2 !== "string") {
3480
+ return false;
3481
+ }
3482
+ return str1.trim().toUpperCase() === str2.trim().toUpperCase();
3483
+ }
3484
+ function punctuationless(str) {
3485
+ return str.replace(/\s+/g, "-").replace(/[.,\/#!$%\^&\*;:{}=\_`~()]/g, "");
3486
+ }
3487
+ function randomString({ len = 16, pattern = "a1" } = {}) {
3488
+ const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3489
+ const a = "abcdefghijklmnopqrstuvwxyz";
3490
+ const num = "1234567890";
3491
+ const mark = "~!@#$%^&*_+-=";
3492
+ let str = "";
3493
+ if (pattern.includes("A")) {
3494
+ str += A;
3495
+ }
3496
+ if (pattern.includes("a")) {
3497
+ str += a;
3498
+ }
3499
+ if (pattern.includes("1")) {
3500
+ str += num;
3501
+ }
3502
+ if (pattern.includes("#")) {
3503
+ str += mark;
3504
+ }
3505
+ const chars = [...str];
3506
+ return [...new Array(len)].map((i) => {
3507
+ return chars[Math.random() * chars.length | 0];
3508
+ }).join``;
3509
+ }
3510
+ function reverse(str) {
3511
+ const _str = typeof str !== "string" ? str.toString() : str;
3512
+ const splitString = _str.split("");
3513
+ const reverseArray = splitString.reverse();
3514
+ return reverseArray.join("");
3515
+ }
3516
+ function safeToUpperCase(input) {
3517
+ return typeof (input == null ? void 0 : input.toUpperCase) === "function" ? input.toUpperCase() : "";
3518
+ }
3519
+ function setCode(param) {
3520
+ let base = 34;
3521
+ let len = 8;
3522
+ if (param === void 0) ;
3523
+ else if (typeof param === "number") {
3524
+ base = param;
3525
+ } else if (typeof param === "object" && param !== null) {
3526
+ base = param.base ?? base;
3527
+ len = param.len ?? len;
3528
+ }
3529
+ const now = (/* @__PURE__ */ new Date()).valueOf();
3530
+ const random = randomString({
3531
+ len,
3532
+ pattern: "1"
3533
+ });
3534
+ const str = reverse(`${now}${random}`);
3535
+ return baseXEncode(str, base);
3536
+ }
3537
+ function toCamelCase(str) {
3538
+ if (!str)
3539
+ return "";
3540
+ return str.trim().split(/\s+/).map((word, index2) => {
3541
+ if (!word)
3542
+ return "";
3543
+ if (index2 === 0) {
3544
+ return word.toLowerCase();
3545
+ }
3546
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
3547
+ }).join("");
3548
+ }
3549
+ function toLowerCase(str) {
3550
+ if (!str)
3551
+ return "";
3552
+ return str.trim().toLowerCase();
3553
+ }
3554
+ function toScreamingSnakeCase(str) {
3555
+ if (/[^\w\s]|_/g.test(str.replace(/_/g, ""))) {
3556
+ return null;
3557
+ }
3558
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/[\s\-\.]+/g, "_").toUpperCase().replace(/^_+|_+$/g, "").replace(/_{2,}/g, "_");
3559
+ }
3560
+ const stringHelper = {
3561
+ getCssClass,
3562
+ isSame,
3563
+ punctuationless,
3564
+ safeToUpperCase,
3565
+ setCode,
3566
+ toCamelCase,
3567
+ toLowerCase,
3568
+ toScreamingSnakeCase
3569
+ };
3570
+ function trackingPlugin(schema, options) {
3571
+ schema.add({
3572
+ meta: {
3573
+ active: { type: Boolean, default: true },
3574
+ created: { type: Number },
3575
+ creator: { type: String },
3576
+ deleted: { type: Boolean, default: false },
3577
+ modified: { type: Number },
3578
+ owner: { type: String }
3579
+ }
3580
+ });
3581
+ schema.pre("save", function(next) {
3582
+ this.meta.modified = Date.now();
3583
+ next();
3584
+ });
3585
+ schema.index({
3586
+ "meta.active": 1,
3587
+ "meta.deleted": 1
3588
+ }, {
3589
+ name: "tracking_status_index",
3590
+ background: true,
3591
+ partialFilterExpression: {
3592
+ "meta.active": true,
3593
+ "meta.deleted": false
3594
+ }
3595
+ });
3596
+ }
3597
+ function tenantPlugin(schema, options) {
3598
+ if (!schema.path("meta")) {
3599
+ trackingPlugin(schema);
3600
+ }
3601
+ schema.add({
3602
+ metadata: [{ type: Object }],
3603
+ // Instead of Schema.Types.Mixed
3604
+ remarks: [{ type: Object }],
3605
+ tenantCode: { type: String, required: true }
3606
+ });
3607
+ schema.index({
3608
+ tenantCode: 1
3609
+ }, {
3610
+ name: "tenant_core_index",
3611
+ background: true
3612
+ });
3613
+ const existingIndexes = schema.indexes();
3614
+ const hasTenantStatusIndex = existingIndexes.some(
3615
+ (idx) => idx.name === "tenant_status_index"
3616
+ // Check by name for reliability
3617
+ );
3618
+ if (!hasTenantStatusIndex) {
3619
+ schema.index({
3620
+ tenantCode: 1,
3621
+ // Unique field first
3622
+ _type: 1
3623
+ // Low-cardinality field last
3624
+ }, {
3625
+ name: "tenant_status_index",
3626
+ background: true,
3627
+ partialFilterExpression: {
3628
+ "_type": "Tenant",
3629
+ "meta.active": true,
3630
+ "meta.deleted": false
3631
+ }
3632
+ });
3633
+ }
3634
+ }
3635
+ const helpers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3636
+ __proto__: null,
3637
+ CheckResult,
3638
+ ExcelImportHelper,
3639
+ authorize,
3640
+ calculateAge,
3641
+ changeCreatorOwner,
3642
+ concatStringByArray,
3643
+ convertString,
3644
+ convertTimestampToString,
3645
+ detectControlCharacters,
3646
+ displayName,
3647
+ downloadFileByUrl,
3648
+ escapeRegex,
3649
+ expressHelper,
3650
+ extractEmails,
3651
+ formatDate,
3652
+ generalPost,
3653
+ getObjectByArr,
3654
+ getValidation,
3655
+ getValueByKeys,
3656
+ groupArrayByKey,
3657
+ init,
3658
+ initFromArray,
3659
+ initOnlyValidFromArray,
3660
+ isConvertibleToNumber,
3661
+ mergeArraysByKey,
3662
+ objectHelper,
3663
+ pMap,
3664
+ pMapIterable,
3665
+ pMapSkip,
3666
+ pReduce,
3667
+ padZeros,
3668
+ printControlCharReport,
3669
+ renderByTemplate,
3670
+ replacePlaceholders,
3671
+ sanitizeText,
3672
+ setId,
3673
+ shuffleArray,
3674
+ stringFormatter,
3675
+ stringHelper,
3676
+ tenantPlugin,
3677
+ trackingPlugin
3678
+ }, Symbol.toStringTag, { value: "Module" }));
3679
+ class AwsStsS3Client {
3680
+ constructor(options) {
3681
+ options = options || {};
3682
+ this.expiration = options.expiration || null;
3683
+ this.s3Client = options.s3Client || null;
3684
+ this.getIdToken = options.getIdToken;
3685
+ this.region = options.region || "ap-east-1";
3686
+ this.roleArn = options.roleArn;
3687
+ this.roleSessionName = options.roleSessionName || "web-identity-session";
3688
+ this.durationSession = options.durationSession || 3600;
3689
+ this.awsClientSts = options.awsClientSts;
3690
+ this.awsClientS3 = options.awsClientS3;
3691
+ }
3692
+ static dummyData() {
3693
+ return {
3694
+ getIdToken: () => "mock-web-identity-token",
3695
+ roleArn: "arn:aws:iam::846252828949:role/oidcS3Jccpa",
3696
+ awsClientSts: {
3697
+ STSClient: class {
3698
+ },
3699
+ AssumeRoleWithWebIdentityCommand: class {
3700
+ }
3701
+ },
3702
+ awsClientS3: {
3703
+ S3Client: class {
3704
+ },
3705
+ PutObjectCommand: class {
3706
+ },
3707
+ GetObjectCommand: class {
3708
+ },
3709
+ DeleteObjectCommand: class {
3710
+ }
3711
+ }
3712
+ };
3713
+ }
3714
+ static init(options = {}) {
3715
+ if (options instanceof this) {
3716
+ return options;
3717
+ }
3718
+ try {
3719
+ const instance2 = new this(options);
3720
+ if (!instance2.isValid) {
3721
+ return null;
3722
+ }
3723
+ return instance2;
3724
+ } catch (error) {
3725
+ return null;
3726
+ }
3727
+ }
3728
+ get isExpired() {
3729
+ if (!this.expiration)
3730
+ return true;
3731
+ const now = /* @__PURE__ */ new Date();
3732
+ const bufferMs = 1 * 60 * 1e3;
3733
+ return now >= new Date(this.expiration.getTime() - bufferMs);
3734
+ }
3735
+ get isValid() {
3736
+ if (!this.getIdToken) {
3737
+ throw new Error("Missing required configuration: getIdToken function");
3738
+ }
3739
+ if (!this.roleArn) {
3740
+ throw new Error("Missing required configuration: roleArn");
3741
+ }
3742
+ if (!this.awsClientSts) {
3743
+ throw new Error("Missing required AWS awsClientSts client configuration");
3744
+ }
3745
+ if (!this.awsClientSts.STSClient) {
3746
+ throw new Error("Missing STSClient in AWS awsClientSts client configuration");
3747
+ }
3748
+ if (!this.awsClientSts.AssumeRoleWithWebIdentityCommand) {
3749
+ throw new Error("Missing AssumeRoleWithWebIdentityCommand in AWS awsClientSts client configuration");
3750
+ }
3751
+ if (!this.awsClientS3) {
3752
+ throw new Error("Missing required AWS awsClientS3 client configuration");
3753
+ }
3754
+ const requiredS3Components = [
3755
+ "S3Client",
3756
+ "PutObjectCommand",
3757
+ "GetObjectCommand",
3758
+ "DeleteObjectCommand"
3759
+ ];
3760
+ for (const component of requiredS3Components) {
3761
+ if (!this.awsClientS3[component]) {
3762
+ throw new Error(`Missing ${component} in AWS awsClientS3 client configuration`);
3763
+ }
3764
+ }
3765
+ return true;
3766
+ }
3767
+ async refreshCredentials() {
3768
+ try {
3769
+ const webIdentityToken = await this.getIdToken();
3770
+ if (!webIdentityToken) {
3771
+ throw new Error("getIdToken function returned empty or invalid token");
3772
+ }
3773
+ const stsClient = new this.awsClientSts.STSClient({ region: this.region });
3774
+ const stsResponse = await stsClient.send(
3775
+ new this.awsClientSts.AssumeRoleWithWebIdentityCommand({
3776
+ RoleArn: this.roleArn,
3777
+ RoleSessionName: this.roleSessionName,
3778
+ WebIdentityToken: await this.getIdToken(),
3779
+ DurationSeconds: this.durationSession
3780
+ })
3781
+ );
3782
+ const credentials = stsResponse.Credentials;
3783
+ if (!credentials) {
3784
+ throw new Error("No credentials returned from awsClientSts");
3785
+ }
3786
+ this.expiration = credentials.Expiration;
3787
+ this.s3Client = new this.awsClientS3.S3Client({
3788
+ region: this.region,
3789
+ credentials: {
3790
+ accessKeyId: credentials.AccessKeyId,
3791
+ secretAccessKey: credentials.SecretAccessKey,
3792
+ sessionToken: credentials.SessionToken
3793
+ }
3794
+ });
3795
+ return this;
3796
+ } catch (error) {
3797
+ throw new Error(`Failed to refresh credentials: ${error.message}`);
3798
+ }
3799
+ }
3800
+ async getS3Client() {
3801
+ if (this.isExpired || !this.s3Client) {
3802
+ await this.refreshCredentials();
3803
+ }
3804
+ return this.s3Client;
3805
+ }
3806
+ async putObject(params) {
3807
+ try {
3808
+ const client = await this.getS3Client();
3809
+ const command = new this.awsClientS3.PutObjectCommand(params);
3810
+ await client.send(command);
3811
+ const fileArr = params.Key.split("/");
3812
+ return {
3813
+ url: `https://s3.${this.region}.amazonaws.com/${params.Bucket}/${params.Key}`,
3814
+ filename: fileArr.pop(),
3815
+ folder: params.Bucket,
3816
+ subFolders: fileArr
3817
+ };
3818
+ } catch (error) {
3819
+ throw new Error(`Failed to put object: ${error.message}`);
3820
+ }
3821
+ }
3822
+ async getObject(params) {
3823
+ try {
3824
+ const client = await this.getS3Client();
3825
+ const command = new this.awsClientS3.GetObjectCommand(params);
3826
+ const response = await client.send(command);
3827
+ return {
3828
+ body: response.Body,
3829
+ contentType: response.ContentType,
3830
+ lastModified: response.LastModified,
3831
+ contentLength: response.ContentLength
3832
+ };
3833
+ } catch (error) {
3834
+ throw new Error(`Failed to get object: ${error.message}`);
3835
+ }
3836
+ }
3837
+ async deleteObject(params) {
3838
+ try {
3839
+ const client = await this.getS3Client();
3840
+ const command = new this.awsClientS3.DeleteObjectCommand(params);
3841
+ await client.send(command);
3842
+ return true;
3843
+ } catch (error) {
3844
+ throw new Error(`Failed to delete object: ${error.message}`);
3845
+ }
3846
+ }
3847
+ }
3848
+ const DELIMITER = "_";
3849
+ class Metadata extends KeyValueObject {
3850
+ static init(options = {}) {
3851
+ if (options instanceof this) {
3852
+ return options;
3853
+ }
3854
+ const instance2 = new this({
3855
+ ...options,
3856
+ key: stringFormatter(options.key, DELIMITER)
3857
+ });
3858
+ return instance2.isValid ? instance2 : null;
3859
+ }
3860
+ static get _classname() {
3861
+ return "Metadata";
3862
+ }
3863
+ // Override the fromArrayWithCustomMapping method
3864
+ static mapToKeyValue(arr = [], keyPath = "key", valuePath = "value") {
3865
+ if (!Array.isArray(arr)) {
3866
+ return [];
3867
+ }
3868
+ return arr.reduce((acc, item) => {
3869
+ if (item && typeof item === "object") {
3870
+ const key = objectHelper.get(item, keyPath);
3871
+ const value = objectHelper.get(item, valuePath);
3872
+ if (key !== void 0 && key !== null) {
3873
+ const formattedValue = value !== void 0 ? stringHelper.toScreamingSnakeCase(String(value)) : "";
3874
+ acc.push(this.init({
3875
+ key,
3876
+ value: formattedValue
3877
+ }));
3878
+ }
3879
+ }
3880
+ return acc;
3881
+ }, []);
3882
+ }
3883
+ static merge(toArr, fromArr) {
3884
+ (fromArr || []).map((from) => {
3885
+ const found = toArr.find((to) => {
3886
+ return _isSame(to.key, from.key);
3887
+ });
3888
+ if (found) {
3889
+ found.value = _mergeValues(from.value, found.value);
3890
+ } else {
3891
+ toArr.push(from);
3892
+ }
3893
+ return from;
3894
+ });
3895
+ return toArr;
3896
+ }
3897
+ static sameKey(item, key) {
3898
+ return _isSame(item.key, key);
3899
+ }
3900
+ }
3901
+ function _isSame(key1, key2) {
3902
+ return stringFormatter(key1, DELIMITER) === stringFormatter(key2, DELIMITER);
3903
+ }
3904
+ function _mergeValues(existingValue, newValue) {
3905
+ if (existingValue === void 0)
3906
+ return newValue;
3907
+ if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3908
+ return [.../* @__PURE__ */ new Set([...existingValue, ...newValue])];
3909
+ }
3910
+ if (typeof existingValue === "object" && typeof newValue === "object" && !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3911
+ return { ...existingValue, ...newValue };
3912
+ }
3913
+ return newValue;
3914
+ }
3915
+ class TrackedEntity {
3916
+ constructor(options = {}) {
3917
+ var _a, _b, _c, _d, _e, _f;
3918
+ options = options || {};
3919
+ const id = options._id || options.id;
3920
+ this.id = setId(id);
3921
+ this._type = options._type || "TrackedEntity";
3922
+ const timestamp = Date.now();
3923
+ this.meta = {
3924
+ active: ((_a = options.meta) == null ? void 0 : _a.active) ?? options.active ?? true,
3925
+ created: ((_b = options.meta) == null ? void 0 : _b.created) ?? (options.created ? new Date(options.created).getTime() : timestamp),
3926
+ creator: ((_c = options.meta) == null ? void 0 : _c.creator) ?? options.creator ?? "",
3927
+ deleted: ((_d = options.meta) == null ? void 0 : _d.deleted) ?? options.deleted ?? false,
3928
+ modified: ((_e = options.meta) == null ? void 0 : _e.modified) ?? (options.modified ? new Date(options.modified).getTime() : timestamp),
3929
+ owner: ((_f = options.meta) == null ? void 0 : _f.owner) ?? options.owner ?? ""
3930
+ };
3931
+ }
3932
+ // Class methods
3933
+ static dummyData() {
3934
+ const now = Date.now();
3935
+ return {
3936
+ meta: {
3937
+ active: true,
3938
+ deleted: false,
3939
+ created: now,
3940
+ creator: "creator",
3941
+ modified: now,
3942
+ owner: "owner"
3943
+ }
3944
+ };
3945
+ }
3946
+ static get _classname() {
3947
+ return "TrackedEntity";
3948
+ }
3949
+ static get _superclass() {
3950
+ return "TrackedEntity";
3951
+ }
3952
+ static init(options = {}) {
3953
+ return init(this, options);
3954
+ }
3955
+ static initFromArray(arr = []) {
3956
+ return initFromArray(this, arr);
3957
+ }
3958
+ static initOnlyValidFromArray(arr = []) {
3959
+ return initOnlyValidFromArray(this, arr);
3960
+ }
3961
+ // static nest(entity) {
3962
+ // const { active, created, creator, deleted, modified, owner, ...rest } = entity
3963
+ // return { ...rest, meta: { active, created, creator, deleted, modified, owner } }
3964
+ // }
3965
+ // getters
3966
+ get __valid() {
3967
+ return {};
3968
+ }
3969
+ get isValid() {
3970
+ return !!this;
3971
+ }
3972
+ get active() {
3973
+ var _a;
3974
+ return ((_a = this.meta) == null ? void 0 : _a.active) ?? this.active;
3975
+ }
3976
+ get created() {
3977
+ var _a;
3978
+ return ((_a = this.meta) == null ? void 0 : _a.created) ?? this.created;
3979
+ }
3980
+ get creator() {
3981
+ var _a;
3982
+ return ((_a = this.meta) == null ? void 0 : _a.creator) ?? this.creator;
3983
+ }
3984
+ get deleted() {
3985
+ var _a;
3986
+ return ((_a = this.meta) == null ? void 0 : _a.deleted) ?? this.deleted;
3987
+ }
3988
+ get modified() {
3989
+ var _a;
3990
+ return ((_a = this.meta) == null ? void 0 : _a.modified) ?? this.modified;
3991
+ }
3992
+ get owner() {
3993
+ var _a;
3994
+ return ((_a = this.meta) == null ? void 0 : _a.owner) ?? this.owner;
3995
+ }
3996
+ changeCreatorOwner({ source, target }) {
3997
+ return changeCreatorOwner(this, { source, target }).setModified();
3998
+ }
3999
+ delete() {
4000
+ return this.setDeleted();
4001
+ }
4002
+ setActive() {
4003
+ if (this.meta) {
4004
+ this.meta.active = true;
4005
+ } else {
4006
+ this.active = true;
4007
+ }
4008
+ return this;
4009
+ }
4010
+ setDeleted() {
4011
+ if (this.meta) {
4012
+ this.meta.deleted = true;
4013
+ } else {
4014
+ this.deleted = true;
4015
+ }
4016
+ return this;
4017
+ }
4018
+ setModified() {
4019
+ const timestamp = Date.now();
4020
+ if (this.meta) {
4021
+ this.meta.modified = timestamp;
4022
+ } else {
4023
+ this.modified = timestamp;
4024
+ }
4025
+ return this;
4026
+ }
4027
+ setOwner(owner) {
4028
+ if (!owner) {
4029
+ return this;
4030
+ }
4031
+ if (this.meta) {
4032
+ this.meta.owner = owner;
4033
+ } else {
4034
+ this.owner = owner;
4035
+ }
4036
+ return this;
4037
+ }
4038
+ unsetActive() {
4039
+ if (this.meta) {
4040
+ this.meta.active = false;
4041
+ } else {
4042
+ this.active = false;
4043
+ }
4044
+ return this;
4045
+ }
4046
+ unsetDeleted() {
4047
+ if (this.meta) {
4048
+ this.meta.deleted = false;
4049
+ } else {
4050
+ this.deleted = false;
4051
+ }
4052
+ return this;
4053
+ }
4054
+ update(update) {
4055
+ const allowedProps = this.constructor.ALLOWED_META_PROPS;
4056
+ const newMeta = { ...this.meta };
4057
+ if (update.meta) {
4058
+ allowedProps.forEach((prop) => {
4059
+ if (update.meta.hasOwnProperty(prop)) {
4060
+ newMeta[prop] = update.meta[prop];
4061
+ }
4062
+ });
4063
+ }
4064
+ allowedProps.forEach((prop) => {
4065
+ if (update.hasOwnProperty(prop)) {
4066
+ newMeta[prop] = update[prop];
4067
+ }
4068
+ });
4069
+ if (JSON.stringify(this.meta) !== JSON.stringify(newMeta)) {
4070
+ this.meta = newMeta;
4071
+ }
4072
+ return this.setModified();
4073
+ }
4074
+ }
4075
+ // In your class definition
4076
+ __publicField(TrackedEntity, "ALLOWED_META_PROPS", ["active", "deleted", "owner"]);
4077
+ class PushEnvelope extends TrackedEntity {
4078
+ constructor(options) {
4079
+ options = options || {};
4080
+ super(options);
4081
+ this.id = options.id;
4082
+ this.body = options.body;
4083
+ this.data = options.data;
4084
+ this.dirty = options.dirty;
4085
+ this.metadata = Metadata.initOnlyValidFromArray(options.metadata);
4086
+ this.remarks = KeyValueObject.initOnlyValidFromArray(options.remarks);
4087
+ this.threadID = options.threadID;
4088
+ this.title = options.title;
4089
+ }
4090
+ static get _classname() {
4091
+ return "PushEnvelope";
4092
+ }
4093
+ static get _superclass() {
4094
+ return "PushEnvelope";
4095
+ }
4096
+ static init(options = {}) {
4097
+ return init(this, options);
4098
+ }
4099
+ get _classname() {
4100
+ return "PushEnvelope";
4101
+ }
4102
+ get _superclass() {
4103
+ return "PushEnvelope";
4104
+ }
4105
+ get isValid() {
4106
+ return super.isValid && this.data;
4107
+ }
4108
+ }
4109
+ const QLogLevel = {
4110
+ trace: { weight: 10, name: "TRACE" },
4111
+ debug: { weight: 20, name: "DEBUG" },
4112
+ info: { weight: 30, name: "INFO" },
4113
+ warn: { weight: 40, name: "WARN" },
4114
+ error: { weight: 50, name: "ERROR" },
4115
+ critical: { weight: 60, name: "CRITICAL" },
4116
+ alert: { weight: 70, name: "ALERT" },
4117
+ emergency: { weight: 80, name: "EMERGENCY" }
4118
+ };
4119
+ class LogRecord {
4120
+ constructor(options = {}) {
4121
+ options = options || {};
4122
+ this.data = options.data;
4123
+ this.level = options.level;
4124
+ this.timestamp = options.timestamp;
4125
+ this.stackTrace = _setStackTrace(options);
4126
+ this.name = options.name ?? "";
4127
+ this.zone = options.zone;
4128
+ }
4129
+ toString() {
4130
+ return `[${this.logName(this)}] ${this.serialize(this)}
4131
+ ${this.stackTrace || ""}
4132
+ ${this.zone || ""}`;
4133
+ }
4134
+ logName() {
4135
+ let result = `${this.timestamp}`;
4136
+ if (this.level.name) {
4137
+ result += `>${this.level.name}`;
4138
+ }
4139
+ if (this.name) {
4140
+ result += `>${this.name}`;
4141
+ }
4142
+ return result;
4143
+ }
4144
+ serialize() {
4145
+ var _a;
4146
+ if (this.data instanceof Error || typeof ((_a = this.data) == null ? void 0 : _a.message) !== "undefined") {
4147
+ return this.data.message;
4148
+ }
4149
+ if (this.data === null) {
4150
+ return "null";
4151
+ }
4152
+ if (this.data === void 0) {
4153
+ return "undefined";
4154
+ }
4155
+ if (typeof this.data === "object") {
4156
+ return JSON.stringify(this.data);
4157
+ }
4158
+ return this.data.toString();
4159
+ }
4160
+ }
4161
+ function _setStackTrace(options) {
4162
+ var _a;
4163
+ if (options.stackTrace) {
4164
+ return options.stackTrace;
4165
+ }
4166
+ if (options.data instanceof Error || typeof ((_a = options.data) == null ? void 0 : _a.stack) !== "undefined") {
4167
+ return options.data.stack;
4168
+ }
4169
+ return null;
4170
+ }
4171
+ let instance;
4172
+ class QLog {
4173
+ constructor(options = {}) {
4174
+ const { level } = options;
4175
+ this._level = level ?? QLogLevel.debug;
4176
+ this._handlers = /* @__PURE__ */ new Map();
4177
+ }
4178
+ static getInstance(options) {
4179
+ if (!instance) {
4180
+ instance = new QLog(options);
4181
+ }
4182
+ return instance;
4183
+ }
4184
+ setLevel(level) {
4185
+ this._level = level;
4186
+ return this;
4187
+ }
4188
+ addHandler(handler) {
4189
+ if (handler instanceof QLog) {
4190
+ this._handlers.set(handler.constructor, handler);
4191
+ }
4192
+ return this;
4193
+ }
4194
+ removeHandler(handlerClass) {
4195
+ this._handlers.delete(handlerClass);
4196
+ return this;
4197
+ }
4198
+ receive({ record }) {
4199
+ var _a, _b;
4200
+ if (((_a = record.level) == null ? void 0 : _a.weight) < ((_b = this._level) == null ? void 0 : _b.weight)) {
4201
+ return;
4202
+ }
4203
+ this._handlers.forEach((value) => {
4204
+ value.receive({ record });
4205
+ });
4206
+ this.logBody(record);
4207
+ }
4208
+ logBody(record) {
4209
+ }
4210
+ trace(options, object) {
4211
+ return this._log({
4212
+ level: QLogLevel.trace,
4213
+ object,
4214
+ options
4215
+ });
4216
+ }
4217
+ debug(options, object) {
4218
+ return this._log({
4219
+ level: QLogLevel.debug,
4220
+ object,
4221
+ options
4222
+ });
4223
+ }
4224
+ info(options, object) {
4225
+ return this._log({
4226
+ level: QLogLevel.info,
4227
+ object,
4228
+ options
4229
+ });
4230
+ }
4231
+ warn(options, object) {
4232
+ return this._log({
4233
+ level: QLogLevel.warn,
4234
+ object,
4235
+ options
4236
+ });
4237
+ }
4238
+ error(options, object) {
4239
+ return this._log({
4240
+ level: QLogLevel.error,
4241
+ object,
4242
+ options
4243
+ });
4244
+ }
4245
+ critical(options, object) {
4246
+ return this._log({
4247
+ level: QLogLevel.critical,
4248
+ object,
4249
+ options
4250
+ });
4251
+ }
4252
+ _log({ level, object, options }) {
4253
+ if (typeof object === "undefined") {
4254
+ object = options;
4255
+ options = "";
4256
+ }
4257
+ const timestamp = Date.now();
4258
+ const record = new LogRecord({
4259
+ data: object,
4260
+ level,
4261
+ timestamp,
4262
+ stackTrace: (object == null ? void 0 : object.stack) ?? (options == null ? void 0 : options.stack) ?? null,
4263
+ name: options ?? ""
4264
+ });
4265
+ return this.receive({ record });
4266
+ }
4267
+ }
4268
+ class ConsoleLog extends QLog {
4269
+ constructor(options = {}) {
4270
+ const { format } = options;
4271
+ super(options);
4272
+ this.format = format;
4273
+ }
4274
+ logBody(record) {
4275
+ const logName = record.logName();
4276
+ const message = this.format ? this.format(record) : record.serialize();
4277
+ switch (record.level) {
4278
+ case QLogLevel.error:
4279
+ case QLogLevel.critical:
4280
+ case QLogLevel.alert:
4281
+ case QLogLevel.emergency:
4282
+ console.error(`[${logName}] ${message}`, record.stackTrace || "");
4283
+ break;
4284
+ case QLogLevel.warn:
4285
+ console.warn(`[${logName}] ${message}`, record.stackTrace || "");
4286
+ break;
4287
+ case QLogLevel.info:
4288
+ console.error(`[${logName}] ${message}`, record.stackTrace || "");
4289
+ break;
4290
+ case QLogLevel.debug:
4291
+ console.error(`[${logName}] ${message}`, record.stackTrace || "");
4292
+ break;
4293
+ default:
4294
+ console.error(`[${logName}] ${message}`, record.stackTrace || "");
4295
+ }
4296
+ }
4297
+ }
4298
+ const QLogEnv = {
4299
+ debug: { name: "DEBUG" },
4300
+ production: { name: "PRODUCTION" }
4301
+ };
4302
+ function getQLogEnv(name) {
4303
+ const key = name.toLowerCase();
4304
+ if (QLogEnv[key]) {
4305
+ return QLogEnv[key];
4306
+ }
4307
+ return null;
4308
+ }
4309
+ const updateAllowedProps = [
4310
+ "attributes",
4311
+ "ref"
4312
+ ];
4313
+ class QMeta {
4314
+ constructor(options = {}) {
4315
+ options = options || {};
4316
+ this.attributes = KeyValueObject.initOnlyValidFromArray(options.attributes);
4317
+ this.ref = options.ref || {};
4318
+ }
4319
+ static get _classname() {
4320
+ return "QMeta";
4321
+ }
4322
+ static get _superclass() {
4323
+ return "QMeta";
4324
+ }
4325
+ // Class methods
4326
+ static init(options = {}) {
4327
+ if (options instanceof QMeta) {
4328
+ return options;
4329
+ }
4330
+ return new QMeta(options);
4331
+ }
4332
+ // instance methods
4333
+ addAttribute(obj) {
4334
+ const kvObject = KeyValueObject.init(obj);
4335
+ if (!kvObject) {
4336
+ throw new Error("invalid meta attribute");
4337
+ }
4338
+ this.attributes.push(kvObject);
4339
+ return this;
4340
+ }
4341
+ update(obj) {
4342
+ Object.keys(obj).forEach((key) => {
4343
+ if (updateAllowedProps.includes(key)) {
4344
+ if (key === "attributes") {
4345
+ this[key] = KeyValueObject.initOnlyValidFromArray(obj[key]);
4346
+ } else {
4347
+ this[key] = obj[key];
4348
+ }
4349
+ }
4350
+ });
4351
+ return this;
4352
+ }
4353
+ }
4354
+ class ActionRecord {
4355
+ constructor(options) {
4356
+ options = options || {};
4357
+ const { _Actor } = options._constructor || {};
4358
+ this._Actor = _Actor;
4359
+ this._actor = options._actor;
4360
+ this.actorCode = typeof options === "number" ? null : options.actorCode || null;
4361
+ this.timestamp = typeof options === "number" ? options : options.timestamp || null;
4362
+ }
4363
+ static get _classname() {
4364
+ return "ActionRecord";
4365
+ }
4366
+ static get _superclass() {
4367
+ return "ActionRecord";
4368
+ }
4369
+ static dummyData() {
4370
+ return {
4371
+ timestamp: (/* @__PURE__ */ new Date()).valueOf()
4372
+ };
4373
+ }
4374
+ static init(options = {}) {
4375
+ return init(this, options);
4376
+ }
4377
+ get _classname() {
4378
+ return "ActionRecord";
4379
+ }
4380
+ get _superclass() {
4381
+ return "ActionRecord";
4382
+ }
4383
+ get actor() {
4384
+ return this._Actor && typeof this._Actor.init === "function" ? this._Actor.init(this._actor) : this._actor;
4385
+ }
4386
+ get isValid() {
4387
+ return !!this.timestamp;
4388
+ }
4389
+ update(update) {
4390
+ if (typeof update === "number") {
4391
+ this.timestamp = update;
4392
+ return this;
4393
+ }
4394
+ Object.keys(update).forEach((key) => {
4395
+ this[key] = update[key];
4396
+ });
4397
+ return this;
4398
+ }
4399
+ }
4400
+ const notUpdateAllowedProps = [
4401
+ "_ActionRecord",
4402
+ "created"
4403
+ // 'statusType'
4404
+ ];
4405
+ class Status {
4406
+ constructor(options) {
4407
+ options = options || {};
4408
+ const { _ActionRecord } = options._constructor || {};
4409
+ this._ActionRecord = _ActionRecord && _ActionRecord._superclass === ActionRecord._superclass ? _ActionRecord : ActionRecord;
4410
+ this.created = this._ActionRecord.init(options.created || { timestamp: (/* @__PURE__ */ new Date()).valueOf() });
4411
+ }
4412
+ static get _classname() {
4413
+ return "Status";
4414
+ }
4415
+ static get _superclass() {
4416
+ return "Status";
4417
+ }
4418
+ static dummyData() {
4419
+ return {};
4420
+ }
4421
+ static init(options = {}) {
4422
+ return init(this, options);
4423
+ }
4424
+ static initFromArray(arr = []) {
4425
+ return initFromArray(this, arr);
4426
+ }
4427
+ static initOnlyValidFromArray(arr = []) {
4428
+ return initOnlyValidFromArray(this, arr);
4429
+ }
4430
+ get _classname() {
4431
+ return "Status";
4432
+ }
4433
+ get _superclass() {
4434
+ return "Status";
4435
+ }
4436
+ get isCreated() {
4437
+ var _a;
4438
+ return ((_a = this.created) == null ? void 0 : _a.timestamp) !== null;
4439
+ }
4440
+ get isValid() {
4441
+ return !!this;
4442
+ }
4443
+ setValue(t, actorCode, key) {
4444
+ const timestamp = t || Date.now();
4445
+ this[key] = this[key] instanceof this._ActionRecord ? this[key].update({ actorCode, timestamp }) : this._ActionRecord.init({ actorCode, timestamp });
4446
+ return this;
4447
+ }
4448
+ update(update) {
4449
+ Object.keys(update).forEach((key) => {
4450
+ if (!notUpdateAllowedProps.includes(key)) {
4451
+ this[key] = this[key] instanceof this._ActionRecord ? this[key].update(update[key]) : this._ActionRecord.init(update[key]);
4452
+ }
4453
+ });
4454
+ return this;
4455
+ }
4456
+ }
4457
+ class StatusDocument extends Status {
4458
+ constructor(options) {
4459
+ options = options || {};
4460
+ super(options);
4461
+ this.archived = this._ActionRecord.init(options.archived);
4462
+ this.completed = this._ActionRecord.init(options.completed);
4463
+ this.discarded = this._ActionRecord.init(options.discarded);
4464
+ this.drafted = this._ActionRecord.init(options.drafted);
4465
+ }
4466
+ static get _classname() {
4467
+ return "StatusDocument";
4468
+ }
4469
+ get _classname() {
4470
+ return "StatusDocument";
4471
+ }
4472
+ get isArchived() {
4473
+ var _a;
4474
+ return ((_a = this.created) == null ? void 0 : _a.timestamp) !== null;
4475
+ }
4476
+ get isCompleted() {
4477
+ var _a;
4478
+ return ((_a = this.completed) == null ? void 0 : _a.timestamp) !== null;
4479
+ }
4480
+ get isDiscarded() {
4481
+ var _a;
4482
+ return ((_a = this.discarded) == null ? void 0 : _a.timestamp) !== null;
4483
+ }
4484
+ get isDrafted() {
4485
+ var _a;
4486
+ return ((_a = this.drafted) == null ? void 0 : _a.timestamp) !== null;
4487
+ }
4488
+ get isValid() {
4489
+ return super.isValid;
4490
+ }
4491
+ setArchived(value, actorCode) {
4492
+ return this.setValue(value, actorCode, "archived");
4493
+ }
4494
+ setCompleted(value, actorCode) {
4495
+ return this.setValue(value, actorCode, "completed");
4496
+ }
4497
+ setDiscarded(value, actorCode) {
4498
+ return this.setValue(value, actorCode, "discarded");
4499
+ }
4500
+ setDrafted(value, actorCode) {
4501
+ return this.setValue(value, actorCode, "drafted");
4502
+ }
4503
+ }
4504
+ class TenantAwareEntity extends TrackedEntity {
4505
+ constructor(options = {}) {
4506
+ options = options || {};
4507
+ super(options);
4508
+ this._type = options._type || "TenantAwareEntity";
4509
+ this._tenant = options._tenant;
4510
+ this.metadata = Metadata.initOnlyValidFromArray(options.metadata);
4511
+ this.remarks = KeyValueObject.initOnlyValidFromArray(options.remarks);
4512
+ this.tenantCode = options.tenantCode;
4513
+ }
4514
+ // Class methods
4515
+ static dummyData() {
4516
+ return {
4517
+ ...super.dummyData(),
4518
+ metadata: [],
4519
+ remarks: [],
4520
+ tenantCode: "tenantCode"
4521
+ };
4522
+ }
4523
+ static get _classname() {
4524
+ return "TenantAwareEntity";
4525
+ }
4526
+ static get _superclass() {
4527
+ return "TenantAwareEntity";
4528
+ }
4529
+ // getters
4530
+ get __valid() {
4531
+ return {
4532
+ ...super.__valid,
4533
+ tenantCode: this.tenantCode
4534
+ };
4535
+ }
4536
+ get isValid() {
4537
+ return super.isValid && !!this.tenantCode;
4538
+ }
4539
+ // instance methods
4540
+ insertOrUpdateMetadata(key, value) {
4541
+ this.metadata = Metadata.insertOrUpdateRecord(this.metadata, key, value);
4542
+ return this;
4543
+ }
4544
+ getMetadata() {
4545
+ return this.metadata;
4546
+ }
4547
+ getMetadataByKey(key) {
4548
+ return Metadata.foundByKey(this.metadata, key);
4549
+ }
4550
+ getMetadataValueByKey(key) {
4551
+ const found = this.getMetadataByKey(key);
4552
+ return found ? found.value : null;
4553
+ }
4554
+ getMetadataValueByKeys(keys, kv) {
4555
+ if (!Array.isArray(keys)) {
4556
+ return null;
4557
+ }
4558
+ kv = kv || this.metadata;
4559
+ if (keys.length === 0) {
4560
+ return kv;
4561
+ }
4562
+ const key = keys.shift();
4563
+ const _val = Metadata.getMetadataValueByKeyAsArray(kv, key);
4564
+ return this.getMetadataValueByKeys(keys, _val);
4565
+ }
4566
+ getMetadataValueByKeyAsArray(key) {
4567
+ return Metadata.getMetadataValueByKeyAsArray(this.metadata, key);
4568
+ }
4569
+ getRemarks() {
4570
+ return this.remarks;
4571
+ }
4572
+ getRemarkByKey(key) {
4573
+ return KeyValueObject.foundByKey(this.remarks, key);
4574
+ }
4575
+ getRemarksValueByKey(key) {
4576
+ const found = this.getRemarkByKey(key);
4577
+ return found ? found.value : null;
4578
+ }
4579
+ getTenantCode() {
4580
+ return this.tenantCode;
4581
+ }
4582
+ update(update) {
4583
+ if (update.metadata && Array.isArray(update.metadata)) {
4584
+ this.metadata = Metadata.initOnlyValidFromArray(update.metadata);
4585
+ }
4586
+ if (update.remarks && Array.isArray(update.remarks)) {
4587
+ this.remarks = KeyValueObject.initOnlyValidFromArray(update.remarks);
4588
+ }
4589
+ return super.update(update);
4590
+ }
4591
+ }
4592
+ class UniqueKeyGenerator {
4593
+ static get _classname() {
4594
+ return "UniqueKeyGenerator";
4595
+ }
4596
+ static get _superclass() {
4597
+ return "UniqueKeyGenerator";
4598
+ }
4599
+ static makeFormatter({ fieldName, format, options }) {
4600
+ switch (format) {
4601
+ case "set_code":
4602
+ return _makeSetCode(fieldName);
4603
+ default:
4604
+ return _makeSetCode(fieldName);
4605
+ }
4606
+ }
4607
+ static makeGenerator(arr) {
4608
+ const fns = arr.map((item) => this.makeFormatter(item));
4609
+ return async (obj) => {
4610
+ const output = await pReduce(fns, async (acc, fn) => {
4611
+ const _obj = await fn(obj);
4612
+ return Object.assign(acc, _obj);
4613
+ }, obj);
4614
+ return output;
4615
+ };
4616
+ }
4617
+ }
4618
+ function _makeSetCode(fieldName, options) {
4619
+ return async (obj = {}) => {
4620
+ if (obj[fieldName]) {
4621
+ return {};
4622
+ }
4623
+ return {
4624
+ [fieldName]: stringHelper.setCode()
4625
+ };
4626
+ };
4627
+ }
4628
+ class WebAppRequest {
4629
+ constructor(options = {}) {
4630
+ this.blockUI = options.blockUI ?? false;
4631
+ this.callback = options.callback ?? null;
4632
+ this.data = options.data ?? null;
4633
+ this.event = options.event ?? null;
4634
+ this.reloadPage = options.reloadPage ?? false;
4635
+ this.sessionId = options.sessionId ?? null;
4636
+ this.timeout = options.timeout ?? 3e4;
4637
+ }
4638
+ // Class methods
4639
+ static get _classname() {
4640
+ return "WebAppRequest";
4641
+ }
4642
+ static get _superclass() {
4643
+ return "WebAppRequest";
4644
+ }
4645
+ static init(options) {
4646
+ if (options instanceof WebAppRequest) {
4647
+ return options;
4648
+ }
4649
+ const instance2 = new WebAppRequest(options);
4650
+ return instance2.isValid ? instance2 : null;
4651
+ }
4652
+ static dummyData() {
4653
+ return {
4654
+ data: null,
4655
+ sessionId: "sessionId"
4656
+ };
4657
+ }
4658
+ // getters
4659
+ get isValid() {
4660
+ return !!this.sessionId;
4661
+ }
4662
+ getId() {
4663
+ try {
4664
+ return this.sessionId;
4665
+ } catch (err) {
4666
+ return null;
4667
+ }
4668
+ }
4669
+ }
4670
+ const ERROR_CODES = {
4671
+ EXCUTE_EVENT_ERROR: "EXCUTE_EVENT_ERROR",
4672
+ NOT_FOUND: "NOT_FOUND",
4673
+ SERVER_ERROR: "SERVER_ERROR",
4674
+ TIMEOUT: "TIMEOUT",
4675
+ UNAUTHORIZED: "UNAUTHORIZED",
4676
+ VALIDATION_ERROR: "VALIDATION_ERROR"
4677
+ };
4678
+ class ErrorDetail {
4679
+ constructor(options = {}) {
4680
+ this.code = options.code ?? null;
4681
+ this.message = options.message ?? "";
4682
+ this.timestamp = options.timestamp ?? null;
4683
+ }
4684
+ static init(options) {
4685
+ if (options instanceof ErrorDetail) {
4686
+ return options;
4687
+ }
4688
+ const instance2 = new ErrorDetail(options);
4689
+ return instance2.isValid ? instance2 : null;
4690
+ }
4691
+ get isValid() {
4692
+ return !!this.code;
4693
+ }
4694
+ }
4695
+ class WebAppResponse {
4696
+ constructor(options = {}) {
4697
+ this.data = options.data ?? null;
4698
+ this.errorDetail = ErrorDetail.init(options.errorDetail);
4699
+ this.sessionId = options.sessionId ?? null;
4700
+ this.success = options.success ?? false;
4701
+ }
4702
+ // Class methods
4703
+ static get _classname() {
4704
+ return "WebAppResponse";
4705
+ }
4706
+ static get _superclass() {
4707
+ return "WebAppResponse";
4708
+ }
4709
+ static init(options) {
4710
+ if (options instanceof WebAppResponse) {
4711
+ return options;
4712
+ }
4713
+ const instance2 = new WebAppResponse(options);
4714
+ return instance2.isValid ? instance2 : null;
4715
+ }
4716
+ static dummyData() {
4717
+ return {
4718
+ data: null,
4719
+ errorDetail: null,
4720
+ sessionId: "sessionId",
4721
+ success: false
4722
+ };
4723
+ }
4724
+ // getters
4725
+ get isValid() {
4726
+ return !!this.sessionId;
4727
+ }
4728
+ getId() {
4729
+ try {
4730
+ return this.sessionId;
4731
+ } catch (err) {
4732
+ return null;
4733
+ }
4734
+ }
4735
+ }
4736
+ const models = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4737
+ __proto__: null,
4738
+ ActionRecord,
4739
+ ApiResponse,
4740
+ AwsStsS3Client,
4741
+ ConsoleLog,
4742
+ ERROR_CODES,
4743
+ ErrorDetail,
4744
+ KeyValueObject,
4745
+ LogRecord,
4746
+ Metadata,
4747
+ PushEnvelope,
4748
+ QLog,
4749
+ QLogEnv,
4750
+ QLogLevel,
4751
+ QMeta,
4752
+ Repo,
4753
+ Service,
4754
+ Status,
4755
+ StatusDocument,
4756
+ TemplateCompiler,
4757
+ TenantAwareEntity,
4758
+ TrackedEntity,
4759
+ UniqueKeyGenerator,
4760
+ WebAppRequest,
4761
+ WebAppResponse,
4762
+ getQLogEnv,
4763
+ makeApiResponse,
4764
+ makeService
4765
+ }, Symbol.toStringTag, { value: "Module" }));
4766
+ const index = {
4767
+ ...helpers,
4768
+ ...models
4769
+ };
4770
+ exports.ActionRecord = ActionRecord;
4771
+ exports.ApiResponse = ApiResponse;
4772
+ exports.AwsStsS3Client = AwsStsS3Client;
4773
+ exports.CheckResult = CheckResult;
4774
+ exports.ConsoleLog = ConsoleLog;
4775
+ exports.ERROR_CODES = ERROR_CODES;
4776
+ exports.ErrorDetail = ErrorDetail;
4777
+ exports.ExcelImportHelper = ExcelImportHelper;
4778
+ exports.KeyValueObject = KeyValueObject;
4779
+ exports.LogRecord = LogRecord;
4780
+ exports.Metadata = Metadata;
4781
+ exports.PushEnvelope = PushEnvelope;
4782
+ exports.QLog = QLog;
4783
+ exports.QLogEnv = QLogEnv;
4784
+ exports.QLogLevel = QLogLevel;
4785
+ exports.QMeta = QMeta;
4786
+ exports.Repo = Repo;
4787
+ exports.Service = Service;
4788
+ exports.Status = Status;
4789
+ exports.StatusDocument = StatusDocument;
4790
+ exports.TemplateCompiler = TemplateCompiler;
4791
+ exports.TenantAwareEntity = TenantAwareEntity;
4792
+ exports.TrackedEntity = TrackedEntity;
4793
+ exports.UniqueKeyGenerator = UniqueKeyGenerator;
4794
+ exports.WebAppRequest = WebAppRequest;
4795
+ exports.WebAppResponse = WebAppResponse;
4796
+ exports.authorize = authorize;
4797
+ exports.calculateAge = calculateAge;
4798
+ exports.changeCreatorOwner = changeCreatorOwner;
4799
+ exports.concatStringByArray = concatStringByArray;
4800
+ exports.convertString = convertString;
4801
+ exports.convertTimestampToString = convertTimestampToString;
4802
+ exports.default = index;
4803
+ exports.detectControlCharacters = detectControlCharacters;
4804
+ exports.displayName = displayName;
4805
+ exports.downloadFileByUrl = downloadFileByUrl;
4806
+ exports.escapeRegex = escapeRegex;
4807
+ exports.expressHelper = expressHelper;
4808
+ exports.extractEmails = extractEmails;
4809
+ exports.formatDate = formatDate;
4810
+ exports.generalPost = generalPost;
4811
+ exports.getObjectByArr = getObjectByArr;
4812
+ exports.getQLogEnv = getQLogEnv;
4813
+ exports.getValidation = getValidation;
4814
+ exports.getValueByKeys = getValueByKeys;
4815
+ exports.groupArrayByKey = groupArrayByKey;
4816
+ exports.init = init;
4817
+ exports.initFromArray = initFromArray;
4818
+ exports.initOnlyValidFromArray = initOnlyValidFromArray;
4819
+ exports.isConvertibleToNumber = isConvertibleToNumber;
4820
+ exports.makeApiResponse = makeApiResponse;
4821
+ exports.makeService = makeService;
4822
+ exports.mergeArraysByKey = mergeArraysByKey;
4823
+ exports.objectHelper = objectHelper;
4824
+ exports.pMap = pMap;
4825
+ exports.pMapIterable = pMapIterable;
4826
+ exports.pMapSkip = pMapSkip;
4827
+ exports.pReduce = pReduce;
4828
+ exports.padZeros = padZeros;
4829
+ exports.printControlCharReport = printControlCharReport;
4830
+ exports.renderByTemplate = renderByTemplate;
4831
+ exports.replacePlaceholders = replacePlaceholders;
4832
+ exports.sanitizeText = sanitizeText;
4833
+ exports.setId = setId;
4834
+ exports.shuffleArray = shuffleArray;
4835
+ exports.stringFormatter = stringFormatter;
4836
+ exports.stringHelper = stringHelper;
4837
+ exports.tenantPlugin = tenantPlugin;
4838
+ exports.trackingPlugin = trackingPlugin;
4839
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
4840
+ })(this.qUtilities = this.qUtilities || {});
12
4841
  //# sourceMappingURL=q-utilities.iife.js.map