utiller 1.0.501 → 1.0.503
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/utiller/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_cryptoJs=_interopRequireDefault(require("crypto-js")),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner")),_uuid=require("uuid"),_nodeHtmlParser=require("node-html-parser"),_dayjs=_interopRequireDefault(require("dayjs"));require("dayjs/locale/zh-tw"),require("dayjs/locale/en");var _utc=_interopRequireDefault(require("dayjs/plugin/utc")),_timezone=_interopRequireDefault(require("dayjs/plugin/timezone")),_duration=_interopRequireDefault(require("dayjs/plugin/duration")),_customParseFormat=_interopRequireDefault(require("dayjs/plugin/customParseFormat")),_relativeTime=_interopRequireDefault(require("dayjs/plugin/relativeTime")),_isBetween=_interopRequireDefault(require("dayjs/plugin/isBetween"));_dayjs.default.extend(_utc.default),_dayjs.default.extend(_timezone.default),_dayjs.default.extend(_duration.default),_dayjs.default.extend(_customParseFormat.default),_dayjs.default.extend(_relativeTime.default),_dayjs.default.extend(_isBetween.default),_dayjs.default.locale("zh-tw"),String.format=function(){let e=[];for(let t=0,r=arguments.length;t<r;t++)e.push(arguments[t]);let t=e[0];return e.shift(),t.replace(/\{(\d+)\}/g,function(t,r){return e[r]})};class Utiller{upperFirst(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}camelCase(e){if(!e)return"";const t=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g);return t?t.map((e,t)=>{const r=e.toLowerCase();return 0===t?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(""):""}dropWhile(e,t){if(!Array.isArray(e))return[];let r=0;for(;r<e.length&&t(e[r],r,e);)r++;return e.slice(r)}dropRightWhile(e,t){if(!Array.isArray(e))return[];let r=e.length-1;for(;r>=0&&t(e[r],r,e);)r--;return e.slice(0,r+1)}removeMutate(e,t){if(!Array.isArray(e))return[];const r=[],n=[];e.forEach((i,a)=>{t(i,a,e)&&(r.push(i),n.push(a))});for(let t=n.length-1;t>=0;t--)e.splice(n[t],1);return r}isBoolean(e){return!0===e||!1===e||null!==e&&"object"==typeof e&&"[object Boolean]"===Object.prototype.toString.call(e)}isObject(e){if(null===e)return!1;const t=typeof e;return"object"===t||"function"===t}toString(e){if(null==e)return"";if("string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>this.toString(e)).join(",");if("symbol"==typeof e)return e.toString();const t=`${e}`;return"0"===t&&1/e==-1/0?"-0":t}toNumber(e){if("number"==typeof e)return e;if("symbol"==typeof e)return NaN;if(null!==e&&"object"==typeof e){const t="function"==typeof e.valueOf?e.valueOf():e;e="object"==typeof t?`${t}`:t}return"string"==typeof e&&(e=e.trim()),Number(e)}isString(e){return"string"==typeof e||null!==e&&"object"==typeof e&&"[object String]"===Object.prototype.toString.call(e)}isNumber(e){return"number"==typeof e||null!==e&&"object"==typeof e&&"[object Number]"===Object.prototype.toString.call(e)}isFunction(e){if(!e)return!1;const t=Object.prototype.toString.call(e);return"[object Function]"===t||"[object AsyncFunction]"===t||"[object GeneratorFunction]"===t||"[object Proxy]"===t}isEmpty(e){return null==e||(Array.isArray(e)||"string"==typeof e||"function"==typeof e.splice?0===e.length:e instanceof Map||e instanceof Set?0===e.size:"object"!=typeof e||0===Object.keys(e).length)}isEqual(e,t){if(e===t)return 0!==e||1/e==1/t;if(e!=e&&t!=t)return!0;if(null==e||null==t||"object"!=typeof e&&"object"!=typeof t)return!1;const r=Object.prototype.toString.call(e);if(r!==Object.prototype.toString.call(t))return!1;switch(r){case"[object Date]":case"[object Boolean]":return+e===+t;case"[object Number]":return e===+e?e===+t:e!=e&&t!=t;case"[object String]":case"[object RegExp]":return e===String(t)}if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!this.isEqual(e[r],t[r]))return!1;return!0}const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++){const i=n[r];if(!Object.prototype.hasOwnProperty.call(t,i)||!this.isEqual(e[i],t[i]))return!1}return!0}merge(e,...t){if(!t.length)return e;const r=t.shift();if(this.isPlainObject(e)&&this.isPlainObject(r))for(const t in r)this.isPlainObject(r[t])?(e[t]||Object.assign(e,{[t]:{}}),this.merge(e[t],r[t])):Object.assign(e,{[t]:r[t]});return this.merge(e,...t)}cloneDeep(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);let r;switch(Object.prototype.toString.call(e)){case"[object Date]":return new Date(e.getTime());case"[object RegExp]":return r=new RegExp(e.source,e.flags),r.lastIndex=e.lastIndex,r;case"[object Map]":return r=new Map,t.set(e,r),e.forEach((e,n)=>{r.set(this.cloneDeep(n,t),this.cloneDeep(e,t))}),r;case"[object Set]":return r=new Set,t.set(e,r),e.forEach(e=>{r.add(this.cloneDeep(e,t))}),r;case"[object Array]":return r=new Array(e.length),t.set(e,r),e.forEach((e,n)=>{r[n]=this.cloneDeep(e,t)}),r;case"[object Object]":return r=Object.create(Object.getPrototypeOf(e)),t.set(e,r),Reflect.ownKeys(e).forEach(n=>{r[n]=this.cloneDeep(e[n],t)}),r;default:return e}}isPlainObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}removeAttributeBy(e,t=e=>void 0===e){for(const r in e)t(e[r])&&delete e[r]}getUrlPath(...e){return e.filter(e=>null!=e&&""!==e).map(e=>String(e)).map(e=>e.replace(/^\/+|\/+$/g,"")).filter(e=>""!==e).join("/").replace(/^(https?):\/(?!\/)/,"$1://")}getStringsOfFlatten(e=[]){return e.flat().filter(e=>null!=e&&""!==e)}getNumberOfNormalize(e,t=0){if("number"==typeof e&&!Number.isNaN(e))return e;try{const r=Number(e);return"number"!=typeof r||Number.isNaN(r)?t:r}catch(e){this.appendError(`448561684561 ${e.message}`)}return t}getStringOfNormalize(e,t="",r=!1){if("string"==typeof e)return r?e.trim():e;try{const n=String(e);return this.isOrEquals(n,"","undefined")?t:r?n.trim():n}catch(e){this.appendError(`448616845453 ${e.message}`)}return t}isValidVersionOfString(e){if(this.isUndefinedNullEmpty(e))return!1;const t=e.split(".");for(const e of t){const t=Number(e);if("number"!=typeof t||Number.isNaN(t)||isNaN(t))return!1}return!0}getSeparatorOfUnique(){return"།།"}getStringOfVersionIncrement(e,t=1){const r=e.split(".").map(e=>Number(e)),n=r.length-1;return r[n]=r[n]+t,r.join(".")}setLocaleOfDate(e="en"){_dayjs.default.locale(e.toLowerCase())}getUuidOfV4(){return(0,_uuid.v4)()}constructor(){(0,_defineProperty2.default)(this,"mapOfIdNTimeoutId",{}),(0,_defineProperty2.default)(this,"compactConsecutive",e=>Array.isArray(e)?e.filter((e,t,r)=>0===t||e!==r[t-1]):[]),(0,_defineProperty2.default)(this,"getEnvironment",()=>this.env),(0,_defineProperty2.default)(this,"isProductionEnvironment",()=>this.isEqual(this.getEnvironment(),"prod")),(0,_defineProperty2.default)(this,"asyncUnitTaskFunction",(e=2e3,t="預設的param",r)=>async(n=this.getRandomHash(10))=>{const i=this.getRandomValue(e,1.2*e);try{const e=i;if(this.appendInfo(`before executed ===> i'm symbol of ${e}, ready to be executed, inner param = ${t}`),await this.syncDelay(i),"function"==typeof r&&r(n))throw Error("force to made error happen");return this.appendInfo(`after executed ===> i'm symbol of ${e}, the task cost ${i} million-seconds ${n?`i hav params ===> ${n}`:""}`),{randomValue:i,symbol:e,param:n}}catch(e){this.appendError(new Error(`asyncUnitTask() catch error ${e.message}`))}finally{this.appendInfo("wow.... finally got you")}}),(0,_defineProperty2.default)(this,"findLowestValue",(e,t="price")=>{const r=e.reduce((e,r)=>r[t]<e[t]?r:e,e[0])[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"findHighestValue",(e,t="price")=>{const r=e.reduce((e,r)=>r[t]>e[t]?r:e,e[0])[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"getStringOfValueRange",(e,t="price",r="$")=>{const n=e.reduce((e,r)=>r[t]<e[t]?r:e,e[0])[t],i=e.reduce((e,r)=>r[t]>e[t]?r:e,e[0])[t];return i===n?`$${n}`:`${r}${n} - ${r}${i}`}),(0,_defineProperty2.default)(this,"getCallersName",()=>{let e;try{throw new Error}catch(t){let r,n=/(\w+)@|at (\w+) \(/g,i=t.stack;n.exec(i),r=n.exec(i),null===!r&&(e=r[1]||r[2])}return String("asyncGeneratorStep").startsWith(e)&&(e=""),e}),(0,_defineProperty2.default)(this,"getRandomValue",(e,t)=>(e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e)),(0,_defineProperty2.default)(this,"insertToArray",(e,t,...r)=>{if(!Array.isArray(e))throw new Error("First argument must be an array.");const n=Math.max(0,Math.min(t+1,e.length));e.splice(n,0,...r)}),(0,_defineProperty2.default)(this,"getStringOfYearADConvertToMinguoYear",(e,t=!1)=>{const r=e-1911;return r>0?`${t?"民國":""}${r}${t?"年":""}`:`${t?"民國":""}前${Math.abs(r)}${t?"年":""}`}),(0,_defineProperty2.default)(this,"merO",(...e)=>this.merge(...e)),(0,_defineProperty2.default)(this,"merO4",(...e)=>{if(0===e.length)return{};const t=e[0],r=e.slice(1),n=structuredClone(t);return this.merge(n,...r)}),(0,_defineProperty2.default)(this,"convertDateToTimestamp",e=>(0,_dayjs.default)(e).valueOf()),(0,_defineProperty2.default)(this,"measureExecutionTime",async(e,...t)=>{const r=Date.now();await e(...t);const n=Date.now()-r,i=_dayjs.default.duration(n),a=Math.floor(i.asHours()),o=i.minutes(),s=i.seconds(),u=i.milliseconds(),l=(n/1e3).toFixed(3);return{second:l,zh_TW:`${a}小時 ${o}分 ${s}.${u.toString().padStart(3,"0")}秒 (合計 ${l} 秒)`}}),(0,_defineProperty2.default)(this,"formatPriceWithCurrency",(e,t)=>{if("number"!=typeof e||"string"!=typeof t)throw new TypeError("Invalid input: number must be a number and locale must be a string.");return new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e)}),(0,_defineProperty2.default)(this,"formatPrice",(e,t)=>{if("number"!=typeof e)throw new TypeError("Invalid input: number must be a number.");return t?new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e):e.toLocaleString("en-US")}),(0,_defineProperty2.default)(this,"generateUniversalKeywords",(e,t=50,r=4)=>{if(!e||"string"!=typeof e)return[];let n=e.trim(),i=[];r=Math.max(2,r),n.length>t&&(console.warn(`警告:輸入字串長度為 ${n.length},已根據 maxLength: ${t} 截斷。`),n=n.substring(0,t)),(n.match(/[a-zA-Z]+/g)||[]).forEach(e=>{if(e.length>=2){i.push(e.toUpperCase()),i.push(e.toLowerCase());const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase();i.push(t)}});const a=(n.match(/\b[0-9]+[a-zA-Z]{1,4}\b|\b[0-9]{1,3}(w|ml|g|oz|k)\b|[\u4e00-\u9fa5a-zA-Z0-9]{1,4}(色|號)[\u4e00-\u9fa5a-zA-Z0-9]{0,2}/gi)||[]).filter(e=>e.length>=2).map(e=>e.toLowerCase());i.push(...a);let o=n.toLowerCase();o=o.replace(/[0-9]+([\u4e00-\u9fa5a-z]{1,4}|[\/\-\~\\])/g," ").replace(/\b[a-z]{1,4}\b/g," ").replace(/\b[0-9]{1,3}\b/g," "),o=o.replace(/[!@#$%^&*()_+={}\[\]:;"'<>,.?\/\\|`~]/g," ").replace(/系列|一組|單色|多款|套組|全套|專用|迷你|頂級|高品質|超閃|奢華|最新|款式|新款|超亮|的|與|和|閃|美甲/g," ").replace(/\s+/g,"").trim();for(let e=2;e<=r;e++)for(let t=0;t<=o.length-e;t++){const r=o.substring(t,t+e);i.push(r)}return i.filter(e=>e.length>=2).filter(e=>e.length>2||!/^[\u4e00-\u9fa5a-z0-9]$/.test(e)).filter((e,t,r)=>r.indexOf(e)===t).sort()}),(0,_defineProperty2.default)(this,"mutateIndexOfArrayItem",(e,t,r=0)=>{if(!Array.isArray(e)||!this.isObject(t))return e;const n=e.findIndex((e,r)=>r>=t&&(t=>this.isEqual(t)(e,r)));if(-1===n)return e;e.splice(n,1);const i=Math.min(Math.max(r,0),e.length);return e.splice(i,0,t),e}),(0,_defineProperty2.default)(this,"getArrayOfModifyObject2Index",(e,t,r=0)=>{if(!Array.isArray(e)||!this.isObject(t))return e;const n=structuredClone(e),i=n.findIndex((e,r)=>r>=t&&(t=>this.isEqual(t)(e,r)));if(-1===i)return e;n.splice(i,1);const a=Math.min(Math.max(r,0),n.length);return n.splice(a,0,t),n}),(0,_defineProperty2.default)(this,"generateLabelValuePairsWithOrigin",(e=[{label:"aa",value:1203},{label:"cc",value:1204},{label:"gg",value:2}],t=["aa","bb"])=>{const r=new Set(e.map(e=>e.value));return Array.from(new Set(t)).map(t=>{const n=e.find(e=>e.label===t);if(n)return{label:t,value:n.value};let i;do{i=Math.floor(999999998*Math.random())+2}while(r.has(i));return r.add(i),{label:t,value:i}})}),(0,_defineProperty2.default)(this,"getItemsOfMarkMatching",(e=[],t=[],r="value",n="belong")=>{const i=new Set(t);return e.map(e=>({...e,[n]:i.has(e[r])}))}),(0,_defineProperty2.default)(this,"generateVariants",(e,t="|",r="-")=>{const n=e.filter(e=>e.length>0);return 0===n.length?[]:1===n.length?n[0].map(e=>({label:e.label,value:e.value})):n.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),[[]]).map(e=>({label:e.map(e=>e.label).join(t),value:e.map(e=>e.value).join(r)}))}),(0,_defineProperty2.default)(this,"renameKeysInArray",(e,...t)=>{const r=Object.fromEntries(t);return e.map(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[r[e]||e,t])))}),(0,_defineProperty2.default)(this,"getArrayOfMergeBySpecificId",(e,t,r="id")=>{if(!Array.isArray(t))return e;const n=t.reduce((e,t)=>(e[t[r]]=t,e),{});return e.map(e=>{const t=e[r],i=n[t];return i?this.merge({},e,i):e})}),(0,_defineProperty2.default)(this,"toPercentageDecimal",e=>{if(null==e)return 1;"string"==typeof e&&(e=e.replace(/%/g,"").trim());const t=Number(e);return Number.isFinite(t)?Number(Math.round(t/100+"e10")+"e-10"):1}),(0,_defineProperty2.default)(this,"getNumberOfMultiplyCeil",(e,t,r=0)=>{const n=Math.pow(10,r);return Math.ceil(e*t*n)/n}),(0,_defineProperty2.default)(this,"generateGoogleCalendarLink",({title:e,startDate:t,startTime:r,endDate:n,endTime:i,location:a,details:o})=>{const s="YYYYMMDDTHHmmss",u=(0,_dayjs.default)(`${t} ${r}`,"YYYY/MM/DD HH:mm").format(s),l=(0,_dayjs.default)(`${n} ${i}`,"YYYY/MM/DD HH:mm").format(s),c=new URLSearchParams;return e&&c.append("text",e),u&&l&&c.append("dates",`${u}/${l}`),o&&c.append("details",o),a&&c.append("location",a),c.append("ctz","Asia/Taipei"),c.append("trp","true"),`https://calendar.google.com/calendar/r/eventedit?${c.toString()}`}),(0,_defineProperty2.default)(this,"generateTimeTreeLink",({title:e,startDate:t,startTime:r,endDate:n,endTime:i,location:a,memo:o})=>{const s=new URLSearchParams;return e&&s.append("title",e),t&&s.append("start_date",t.replace(/\//g,"-")),r&&s.append("start_time",r),n&&s.append("end_date",n.replace(/\//g,"-")),i&&s.append("end_time",i),a&&s.append("location",a),o&&s.append("memo",o),`https://timetreeapp.com/plans/new?${s.toString()}`}),(0,_defineProperty2.default)(this,"generateIcsContent",({title:e,startDate:t,startTime:r,endDate:n,endTime:i,location:a,details:o})=>{const s="Asia/Taipei",u="YYYYMMDDTHHmmss",l=_dayjs.default.tz(`${t} ${r}`,"YYYY/MM/DD HH:mm",s).format(u),c=_dayjs.default.tz(`${n} ${i}`,"YYYY/MM/DD HH:mm",s).format(u),f=(0,_dayjs.default)().utc().format(u)+"Z",d=e=>(e||"").replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n"),p=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//Gemini AI//NONSGML v1.0//EN","BEGIN:VEVENT","UID:"+(Date.now().toString(36)+Math.random().toString(36).substring(2,5)+"@gemini-app.com"),`DTSTAMP:${f}`];return l&&p.push(`DTSTART;TZID=${s}:${l}`),c&&p.push(`DTEND;TZID=${s}:${c}`),e&&p.push(`SUMMARY:${d(e)}`),a&&p.push(`LOCATION:${d(a)}`),o&&p.push(`DESCRIPTION:${d(o)}`),p.push("END:VEVENT","END:VCALENDAR"),p.join("\r\n")}),(0,_defineProperty2.default)(this,"generateAllCalendarLinks",e=>{const t=this.generateGoogleCalendarLink(e),r={...e,memo:e.details},n=this.generateTimeTreeLink(r),i=this.generateIcsContent(e);return{google:t,timeTree:n,ics:`data:text/calendar;charset=utf8,${encodeURIComponent(i)}`}}),(0,_defineProperty2.default)(this,"getArrayOfMappingRef",(e,t)=>e.map(e=>{const r=t.find(t=>t.value===e.value);return r?this.merge({},e,r):e})),(0,_defineProperty2.default)(this,"areAllValuesTheSameOnKeys",(e,...t)=>{if(!e||e.length<=1||0===t.length)return!0;for(const r of t){const t=e[0]?.[r];if(!e.every(e=>e[r]===t))return!1}return!0}),(0,_defineProperty2.default)(this,"getArrayOfUniqBy",(e,t)=>{if(!Array.isArray(e))return console.error("Input must be an array."),[];if("string"!=typeof t||0===t.length)return console.error("Key must be a non-empty string."),[...e];const r=e.reduce((e,r)=>{const n=r[t];return e.has(n)||e.set(n,r),e},new Map);return Array.from(r.values())}),(0,_defineProperty2.default)(this,"execute4Tasks",async(e=[],t)=>{if(!t||"function"!=typeof t)throw new Error("Task function is required and must be a function.");if("AsyncFunction"!==t.constructor.name)throw new Error("Task function must be an asynchronous function (async function) to ensure proper Promise handling.");return 0===e.length?Promise.resolve([]):await Promise.all(e.map(async(r,n)=>t(r,n,e)))}),(0,_defineProperty2.default)(this,"execute4Settled",async(e=[],t)=>{if(!t||"function"!=typeof t)throw new Error("Task function is required and must be a function.");if("AsyncFunction"!==t.constructor.name)throw new Error("Task function must be an asynchronous function (async function) to ensure proper Promise handling.");return 0===e.length?Promise.resolve([]):await Promise.allSettled(e.map((r,n)=>t(r,n,e)))}),(0,_defineProperty2.default)(this,"getReadableOfFileS",(e,t=2)=>{if(0===e)return"0 Bytes";const r=t<0?0:t,n=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,n)).toFixed(r))+" "+["Bytes","KB","MB","GB","TB"][n]}),(0,_defineProperty2.default)(this,"getNumOfFileS",e=>{if(null==e)throw new Error("輸入不能為空");const t=String(e).toUpperCase().trim().match(/^(\d+(\.\d+)?)\s*([A-Z]*)$/);if(!t)throw new Error(`[Invalid Format] 無法解析:'${e}'。請確保格式如 '5MB'`);const r=parseFloat(t[1]),n=t[3],i={"":1,B:1,K:1024,KB:1024,M:1048576,MB:1048576,G:1024**3,GB:1024**3,T:1024**4,TB:1024**4};if(!(n in i))throw new Error(`[Unknown Unit] 未知的容量單位:'${n}'`);return r*i[n]}),(0,_defineProperty2.default)(this,"isCallable",e=>{if("function"==typeof e)return!0;if(e&&"object"==typeof e){const t=Object.prototype.toString.call(e);return!!["[object Function]","[object AsyncFunction]","[object GeneratorFunction]"].includes(t)||"function"==typeof e.call&&"function"==typeof e.apply}return!1}),(0,_defineProperty2.default)(this,"isP",e=>{if(!e)return!1;const t=Object.prototype.toString.call(e);if("[object AsyncFunction]"===t||"function"==typeof e&&"AsyncFunction"===e.constructor?.name)throw new Error("[isPromise Error]: You passed an AsyncFunction instead of a Promise. Did you forget to execute it? (e.g., use 'isPromise(task())' instead of 'isPromise(task)')");return"[object Promise]"===t||e instanceof Promise||("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}),(0,_defineProperty2.default)(this,"exeAsyncT",(e,{thenDo:t,catchDo:r,finallyDo:n,ignore:i=!1}={})=>{if(!this.isP(e))throw console.error("Task validation failed:",e),new Error("[exeAsyncT]: task must be a Promise. Did you forget to call the async function?");return e.then(async e=>{this.isCallable(t)&&await t(e)}).catch(async e=>{if(this.isCallable(r))await r(e);else if(!i)throw console.error("[exeAsyncT Catch]:",e),e}).finally(async()=>{this.isCallable(n)&&await n()})}),this.init(),this.env="dev"}performActionWithoutTimingIssue(e=()=>!0,t=10){this.syncDelay(t).then(()=>e())}executeTimeoutTask(e,t=1e3,r=this.getRandomHash(),...n){const i=this,a=this.mapOfIdNTimeoutId[r];a&&clearTimeout(a);const o=setTimeout(async(...t)=>{await e(),delete i.mapOfIdNTimeoutId[r]},t,...n);i.mapOfIdNTimeoutId[r]=o}printLogMessage(e,t=!1,...r){this.isProductionEnvironment()||(t?this.appendError(e,...r):this.appendInfo(e,...r))}init(){}setEnvironment(e){this.env=e}appendInfo(...e){this.isProductionEnvironment()||console.log(...e)}appendError(...e){this.isProductionEnvironment()||console.error(...e)}async syncDelay(e=2e3){return new Promise(t=>{setTimeout(()=>{t(e)},e)})}startWithRegex(e="",t="."){return new RegExp(`^${t}`,"i").test(e)}accumulate(e,t){let r=e;for(const e of t)void 0!==e&&"function"==typeof e&&(r=e(r));return r}isOrEquals(e,...t){for(const r of t)if(this.isEqual(e,r))return!0;return!1}isAndEquals(...e){for(const t of e)if(!t())return!1;return!0}getStringOfHeadMatch(e,t,r="g"){const n=e.match(new RegExp(t,r));return this.isUndefinedNullEmpty(n)?void 0:n[0]}or(...e){for(const t of e)if("boolean"==typeof t&&t)return!0;return!1}and(...e){for(const t of e)if(!t)return!1;return!0}nth(e,t=-1){return e.at(t%(Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length))}getExistOne(...e){for(const t of e)if(t)return t}getStringOfDropHeadSign(e,t){return this.dropWhile(Array.from(e),e=>this.isEqual(e,t)).join("")}isAndWith(e,t,...r){for(const n of r)if(!t(e,n))return!1;return!0}async syncDelayRandom(e=3e3,t=5e3){const r=this.getRandomValue(e,t);return await this.syncDelay(r),r}has(e,t,r=!1){return Array.isArray(e)?r?e.findIndex(e=>this.isEqual(t,e))>-1:e.indexOf(t)>-1:this.isObject(t)?e[t]:"string"==typeof e&&e.indexOf(t)>-1}containsBy(e,t){return e.findIndex(e=>this.isEqual(e,t))>=0}getStringOfInsideParentheses(e,t="."){return this.getStringOfRule(e,t,"(",")")}getStringOfInsideBrackets(e,t="."){return this.getStringOfRule(e,t,"[","]")}getStringOfInsideBraces(e,t="."){return this.getStringOfRule(e,t,"{","}")}getStringOfRule(e,t=".",r="{",n="}"){return this.getStringOfHeadMatch(e,`(?<=\\${r})${t}+?(?=\\${n})`)}getRandomHash(e=20){const t=_cryptoJs.default.lib.WordArray.random(e);return _cryptoJs.default.enc.Base64.stringify(t).substring(0,e)}getRandomHashV2(e){let t="";for(let r=0;r<e;r++){const e=Math.floor(62*Math.random());t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(e)}return t}getEncryptString(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length);const n=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),i=r?_cryptoJs.default.enc.Base64.parse(`${t}${Array.from({length:22-t.length},(e,t)=>t).join("")}`):t;return _cryptoJs.default.AES.encrypt(e,i,{iv:n}).toString()}getEncryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length);const n=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),i=r?_cryptoJs.default.enc.Base64.parse(`${t}${Array.from({length:22-t.length},(e,t)=>t).join("")}`):t;return _cryptoJs.default.AES.encrypt(JSON.stringify({content:e}),i,{iv:n}).toString()}getDecryptString(e,t=_configerer.configerer.ENCRYPT_KEY){let r=0;if(r=Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length,r>22)throw new _exceptioner.default(8010,r);const n=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const r=_cryptoJs.default.AES.decrypt(e,t,{iv:n}).toString(_cryptoJs.default.enc.Utf8);if(r&&r.trim().length>0)return r}catch(e){}const i=String(t),a=22-i.length,o=Array.from({length:a},(e,t)=>t).join(""),s=_cryptoJs.default.enc.Base64.parse(`${i}${o}`);return _cryptoJs.default.AES.decrypt(e,s,{iv:n}).toString(_cryptoJs.default.enc.Utf8)}getDecryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY){let r=0;if(r=Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length,r>22)throw new _exceptioner.default(8010,r);const n=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const r=_cryptoJs.default.AES.decrypt(e,t,{iv:n}).toString(_cryptoJs.default.enc.Utf8);if(r&&r.trim().length>0)return JSON.parse(r).content}catch(e){}const i=String(t),a=22-i.length,o=Array.from({length:a},(e,t)=>t).join(""),s=_cryptoJs.default.enc.Base64.parse(`${i}${o}`),u=_cryptoJs.default.AES.decrypt(e,s,{iv:n}).toString(_cryptoJs.default.enc.Utf8);return JSON.parse(u).content}getFirebaseFormattedString(e){return String(e).replace(/[\.\#\$\[\]]/g,"-").trim()}formalizeNamesToArray(e){let t=e;for(t=t.split(_configerer.configerer.SEPARATE_TONE_SINGER)[0].trim(),t=String(t).replace(/[, \/#!$%\^&\*;:{}=_`、~()()]/g,"_").trim(),t=this.getFirebaseFormattedString(t),t=String(t).replace(/\_\_+/g,"_").trim();String(t).endsWith("_");)t=t.slice(0,-1).trim();return t.split("_").map(e=>String(e).trim())}getShuffledArrayWithLimitCountHighPerformance(e,t){let r=new Array(t),n=e.length,i=new Array(n);for(t>n&&(t=n);t--;){let a=Math.floor(Math.random()*n);r[t]=e[a in i?i[a]:a],i[a]=--n in i?i[n]:n}return r}getFileNameFromPath(e,t=!1){const r=e.split("/").pop();return t?r:r.split(".").shift()}getFileNameExtensionFromPath(e){return e.split("/").pop()}getPathOfReplaceLastDir(e,t){const r=e.split("/");return r.pop(),r.push(t),r.join("/")}getExtensionFromPath(e){const t=e.split("/").pop().split(".");return(Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length)>1?t.pop():""}getFolderPathOfSpecificPath(e){const t=e.split("/");return t.pop(),t.join("/")}getFolderNameOfFilePath(e){if(this.isValidFilePath(e))return e.split("/").at(-2);throw new _exceptioner.default(9999,`64255615 path is not valid '${e}'`)}isUnderTargetPath(e,t){const r=e.split("/");return this.has(r,t)}getFileDirPath(e,t=!0){return String(e).slice(0,-1).join("/").split("/")+(t?"/":"")}isPathEqualsFileType(e,t){const r=e.split(".").pop();return this.isEqual(r,t)}isValidFilePath(e){const t=this.getExtensionFromPath(e);return(Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length)>0}getArrayOfSize(e,t=1){return e.slice(0,t)}getShuffledArrayWithLimitCount(e,t){return this.getShuffledArrayWithLimitCountHighPerformance(e,t)}getRandomItemOfArray(e,...t){if(!Array.isArray(e))throw new _exceptioner.default(9999,`why are you so stupid, typeof array should be array, not ==> ${e} `);const r=e.filter(e=>!t.includes(e)),n=(Array.isArray(r)?r.length:"object"==typeof r&&null!==r?Object.keys(r).length:String(r).length)>0?r:e,i=this.getShuffledArrayWithLimitCount(n,1);return i.length>0?i[0]:void 0}appendMapOfKeyArray(e,t,...r){this.isUndefinedNullEmpty(e[t])?e[t]=[...r]:e[t].push(...r)}getMergedArrayBy(e=[],t=[],r){if(!r||0===e.length||0===t.length)return[...e];const n=new Map(t.map(e=>[e[r],e]));return e.map(e=>({...n.get(e[r])||{},...e}))}getShuffledItemFromArray(e){return[...e].sort(()=>Math.random()-.5)[0]}getShuffledArray(e){return[...e].sort(()=>Math.random()-.5)}isJson(e){e="string"!=typeof e?JSON.stringify(e):e;try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e}getObjectValue(e){return this.isObject(e)?Object.values(e)[0]:""}getObject(e,t){const r={};return r[e]=t,r}getStringOfCreditCardFormatted(e=0){return e.replace(/\D/g,"").replace(/(\d{4})(?=\d)/g,"$1-").slice(0,19)}getObjectKey(e){return this.isObject(e)?Object.keys(e)[0]:""}printf(){this.appendInfo("i can use in web || react.js")}isKeywordRule(e){if(void 0===e||null==e||"object"==typeof e&&0===Object.keys(e).length||"string"==typeof e&&0===e.length)throw new Error("PARAMS CAN NOT BE EMPTY");if("string"!=typeof e)throw new Error("PARAMS SHOULD BE STRING");if(e.length>20)throw new Error("EXCEED 20 WORDS IS NOT ALLOWED")}getItsKeyByValue(e,t){return Object.keys(e).find(r=>e[r]===t)}startWiths(e,t=[]){for(const r of t)if(String(e).startsWith(r))return!0;return!1}replaceAll(e,t,r){return String(e).replace(new RegExp(`${t}`,"g"),r)}replaceAllWithSets(e="",...t){let r=e;for(const e of t){if(this.isOrEquals(void 0,e.from,e.to))throw(0,_exceptioner.default)(9999,"from or to can't be empty");r=this.replaceAll(r,e.from,e.to)}return r}replaceArrayByContentIndex(e,t,r){const n=e.indexOf(t);e[n]=r}deepFlat(e,t="_"){let r="";const n=[[e,""]];for(;n.length>0;){const[e,i]=n.pop();if(Array.isArray(e))for(let t=e.length-1;t>=0;t--)n.push([e[t],i]);else if(this.isObject(e)){const r=Object.keys(e);for(let a=r.length-1;a>=0;a--){const o=r[a];n.push([e[o],i+o+t])}}else{const n=String(String(e).trim());n.length>0?r+=(r.length>0?t:"")+i+n:i.length>0&&r.length>0?r+=t:i.length>0&&0===r.length&&(r+=i.endsWith(t)?i.slice(0,-t.length):i)}}return r.endsWith(t)&&(r=r.slice(0,-t.length)),r}joinEscapeChar(e){return(e+"").replace(/[\\"']/g,"\\$&").replace(/\u0000/g,"\\0")}getValueWithIntegerType(e){try{const t=parseInt(e);return isNaN(t)?0:t}catch(e){return 0}}getValueOfPriority(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return t}async asyncPool(e,t,r){const n=[],i=[];for(const a of t){const o=Promise.resolve().then(()=>r(a,t));if(n.push(o),e<=t.length){const t=o.then(()=>i.splice(i.indexOf(t),1));i.push(t),i.length>=e&&await Promise.race(i)}}return Promise.all(n)}getAttrValueInSequence(e,...t){for(const r of t)if(!(null==e[r]||"object"==typeof e[r]&&0===Object.keys(e[r]).length||"string"==typeof e[r]&&0===e[r].length))return e[r];return e}toDBC(e){for(var t="",r=0;r<e.length;r++)32===e.charCodeAt(r)&&(t+=String.fromCharCode(12288)),e.charCodeAt(r)<127&&(t+=String.fromCharCode(e.charCodeAt(r)+65248));return t}toCDB(e){for(var t="",r=0;r<e.length;r++)12288!==e.charCodeAt(r)?e.charCodeAt(r)>65280&&e.charCodeAt(r)<65375?t+=String.fromCharCode(e.charCodeAt(r)-65248):t+=String.fromCharCode(e.charCodeAt(r)):t+=String.fromCharCode(e.charCodeAt(r)-12256);return t}findIndexes(e,t){const r=[];let n=!0,i=0;for(;n;)i=e.findIndex((e,r)=>r>=i+1&&t(e,r)),i>-1?r.push(i):n=!1;return r}getSliceArrayOfSpecificIndexes(e,...t){const r=[],n=Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length;for(const i of t){if("number"!=typeof i||Number.isNaN(i))throw new _exceptioner.default(9999,`59941278 index should be number => ${i}, ${e}`);if(i>n-1)throw new _exceptioner.default(9999,`5994123 index=>${i} is not valid, exceed than array size=${n}, ${e}`);r.push(e.at(i))}return r}indexesOf(e,t){const r=[];let n=-1;for(;-1!==(n=e.indexOf(t,n+1));)r.push(n);return r}getIndexOfContext(e,t){return e.findIndex(e=>this.isEqual(e.trim(),t))}toOneLineString(e){return String(e).join("\n").split("")}toSpaceLessString(e){return String(e).split("").map(e=>String(e).trim()).join("")}toNewLineLessString(e){return String(e).split("\n").map(e=>String(e).trim()).join("")}exist(e){return null===!e&&void 0===!e}isUndefinedNullEmpty(e){const t=null==e,r=!("string"!=typeof e&&!Array.isArray(e)&&!this.isObject(e))&&(null==e||"object"==typeof e&&0===Object.keys(e).length||"string"==typeof e&&0===e.length);return t||r}isAndConditionOfUndefinedNullEmpty(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return!1;return!0}isOrConditionOfUndefinedNullEmpty(...e){for(const t of e)if(this.isUndefinedNullEmpty(t))return!0;return!1}getStringHandledByEachLine(e,t=(e,t,r)=>!0,r="\n"){const n=e.split(r);for(const e of n)t(e,n.indexOf(e),n);return n.join(r)}getSegmentsOfEachLine(e){return e.split("\n")}getNormalizedStringEndWith(e,t){e=this.toCDB(e),t=this.toCDB(t);const r=(this.dropRightWhile(e).join(e=>!this.isEqual(e,t)),"");return null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?e:r}getNormalizedStringNotStartWith(e,...t){e=this.toCDB(e);const r=(this.dropWhile(e).join(e=>this.has(t,e)),"");return null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?e:r}getNormalizedStringNotEndWith(e,...t){e=this.toCDB(e);const r=(this.dropRightWhile(e).join(e=>this.has(t,e)),"");return null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?e:r}getTodayTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD")}getCustomFormatOfDatePresent(e,t="YY/MM"){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format(t)}getSimpleDateYYMMDDFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD")}getSimpleTimeYYMMDDHHmmFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD HH:mm")}getECPayCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatV2(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatYMDHM(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm")}getCurrentTimeFormatYMDHMS(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD-HH-mm-ss")}getCurrentMillionSecTimeFormat(e){return(0,_dayjs.default)(e||void 0).format("YYYY-MM-DD-HH-mm-ss-SSS")}isBetweenTimeStamp(e=this.getCurrentTimeStamp(),t,r){return(0,_dayjs.default)(e).isBetween(t,r)}isBeforeTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isBefore(t)}isAfterTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isAfter(t)}formatTimeByLocale(e,t="zh-tw",r="Asia/Taipei",n=!0){const i=t.toLowerCase(),a=n?"YYYY/MM/DD HH:mm":"YYYY/MM/DD hh:mm A";return(0,_dayjs.default)(e).tz(r).locale(i).format(a)}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampByStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeStampFromSpecificFormat(e,t="YYYY/MM/DD HH:mm:ss"){return(0,_dayjs.default)(e,t).valueOf()}getTimeStampFromECPayStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeFormatOfDurationToMillionSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒SSS")}getTimeFormatOfDurationToSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒")}getTimeFormatOfDurationToDay(e){return _dayjs.default.utc(e).format("DD天HH小時mm分鐘ss秒")}getChineseTimeFormat(e){return(0,_dayjs.default)(e).format("LLLL")}getMinuteFormatOfDuration(e){return _dayjs.default.duration(e).asMinutes()}getSecondFormatOfDuration(e){return _dayjs.default.duration(e).asSeconds()}getDayFormatOfDuration(e){return _dayjs.default.duration(e).asDays()}getDurationOfMillionSec(e){const t=(0,_dayjs.default)(),r=(0,_dayjs.default)(e);return Math.abs(t.diff(r))}getCurrentTimeStamp(){return(0,_dayjs.default)().valueOf()}isStringContainInLines(e,t){for(let r of String(e).split("\n"))if(this.has(r,t))return!0;return!1}camel(...e){return this.camelCase(e.join("_"))}upperCamel(...e){return this.upperFirst(this.camel(...e))}array2Obj(e){const t={};for(const r of e)t[`${this.getObjectKey(r)}`]=this.getObjectValue(r);return t}arrayToObjWith(e,t){const r={};for(const n of e){const e=t(n),i=r[e];i&&Array.isArray(i)?i.push(n):r[e]=[n]}return r}isEmptyString(e){return this.isEqual(String(e).trim(),"")}syncSetTimeout(e,t,r=()=>{}){!function n(i){i?r():setTimeout(function(){e(),n(!0)},t)}()}mergeArrayBy(e="id",...t){return Object.values(t.flat().reduce((t,r)=>(r[e]&&(t[r[e]]={...t[r[e]]||{},...r}),t),{}))}getRelativePath(e,t){return this.dropWhile(e,(e,r)=>this.isEqual(e,t[r])).join("")}dropItemsByIndex(e,t,r){this.removeMutate(e,(e,n,i)=>r>=n&&n>=t)}isEven(e){return e%2==0}isOdd(e){return 1===Math.abs(e%2)}getVisibleOrHidden(e){return{visibility:e?"visible":"hidden"}}getNumberOfPercentageToFloat(e){let t=e.replace("%","");return parseFloat(t)/100}getVisibleOrNone(e,t=!1){return{display:e?t?"flex":"inherit":"none"}}stringToInteger(e){switch(e=String(e).toUpperCase()){case"A":return 0;case"B":return 1;case"C":return 2;case"D":return 3;case"E":return 4;case"F":return 5;case"G":return 6;case"H":return 7;case"I":return 8;case"J":return 9;case"K":return 10;case"L":return 11;case"M":return 12;case"N":return 13;default:return 101}}integerToString(e){switch(e){case 0:return"A";case 1:return"B";case 2:return"C";case 3:return"D";case 4:return"E";case 5:return"F";case 6:return"G";case 7:return"H";case 8:return"I";case 9:return"J";case 10:return"K";case 11:return"L";case 12:return"M";case 13:return"N";default:return"Z"}}toObjectMap(e,...t){const r=[];for(const n of e){const e={};for(const r of t){const t=r.func?r.func:e=>e;e[r.to]=this.isUndefinedNullEmpty(r.from)||!this.isObject(n)?t(n):t(n[r.from])}r.push(e)}return r}exeAll(e,...t){if(Array.isArray(e))for(const r of e)for(const e of t)e(r);else{if(!this.isObject(e))throw new _exceptioner.default(9999,"7841212 type can't be array or object");for(const r in e)for(const n of t)e[r]=n(e[r])}return e}getObjectWhile(e,t,r=e=>!0){const n={};for(const i in e)r(e,t,i)&&(n[i]=e[i]);return n}getIntersectionObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0!==t[r])}getDifferenceObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0===t[r])}isObjectContainAndEqual(e,t){let r=!0;for(const n in e)if(void 0===t[n]||t[n]!==e[n]){r=!1;break}return r}getStringOfPop(e,t){if("string"!=typeof e)throw new _exceptioner.default(9999,"445115,type should be string but ==> "+typeof e);const r=e.split(t);return r.pop(),r.join(t)}getStringOfShift(e,t){if("string"!=typeof e)throw new _exceptioner.default(9999,"445116,type should be string but ==> "+typeof e);const r=e.split(t);return r.shift(),r.join(t)}toObjectWithAttributeKey(e,t){const r={};for(const n of e){const e=n[t];if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`48157232 pk can't be empty => '${e}'`);r[e]=n}return r}getObjectOfArraySpecifyAttr(e,t){return this.toObjectWithAttributeKey(e,t)}getStateOfStringContainsSign(e,...t){for(const r of t)if(this.has(e,r))return{exists:!0,sign:r};return{exists:!1}}constraintOfParam(e,t,...r){let n=!1;const i=null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length||this.and(...r.map(e=>e.logic));switch(t){case"array":Array.isArray(e)&&i&&(n=!0);break;case"object":this.isObject(e)&&i&&(n=!0);break;case"string":"string"==typeof e&&i&&(n=!0);break;case"number":"number"==typeof e&&!Number.isNaN(e)&&i&&(n=!0);break;case"other":if(i)return!0}const a=null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?"":`, ${r.map(e=>e.message).join(" | ")}`;if(!1===n)throw new _exceptioner.default(9999,`7474423 type should be ${t} but get '${typeof t}' ${a} `)}getSliceArrayWithMutate(e,t){return this.removeMutate(e,(e,r)=>r<t)}getArrayOfInteraction(e,t){return e.filter(e=>!t.includes(e))}getArrayOfMoveToSpecificIndex(e,t,r){if(!Array.isArray(e))throw new Error("First argument must be an array.");const n=e.length;if(t<0||t>=n||r<0||r>=n)return console.warn("Invalid 'from' or 'to' index for getArrayOfMoveToSpecificIndexOptimized."),[...e];if(t===r)return[...e];const i=[...e],[a]=i.splice(t,1);return i.splice(r,0,a),i}getArrayOfMoveItemToSpecificIndex(e,t,r){const n=e.indexOf(t);return this.getArrayOfMoveToSpecificIndex(e,n,r)}getArrayOfMoveSpecificItemToAside(e,t,r=!0){const n=e.indexOf(t);return this.getArrayOfMoveSpecificIndexToAside(e,n,r)}getArrayOfMoveSpecificIndexToAside(e,t,r=!0){const n=(Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length)-1;return this.getArrayOfMoveToSpecificIndex(e,t,r?n:0)}getECPayCheckMacValue(e,t="5294y06JbISpM5x9",r="v77hoKGq4kWxNNIS"){const n=structuredClone(e);delete n.CheckMacValue;const i=Object.keys(n).sort((e,t)=>e>t?1:-1);let a="";for(const e of i)a+=`${e}=${n[e]}&`;return a=`HashKey=${t}&${a}HashIV=${r}`,a=encodeURIComponent(a).toLowerCase(),a=a.replace(/%20/g,"+").replace(/%2d/g,"-").replace(/%5f/g,"_").replace(/%2e/g,".").replace(/%21/g,"!").replace(/%2a/g,"*").replace(/%28/g,"(").replace(/%29/g,")").replace(/%20/g,"+"),String(_cryptoJs.default.SHA256(a).toUpperCase().toString(_cryptoJs.default.enc.Hex))}getStringOfHandledHtml(e,t=e=>!0){const r=(0,_nodeHtmlParser.parse)(e);return t(r),r.toString()}getSpecifyObjectBy(e,t){for(const r of e)if(t(r))return r}validatePayloadObjectValid(e,t=[],r=this.getRandomHash(10)){if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`${r} content(pay-load) is undefined || empty`);for(const n of t)if("string"==typeof n){if(this.isUndefinedNullEmpty(e[n]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${n}' is not Exist`)}else if(this.isObject(n)){const t=this.getObjectKey(n);if(!this.getObjectValue(n)(e[t]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${t}' is not valid of custom rule`)}return!0}getArrayOfSummarizeBy(e,t,r){const n={};for(const i of e){const e=i[t];void 0!==n[e]?n[e]=n[e]+i[r]:n[e]=i[r]}const i=[];for(const e in n){const a={};a[t]=e,a[r]=n[e],i.push(a)}return i}getHeadStringSplitBy(e,t=this.getSeparatorOfUnique()){return String(e).split(t).shift()}getTailStringSplitBy(e,t=this.getSeparatorOfUnique()){return String(e).split(t).pop()}getSlicesByIndexes(e=[],t=[]){const r=[];return t.forEach((n,i,a)=>{if(this.isEqual(i,t.length-1))return!1;const o=e.slice(n,t[i+1]);r.push(o)}),r}findIndexes(e,t){const r=[];let n=!0,i=0;for(;n;)i=e.findIndex((e,r)=>r>=i+1&&t(e,r)),i>-1?r.push(i):n=!1;return r}isOverSpecificAge(e,t=18){return(0,_dayjs.default)().diff((0,_dayjs.default)(e),"years")>=t}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}isValidTaiwaneseID(e){if(!/^[A-Z][1-2]\d{8}$/.test(e))return!1;const t=[1,9,8,7,6,5,4,3,2,1];let r=10*(e.charCodeAt(0)-65)+parseInt(e.slice(1));for(let n=0;n<t.length;n++)r+=parseInt(e.charAt(n+1))*t[n];return r%10==0}validatePersonalInfoInput(e,t,r,n,i,a=12){return e.length<2?{valid:!1,message:"姓名至少要兩個字"}:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?/^[A-Z][1-2]\d{8}$/.test(r)?/^09\d{8}$/.test(n)?i&&""!==i?(0,_dayjs.default)().diff((0,_dayjs.default)(i),"years")<a?{valid:!1,message:`年齡不得小於 ${a} 歲`}:{valid:!0,message:"格式檢查通過"}:{valid:!1,message:"出生日期格式不正確"}:{valid:!1,message:"手機號碼格式不正確"}:{valid:!1,message:"身分證號碼格式不正確"}:{valid:!1,message:"電子郵件格式不正確"}}getStringOfFormatTimestampRange(e,t){const r=(0,_dayjs.default)(e),n=(0,_dayjs.default)(t),i=e=>e.format("YY/MM/DD");return r.year()===n.year()?`${i(r)} - ${n.format("MM/DD")}`:`${i(r)} - ${i(n)}`}getStringOfCalculateClassTime(e,t,r){const n=(0,_dayjs.default)(e),i=(0,_dayjs.default)(t).diff(n,"days")+1,a=Math.ceil(i/7)*r,o=Math.floor(a/60),s=a%60;return 0===s?`${o}小時`:`${o}小時${s}分鐘`}getNumberOfPeriodMinute(e,t){const r=(0,_dayjs.default)(e).format("HH:mm"),n=(0,_dayjs.default)(t).format("HH:mm"),i=(0,_dayjs.default)(r,"HH:mm"),a=(0,_dayjs.default)(n,"HH:mm");return _dayjs.default.duration(a.diff(i)).asMinutes()}getStringOfWeekTime(e,t,r){if(e<1||e>7)throw new Error("day 必須在 1 到 7 之間");const n=(0,_dayjs.default)(t).format("HH:mm"),i=(0,_dayjs.default)(r).format("HH:mm");return`${{1:"週一",2:"週二",3:"週三",4:"週四",5:"週五",6:"週六",7:"週日"}[e]} ${n}-${i}`}extractNumber(e){if(this.isUndefinedNullEmpty(e))return-1;const t=e.match(/\d+/);return t?Number(t[0]):-1}async fetchElementAttribute(e,t="innerText",r=""){return await e.evaluate(e=>e[t])}async fetchElementAttributes(e,t,r="",...n){const i=await e.$(t);if(!this.isUndefinedNullEmpty(i))try{return await i.evaluate((e,t)=>1===t.length?e[t.shift()]:{...t.map(t=>e[t])},n)}catch(e){return this.appendError(`1581532 ${t} fetch ${JSON.stringify(n)} fail, element is not found`),r}return r}async writeElementAttributes(e,t,...r){const n=await e.$(t);this.isUndefinedNullEmpty(n)?this.appendError(`1231232 ${t} fetch ${JSON.stringify(r)} fail, element is not found`):await n.evaluate((e,t)=>{t.map(t=>{const r=Object.entries(t),n=r[0][0],i=r[0][1];e[n]=i})},r)}getSliceArrayOfUnique(e){if(!Array.isArray(e)||0===e.length)return[];const t=e[0];if(this.isObject(t)&&key){const t=new Map(e.map(e=>[e[key],e]));return Array.from(t.values())}return this.isObject(t)?(console.warn("getSliceArrayOfUniqueOptimized: No key provided for object array, using potentially slow deep comparison."),e.filter((t,r)=>e.findIndex(e=>this.isEqual(t,e))===r)):Array.from(new Set(e))}getUniqueValuesBy(e,t="valueOfType"){return Array.from(new Set(e.map(e=>e[t])))}generateCombinations(...e){const t=e.map(e=>e.key);return e.reduce((e,t)=>(e[t.key]=t,e),{}),[...e.map(e=>e.options.map(t=>({key:e.key,value:t.value,label:t.label}))).reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),[[]]).map(e=>{const t={},r=[],n=[];for(const{key:i,value:a,label:o}of e)t[i]=a,r.push(`${i}_${a}`),n.push(`${o}`);return{trait:t,id:r.join("_"),content:n.join("|")}})].sort((e,r)=>{for(const n of t){if(e.trait[n]>r.trait[n])return 1;if(e.trait[n]<r.trait[n])return-1}return 0})}extractStaticSegments(e,t=[":"]){return e.trim().replace(/^\.?\/*|\/*$/g,"").split("/").filter(e=>e&&!t.some(t=>e.startsWith(t)))}mutateRemoveKeys(e,t){e.forEach((e,r)=>{const n=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)));Object.keys(e).forEach(t=>delete e[t]),Object.assign(e,n)})}removeKeysFromArrayObjects(e,t){return e.map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))))}formatTextWithEllipsis(e,t){if((Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length)<=t)return e;if(t<=6)return"";const r=t-6,n=Math.floor(r/2),i=r-n;return`${e.length>n?e.slice(0,n):e}......${e.slice(-i)}`}getObjectBy(e,t=e=>!0!==e.checked){return Object.fromEntries(Object.entries(e).filter(([e,r])=>t(r)))}mutateBy(e,t=e=>e){const r=[...e].sort((e,r)=>{const n=t(e),i=t(r);if(Array.isArray(n)&&Array.isArray(i)){for(let e=0;e<Math.max(n.length,i.length);e++){if(n[e]>i[e])return 1;if(n[e]<i[e])return-1}return 0}return n>i?1:n<i?-1:0});e.splice(0,e.length,...r)}findUniqueStrings(...e){const t=e.flat().reduce((e,t)=>(e[t]=(e[t]||0)+1,e),{});return Object.entries(t).filter(([e,t])=>1===t).map(([e,t])=>e).filter(Boolean)}getObjectOfSpecifyKey(e,t){const r={};return r[t]=e,r}findUniqueNonReferenceStrings(...e){if(0===e.length)return[];const[t,...r]=e,n=r.flat().reduce((e,t)=>(e[t]=(e[t]||0)+1,e),{});return Object.entries(n).filter(([e,r])=>1===r&&!t.includes(e)).map(([e])=>e).filter(Boolean)}getArrayOfFillMissingValues(e){const t=()=>Array.from({length:8},()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(62*Math.random())]).join(""),r=new Set(e.map(e=>e.value).filter(Boolean));return e.map(e=>{if(null==e.value||"object"==typeof e.value&&0===Object.keys(e.value).length||"string"==typeof e.value&&0===e.value.length){let n;do{n=t()}while(r.has(n));return r.add(n),{...e,value:n}}return e})}isFirestoreAutoId(e){return"string"==typeof e&&20===e.length&&/^[A-Za-z0-9]{20}$/.test(e)}getAutoIdOfFirestore(){return this.getRandomHashV2(20)}getStringOfConvertTimeRange(e){const[t,r]=e.split("|"),n=t.split("(")[0],[i,a]=r.split("-"),o=e=>(0,_dayjs.default)(`${n} ${e}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDHHmm");return`${o(i)}-${o(a)}`}getTSOfSpecificDate(e,{end:t=!1}={}){const r=(0,_dayjs.default)(e.split("(")[0],"YYYY/MM/DD"),n=t?r.endOf("day"):r.startOf("day");return Number(n.format("YYYYMMDDHHmmss"))}isHttpsURL(e){if("string"!=typeof e)return!1;try{const t=decodeURIComponent(e.trim());return"https:"===new URL(t).protocol}catch(e){return!1}}generateUniqueCodeMap(e,t=3){if(t<2)throw new Error("代碼長度最少必須為 2。");const r=new Set,n=new Set;return e.reduce((e,i)=>{const a=this.camelCase(i);if(n.has(a))throw new Error(`23125453 Duplicate key detected: "${a}"`);return n.add(a),e[a]=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",n=e+"0123456789";let i;do{i=e[Math.floor(52*Math.random())];for(let e=1;e<t;e++)i+=n[Math.floor(62*Math.random())]}while(r.has(i));return r.add(i),i})(),e},{})}getPriceOfPercentageBehavior(e,t,r=!1){const n=this.toPercentageDecimal(t);return this.getNumberOfMultiplyCeil(e,r?1-n:1+n)}getFeeOfDiscount(e,t){return Math.round(e*this.toPercentageDecimal(t))}mergeArrayByKey(e){if(!Array.isArray(e))return e;const t={};for(const r of e)if("object"==typeof r&&null!==r&&r.constructor===Object)for(const[e,n]of Object.entries(r))t[e]?this.merge(t[e],n):t[e]=structuredClone(n);return e.length=0,Object.entries(t).forEach(([t,r])=>{e.push({[t]:r})}),e}getObjectOfStartEndDateTime(e){if(!e||"string"!=typeof e)return{startDate:"",startTime:"",endDate:"",endTime:""};const t=e.replace(/|/g," ").replace(/-/g,"-").replace(/\s+/g," ").trim(),r=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})/,n=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/;let i,a,o,s;if(r.test(t))[,i,a,o,s]=t.match(r);else{if(!n.test(t))return{startDate:"",startTime:"",endDate:"",endTime:""};[,i,a,s]=t.match(n),o=i}const u=new Date(`${i} ${a}`);if(new Date(`${o} ${s}`)<u)throw new Error(`End time cannot be earlier than start time: ${e}`);return{startDate:i,startTime:a,endDate:o,endTime:s}}getFilteredHeraPeriods(e,t){return e.filter(e=>e.idOfBooze!==t).uniqBy(e=>`${e.idOfBooze}_${e.idOfVariant}`).value()}checkPeriodConflict(e,t,r=1){const[n,i]=e.content.split("|"),a=n.split(" ")[0],[o,s]=i.split("-"),u=(0,_dayjs.default)(`${a} ${o}`,"YYYY/MM/DD HH:mm"),l=(0,_dayjs.default)(`${a} ${s}`,"YYYY/MM/DD HH:mm"),c=t.filter(e=>{const[t,r]=e.period.split("-"),n=(0,_dayjs.default)(t,"YYYYMMDDHHmm"),i=(0,_dayjs.default)(r,"YYYYMMDDHHmm");return u.isBefore(i)&&l.isAfter(n)});return{conflict:c.length>=r,items:c}}}var _default=exports.default=Utiller;
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_cryptoJs=_interopRequireDefault(require("crypto-js")),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner")),_uuid=require("uuid"),_nodeHtmlParser=require("node-html-parser"),_dayjs=_interopRequireDefault(require("dayjs"));require("dayjs/locale/zh-tw"),require("dayjs/locale/en");var _utc=_interopRequireDefault(require("dayjs/plugin/utc")),_timezone=_interopRequireDefault(require("dayjs/plugin/timezone")),_duration=_interopRequireDefault(require("dayjs/plugin/duration")),_customParseFormat=_interopRequireDefault(require("dayjs/plugin/customParseFormat")),_relativeTime=_interopRequireDefault(require("dayjs/plugin/relativeTime")),_isBetween=_interopRequireDefault(require("dayjs/plugin/isBetween"));_dayjs.default.extend(_utc.default),_dayjs.default.extend(_timezone.default),_dayjs.default.extend(_duration.default),_dayjs.default.extend(_customParseFormat.default),_dayjs.default.extend(_relativeTime.default),_dayjs.default.extend(_isBetween.default),_dayjs.default.locale("zh-tw"),String.format=function(){let e=[];for(let t=0,r=arguments.length;t<r;t++)e.push(arguments[t]);let t=e[0];return e.shift(),t.replace(/\{(\d+)\}/g,function(t,r){return e[r]})};class Utiller{upperFirst(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}camelCase(e){if(!e)return"";const t=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g);return t?t.map((e,t)=>{const r=e.toLowerCase();return 0===t?r:r.charAt(0).toUpperCase()+r.slice(1)}).join(""):""}dropWhile(e,t){if(!Array.isArray(e))return[];let r=0;for(;r<e.length&&t(e[r],r,e);)r++;return e.slice(r)}dropRightWhile(e,t){if(!Array.isArray(e))return[];let r=e.length-1;for(;r>=0&&t(e[r],r,e);)r--;return e.slice(0,r+1)}removeMutate(e,t){if(!Array.isArray(e))return[];const r=[],n=[];e.forEach((i,a)=>{t(i,a,e)&&(r.push(i),n.push(a))});for(let t=n.length-1;t>=0;t--)e.splice(n[t],1);return r}isBoolean(e){return!0===e||!1===e||null!==e&&"object"==typeof e&&"[object Boolean]"===Object.prototype.toString.call(e)}isObject(e){if(null===e)return!1;const t=typeof e;return"object"===t||"function"===t}toString(e){if(null==e)return"";if("string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>this.toString(e)).join(",");if("symbol"==typeof e)return e.toString();const t=`${e}`;return"0"===t&&1/e==-1/0?"-0":t}toNumber(e){if("number"==typeof e)return e;if("symbol"==typeof e)return NaN;if(null!==e&&"object"==typeof e){const t="function"==typeof e.valueOf?e.valueOf():e;e="object"==typeof t?`${t}`:t}return"string"==typeof e&&(e=e.trim()),Number(e)}isString(e){return"string"==typeof e||null!==e&&"object"==typeof e&&"[object String]"===Object.prototype.toString.call(e)}isNumber(e){return"number"==typeof e||null!==e&&"object"==typeof e&&"[object Number]"===Object.prototype.toString.call(e)}isFunction(e){if(!e)return!1;const t=Object.prototype.toString.call(e);return"[object Function]"===t||"[object AsyncFunction]"===t||"[object GeneratorFunction]"===t||"[object Proxy]"===t}isEmpty(e){return null==e||(Array.isArray(e)||"string"==typeof e||"function"==typeof e.splice?0===e.length:e instanceof Map||e instanceof Set?0===e.size:"object"!=typeof e||0===Object.keys(e).length)}isEqual(e,t){if(e===t)return 0!==e||1/e==1/t;if(e!=e&&t!=t)return!0;if(null==e||null==t||"object"!=typeof e&&"object"!=typeof t)return!1;const r=Object.prototype.toString.call(e);if(r!==Object.prototype.toString.call(t))return!1;switch(r){case"[object Date]":case"[object Boolean]":return+e===+t;case"[object Number]":return e===+e?e===+t:e!=e&&t!=t;case"[object String]":case"[object RegExp]":return e===String(t)}if(Array.isArray(e)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!this.isEqual(e[r],t[r]))return!1;return!0}const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++){const i=n[r];if(!Object.prototype.hasOwnProperty.call(t,i)||!this.isEqual(e[i],t[i]))return!1}return!0}merge(e,...t){if(!t.length)return e;const r=t.shift();if(this.isPlainObject(e)&&this.isPlainObject(r))for(const t in r)this.isPlainObject(r[t])?(e[t]||Object.assign(e,{[t]:{}}),this.merge(e[t],r[t])):Object.assign(e,{[t]:r[t]});return this.merge(e,...t)}cloneDeep(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);let r;switch(Object.prototype.toString.call(e)){case"[object Date]":return new Date(e.getTime());case"[object RegExp]":return r=new RegExp(e.source,e.flags),r.lastIndex=e.lastIndex,r;case"[object Map]":return r=new Map,t.set(e,r),e.forEach((e,n)=>{r.set(this.cloneDeep(n,t),this.cloneDeep(e,t))}),r;case"[object Set]":return r=new Set,t.set(e,r),e.forEach(e=>{r.add(this.cloneDeep(e,t))}),r;case"[object Array]":return r=new Array(e.length),t.set(e,r),e.forEach((e,n)=>{r[n]=this.cloneDeep(e,t)}),r;case"[object Object]":return r=Object.create(Object.getPrototypeOf(e)),t.set(e,r),Reflect.ownKeys(e).forEach(n=>{r[n]=this.cloneDeep(e[n],t)}),r;default:return e}}isPlainObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}removeAttributeBy(e,t=e=>void 0===e){for(const r in e)t(e[r])&&delete e[r]}getUrlPath(...e){return e.filter(e=>null!=e&&""!==e).map(e=>String(e).replace(/^\/+|\/+$/g,"")).filter(e=>""!==e).join("/").replace(/^(https?):\/(?!\/)/,"$1://")}getStringsOfFlatten(e=[]){return e.flat().filter(e=>null!=e&&""!==e)}getNumberOfNormalize(e,t=0){if("number"==typeof e&&!Number.isNaN(e))return e;try{const r=Number(e);return"number"!=typeof r||Number.isNaN(r)?t:r}catch(e){this.appendError(`448561684561 ${e.message}`)}return t}getStringOfNormalize(e,t="",r=!1){if(null==e)return t;if("string"==typeof e)return r?e.trim():e;try{const n=String(e);return""===n?t:r?n.trim():n}catch(e){this.appendError(`448616845453 ${e.message}`)}return t}isValidVersionOfString(e){if(this.isUndefinedNullEmpty(e))return!1;const t=e.split(".");for(const e of t){const t=Number(e);if("number"!=typeof t||Number.isNaN(t)||isNaN(t))return!1}return!0}getSeparatorOfUnique(){return"།།"}getStringOfVersionIncrement(e,t=1){const r=e.split(".").map(e=>Number(e)),n=r.length-1;return r[n]=r[n]+t,r.join(".")}setLocaleOfDate(e="en"){_dayjs.default.locale(e.toLowerCase())}getUuidOfV4(){return(0,_uuid.v4)()}constructor(){(0,_defineProperty2.default)(this,"mapOfIdNTimeoutId",{}),(0,_defineProperty2.default)(this,"compactConsecutive",e=>Array.isArray(e)?e.filter((e,t,r)=>0===t||e!==r[t-1]):[]),(0,_defineProperty2.default)(this,"getEnvironment",()=>this.env),(0,_defineProperty2.default)(this,"isProductionEnvironment",()=>this.isEqual(this.getEnvironment(),"prod")),(0,_defineProperty2.default)(this,"asyncUnitTaskFunction",(e=2e3,t="預設的param",r)=>async(n=this.getRandomHash(10))=>{const i=this.getRandomValue(e,1.2*e);try{const e=i;if(this.appendInfo(`before executed ===> i'm symbol of ${e}, ready to be executed, inner param = ${t}`),await this.syncDelay(i),"function"==typeof r&&r(n))throw Error("force to made error happen");return this.appendInfo(`after executed ===> i'm symbol of ${e}, the task cost ${i} million-seconds ${n?`i hav params ===> ${n}`:""}`),{randomValue:i,symbol:e,param:n}}catch(e){this.appendError(new Error(`asyncUnitTask() catch error ${e.message}`))}finally{this.appendInfo("wow.... finally got you")}}),(0,_defineProperty2.default)(this,"findLowestValue",(e,t="price")=>{const r=e.reduce((e,r)=>r[t]<e[t]?r:e,e[0])[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"findHighestValue",(e,t="price")=>{const r=e.reduce((e,r)=>r[t]>e[t]?r:e,e[0])[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"getStringOfValueRange",(e,t="price",r="$")=>{const n=e.reduce((e,r)=>r[t]<e[t]?r:e,e[0])[t],i=e.reduce((e,r)=>r[t]>e[t]?r:e,e[0])[t];return i===n?`$${n}`:`${r}${n} - ${r}${i}`}),(0,_defineProperty2.default)(this,"getCallersName",()=>{let e;try{throw new Error}catch(t){let r,n=/(\w+)@|at (\w+) \(/g,i=t.stack;n.exec(i),r=n.exec(i),null===!r&&(e=r[1]||r[2])}return String("asyncGeneratorStep").startsWith(e)&&(e=""),e}),(0,_defineProperty2.default)(this,"getRandomValue",(e,t)=>(e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e)),(0,_defineProperty2.default)(this,"insertToArray",(e,t,...r)=>{if(!Array.isArray(e))throw new Error("First argument must be an array.");const n=Math.max(0,Math.min(t+1,e.length));e.splice(n,0,...r)}),(0,_defineProperty2.default)(this,"getStringOfYearADConvertToMinguoYear",(e,t=!1)=>{const r=e-1911;return r>0?`${t?"民國":""}${r}${t?"年":""}`:`${t?"民國":""}前${Math.abs(r)}${t?"年":""}`}),(0,_defineProperty2.default)(this,"merO",(...e)=>this.merge(...e)),(0,_defineProperty2.default)(this,"merO4",(...e)=>{if(0===e.length)return{};const t=e[0],r=e.slice(1),n=structuredClone(t);return this.merge(n,...r)}),(0,_defineProperty2.default)(this,"convertDateToTimestamp",e=>(0,_dayjs.default)(e).valueOf()),(0,_defineProperty2.default)(this,"measureExecutionTime",async(e,...t)=>{const r=Date.now();await e(...t);const n=Date.now()-r,i=_dayjs.default.duration(n),a=Math.floor(i.asHours()),o=i.minutes(),s=i.seconds(),u=i.milliseconds(),l=(n/1e3).toFixed(3);return{second:l,zh_TW:`${a}小時 ${o}分 ${s}.${u.toString().padStart(3,"0")}秒 (合計 ${l} 秒)`}}),(0,_defineProperty2.default)(this,"formatPriceWithCurrency",(e,t)=>{if("number"!=typeof e||"string"!=typeof t)throw new TypeError("Invalid input: number must be a number and locale must be a string.");return new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e)}),(0,_defineProperty2.default)(this,"formatPrice",(e,t)=>{if("number"!=typeof e)throw new TypeError("Invalid input: number must be a number.");return t?new Intl.NumberFormat(t,{style:"currency",currency:new Intl.Locale(t).maximize().currency||"USD",minimumFractionDigits:0}).format(e):e.toLocaleString("en-US")}),(0,_defineProperty2.default)(this,"generateUniversalKeywords",(e,t=50,r=4)=>{if(!e||"string"!=typeof e)return[];let n=e.trim(),i=[];r=Math.max(2,r),n.length>t&&(console.warn(`警告:輸入字串長度為 ${n.length},已根據 maxLength: ${t} 截斷。`),n=n.substring(0,t)),(n.match(/[a-zA-Z]+/g)||[]).forEach(e=>{if(e.length>=2){i.push(e.toUpperCase()),i.push(e.toLowerCase());const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase();i.push(t)}});const a=(n.match(/\b[0-9]+[a-zA-Z]{1,4}\b|\b[0-9]{1,3}(w|ml|g|oz|k)\b|[\u4e00-\u9fa5a-zA-Z0-9]{1,4}(色|號)[\u4e00-\u9fa5a-zA-Z0-9]{0,2}/gi)||[]).filter(e=>e.length>=2).map(e=>e.toLowerCase());i.push(...a);let o=n.toLowerCase();o=o.replace(/[0-9]+([\u4e00-\u9fa5a-z]{1,4}|[\/\-\~\\])/g," ").replace(/\b[a-z]{1,4}\b/g," ").replace(/\b[0-9]{1,3}\b/g," "),o=o.replace(/[!@#$%^&*()_+={}\[\]:;"'<>,.?\/\\|`~]/g," ").replace(/系列|一組|單色|多款|套組|全套|專用|迷你|頂級|高品質|超閃|奢華|最新|款式|新款|超亮|的|與|和|閃|美甲/g," ").replace(/\s+/g,"").trim();for(let e=2;e<=r;e++)for(let t=0;t<=o.length-e;t++){const r=o.substring(t,t+e);i.push(r)}return i.filter(e=>e.length>=2).filter(e=>e.length>2||!/^[\u4e00-\u9fa5a-z0-9]$/.test(e)).filter((e,t,r)=>r.indexOf(e)===t).sort()}),(0,_defineProperty2.default)(this,"mutateIndexOfArrayItem",(e,t,r=0)=>{if(!Array.isArray(e)||!this.isObject(t))return e;const n=e.findIndex((e,r)=>r>=t&&(t=>this.isEqual(t)(e,r)));if(-1===n)return e;e.splice(n,1);const i=Math.min(Math.max(r,0),e.length);return e.splice(i,0,t),e}),(0,_defineProperty2.default)(this,"getArrayOfModifyObject2Index",(e,t,r=0)=>{if(!Array.isArray(e)||!this.isObject(t))return e;const n=structuredClone(e),i=n.findIndex((e,r)=>r>=t&&(t=>this.isEqual(t)(e,r)));if(-1===i)return e;n.splice(i,1);const a=Math.min(Math.max(r,0),n.length);return n.splice(a,0,t),n}),(0,_defineProperty2.default)(this,"generateLabelValuePairsWithOrigin",(e=[{label:"aa",value:1203},{label:"cc",value:1204},{label:"gg",value:2}],t=["aa","bb"])=>{const r=new Set(e.map(e=>e.value));return Array.from(new Set(t)).map(t=>{const n=e.find(e=>e.label===t);if(n)return{label:t,value:n.value};let i;do{i=Math.floor(999999998*Math.random())+2}while(r.has(i));return r.add(i),{label:t,value:i}})}),(0,_defineProperty2.default)(this,"getItemsOfMarkMatching",(e=[],t=[],r="value",n="belong")=>{const i=new Set(t);return e.map(e=>({...e,[n]:i.has(e[r])}))}),(0,_defineProperty2.default)(this,"generateVariants",(e,t="|",r="-")=>{const n=e.filter(e=>e.length>0);return 0===n.length?[]:1===n.length?n[0].map(e=>({label:e.label,value:e.value})):n.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),[[]]).map(e=>({label:e.map(e=>e.label).join(t),value:e.map(e=>e.value).join(r)}))}),(0,_defineProperty2.default)(this,"renameKeysInArray",(e,...t)=>{const r=Object.fromEntries(t);return e.map(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[r[e]||e,t])))}),(0,_defineProperty2.default)(this,"getArrayOfMergeBySpecificId",(e,t,r="id")=>{if(!Array.isArray(t))return e;const n=t.reduce((e,t)=>(e[t[r]]=t,e),{});return e.map(e=>{const t=e[r],i=n[t];return i?this.merge({},e,i):e})}),(0,_defineProperty2.default)(this,"toPercentageDecimal",e=>{if(null==e)return 1;"string"==typeof e&&(e=e.replace(/%/g,"").trim());const t=Number(e);return Number.isFinite(t)?Number(Math.round(t/100+"e10")+"e-10"):1}),(0,_defineProperty2.default)(this,"getNumberOfMultiplyCeil",(e,t,r=0)=>{const n=Math.pow(10,r);return Math.ceil(e*t*n)/n}),(0,_defineProperty2.default)(this,"generateGoogleCalendarLink",({title:e,startDate:t,startTime:r,endDate:n,endTime:i,location:a,details:o})=>{const s="YYYYMMDDTHHmmss",u=(0,_dayjs.default)(`${t} ${r}`,"YYYY/MM/DD HH:mm").format(s),l=(0,_dayjs.default)(`${n} ${i}`,"YYYY/MM/DD HH:mm").format(s),c=new URLSearchParams;return e&&c.append("text",e),u&&l&&c.append("dates",`${u}/${l}`),o&&c.append("details",o),a&&c.append("location",a),c.append("ctz","Asia/Taipei"),c.append("trp","true"),`https://calendar.google.com/calendar/r/eventedit?${c.toString()}`}),(0,_defineProperty2.default)(this,"generateTimeTreeLink",({title:e,startDate:t,startTime:r,endDate:n,endTime:i,location:a,memo:o})=>{const s=new URLSearchParams;return e&&s.append("title",e),t&&s.append("start_date",t.replace(/\//g,"-")),r&&s.append("start_time",r),n&&s.append("end_date",n.replace(/\//g,"-")),i&&s.append("end_time",i),a&&s.append("location",a),o&&s.append("memo",o),`https://timetreeapp.com/plans/new?${s.toString()}`}),(0,_defineProperty2.default)(this,"generateIcsContent",({title:e,startDate:t,startTime:r,endDate:n,endTime:i,location:a,details:o})=>{const s="Asia/Taipei",u="YYYYMMDDTHHmmss",l=_dayjs.default.tz(`${t} ${r}`,"YYYY/MM/DD HH:mm",s).format(u),c=_dayjs.default.tz(`${n} ${i}`,"YYYY/MM/DD HH:mm",s).format(u),f=(0,_dayjs.default)().utc().format(u)+"Z",d=e=>(e||"").replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n"),p=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//Gemini AI//NONSGML v1.0//EN","BEGIN:VEVENT","UID:"+(Date.now().toString(36)+Math.random().toString(36).substring(2,5)+"@gemini-app.com"),`DTSTAMP:${f}`];return l&&p.push(`DTSTART;TZID=${s}:${l}`),c&&p.push(`DTEND;TZID=${s}:${c}`),e&&p.push(`SUMMARY:${d(e)}`),a&&p.push(`LOCATION:${d(a)}`),o&&p.push(`DESCRIPTION:${d(o)}`),p.push("END:VEVENT","END:VCALENDAR"),p.join("\r\n")}),(0,_defineProperty2.default)(this,"generateAllCalendarLinks",e=>{const t=this.generateGoogleCalendarLink(e),r={...e,memo:e.details},n=this.generateTimeTreeLink(r),i=this.generateIcsContent(e);return{google:t,timeTree:n,ics:`data:text/calendar;charset=utf8,${encodeURIComponent(i)}`}}),(0,_defineProperty2.default)(this,"getArrayOfMappingRef",(e,t)=>e.map(e=>{const r=t.find(t=>t.value===e.value);return r?this.merge({},e,r):e})),(0,_defineProperty2.default)(this,"areAllValuesTheSameOnKeys",(e,...t)=>{if(!e||e.length<=1||0===t.length)return!0;for(const r of t){const t=e[0]?.[r];if(!e.every(e=>e[r]===t))return!1}return!0}),(0,_defineProperty2.default)(this,"getArrayOfUniqBy",(e,t)=>{if(!Array.isArray(e))return console.error("Input must be an array."),[];if("string"!=typeof t||0===t.length)return console.error("Key must be a non-empty string."),[...e];const r=e.reduce((e,r)=>{const n=r[t];return e.has(n)||e.set(n,r),e},new Map);return Array.from(r.values())}),(0,_defineProperty2.default)(this,"execute4Tasks",async(e=[],t)=>{if(!t||"function"!=typeof t)throw new Error("Task function is required and must be a function.");if("AsyncFunction"!==t.constructor.name)throw new Error("Task function must be an asynchronous function (async function) to ensure proper Promise handling.");return 0===e.length?Promise.resolve([]):await Promise.all(e.map(async(r,n)=>t(r,n,e)))}),(0,_defineProperty2.default)(this,"execute4Settled",async(e=[],t)=>{if(!t||"function"!=typeof t)throw new Error("Task function is required and must be a function.");if("AsyncFunction"!==t.constructor.name)throw new Error("Task function must be an asynchronous function (async function) to ensure proper Promise handling.");return 0===e.length?Promise.resolve([]):await Promise.allSettled(e.map((r,n)=>t(r,n,e)))}),(0,_defineProperty2.default)(this,"getReadableOfFileS",(e,t=2)=>{if(0===e)return"0 Bytes";const r=t<0?0:t,n=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,n)).toFixed(r))+" "+["Bytes","KB","MB","GB","TB"][n]}),(0,_defineProperty2.default)(this,"getNumOfFileS",e=>{if(null==e)throw new Error("輸入不能為空");const t=String(e).toUpperCase().trim().match(/^(\d+(\.\d+)?)\s*([A-Z]*)$/);if(!t)throw new Error(`[Invalid Format] 無法解析:'${e}'。請確保格式如 '5MB'`);const r=parseFloat(t[1]),n=t[3],i={"":1,B:1,K:1024,KB:1024,M:1048576,MB:1048576,G:1024**3,GB:1024**3,T:1024**4,TB:1024**4};if(!(n in i))throw new Error(`[Unknown Unit] 未知的容量單位:'${n}'`);return r*i[n]}),(0,_defineProperty2.default)(this,"isCallable",e=>{if("function"==typeof e)return!0;if(e&&"object"==typeof e){const t=Object.prototype.toString.call(e);return!!["[object Function]","[object AsyncFunction]","[object GeneratorFunction]"].includes(t)||"function"==typeof e.call&&"function"==typeof e.apply}return!1}),(0,_defineProperty2.default)(this,"isP",e=>{if(!e)return!1;const t=Object.prototype.toString.call(e);if("[object AsyncFunction]"===t||"function"==typeof e&&"AsyncFunction"===e.constructor?.name)throw new Error("[isPromise Error]: You passed an AsyncFunction instead of a Promise. Did you forget to execute it? (e.g., use 'isPromise(task())' instead of 'isPromise(task)')");return"[object Promise]"===t||e instanceof Promise||("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}),(0,_defineProperty2.default)(this,"exeAsyncT",(e,{thenDo:t,catchDo:r,finallyDo:n,ignore:i=!1}={})=>{if(!this.isP(e))throw console.error("Task validation failed:",e),new Error("[exeAsyncT]: task must be a Promise. Did you forget to call the async function?");return e.then(async e=>{this.isCallable(t)&&await t(e)}).catch(async e=>{if(this.isCallable(r))await r(e);else if(!i)throw console.error("[exeAsyncT Catch]:",e),e}).finally(async()=>{this.isCallable(n)&&await n()})}),this.init(),this.env="dev"}performActionWithoutTimingIssue(e=()=>!0,t=10){this.syncDelay(t).then(()=>e())}executeTimeoutTask(e,t=1e3,r=this.getRandomHash(),...n){const i=this,a=this.mapOfIdNTimeoutId[r];a&&clearTimeout(a);const o=setTimeout(async(...t)=>{await e(),delete i.mapOfIdNTimeoutId[r]},t,...n);i.mapOfIdNTimeoutId[r]=o}printLogMessage(e,t=!1,...r){this.isProductionEnvironment()||(t?this.appendError(e,...r):this.appendInfo(e,...r))}init(){}setEnvironment(e){this.env=e}appendInfo(...e){this.isProductionEnvironment()||console.log(...e)}appendError(...e){this.isProductionEnvironment()||console.error(...e)}async syncDelay(e=2e3){return new Promise(t=>{setTimeout(()=>{t(e)},e)})}startWithRegex(e="",t="."){return new RegExp(`^${t}`,"i").test(e)}accumulate(e,t){let r=e;for(const e of t)void 0!==e&&"function"==typeof e&&(r=e(r));return r}isOrEquals(e,...t){for(const r of t)if(this.isEqual(e,r))return!0;return!1}isAndEquals(...e){for(const t of e)if(!t())return!1;return!0}getStringOfHeadMatch(e,t,r="g"){const n=e.match(new RegExp(t,r));return this.isUndefinedNullEmpty(n)?void 0:n[0]}or(...e){for(const t of e)if("boolean"==typeof t&&t)return!0;return!1}and(...e){for(const t of e)if(!t)return!1;return!0}nth(e,t=-1){if(null==e)return;const r="object"!=typeof e||Array.isArray(e)?e:Object.values(e);return r.at(t%(r.length||1))}getExistOne(...e){for(const t of e)if(t)return t}getStringOfDropHeadSign(e,t){return this.dropWhile(Array.from(e),e=>this.isEqual(e,t)).join("")}isAndWith(e,t,...r){for(const n of r)if(!t(e,n))return!1;return!0}async syncDelayRandom(e=3e3,t=5e3){const r=this.getRandomValue(e,t);return await this.syncDelay(r),r}has(e,t,r=!1){return Array.isArray(e)?r?e.findIndex(e=>this.isEqual(t,e))>-1:e.indexOf(t)>-1:this.isObject(t)?e[t]:"string"==typeof e&&e.indexOf(t)>-1}containsBy(e,t){return e.findIndex(e=>this.isEqual(e,t))>=0}getStringOfInsideParentheses(e,t="."){return this.getStringOfRule(e,t,"(",")")}getStringOfInsideBrackets(e,t="."){return this.getStringOfRule(e,t,"[","]")}getStringOfInsideBraces(e,t="."){return this.getStringOfRule(e,t,"{","}")}getStringOfRule(e,t=".",r="{",n="}"){return this.getStringOfHeadMatch(e,`(?<=\\${r})${t}+?(?=\\${n})`)}getRandomHash(e=20){const t=_cryptoJs.default.lib.WordArray.random(e);return _cryptoJs.default.enc.Base64.stringify(t).substring(0,e)}getRandomHashV2(e){let t="";for(let r=0;r<e;r++){const e=Math.floor(62*Math.random());t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(e)}return t}getEncryptString(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){const n=String(t);if(n.length>22)throw new _exceptioner.default(8010,n.length);const i=_cryptoJs.default.enc.Utf8.parse("thisIsIVWeNeedToGenerateTheSameValue".substring(0,16)),a=r?n.padEnd(22,"0"):n,o=r?_cryptoJs.default.enc.Utf8.parse(a):a;return _cryptoJs.default.AES.encrypt(e,o,{iv:i}).toString()}getEncryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length);const n=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),i=r?_cryptoJs.default.enc.Base64.parse(`${t}${Array.from({length:22-t.length},(e,t)=>t).join("")}`):t;return _cryptoJs.default.AES.encrypt(JSON.stringify({content:e}),i,{iv:n}).toString()}getDecryptString(e,t=_configerer.configerer.ENCRYPT_KEY){const r=String(t);if(r.length>22)throw new _exceptioner.default(8010,r.length);const n=_cryptoJs.default.enc.Utf8.parse("thisIsIVWeNeedToGenerateTheSameValue".substring(0,16));try{const t=_cryptoJs.default.AES.decrypt(e,r,{iv:n}).toString(_cryptoJs.default.enc.Utf8);if(t&&t.trim().length>0)return t}catch(e){}const i=r.padEnd(22,"0"),a=_cryptoJs.default.enc.Utf8.parse(i);return _cryptoJs.default.AES.decrypt(e,a,{iv:n}).toString(_cryptoJs.default.enc.Utf8)}getDecryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY){let r=0;if(r=Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length,r>22)throw new _exceptioner.default(8010,r);const n=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const r=_cryptoJs.default.AES.decrypt(e,t,{iv:n}).toString(_cryptoJs.default.enc.Utf8);if(r&&r.trim().length>0)return JSON.parse(r).content}catch(e){}const i=String(t),a=22-i.length,o=Array.from({length:a},(e,t)=>t).join(""),s=_cryptoJs.default.enc.Base64.parse(`${i}${o}`),u=_cryptoJs.default.AES.decrypt(e,s,{iv:n}).toString(_cryptoJs.default.enc.Utf8);return JSON.parse(u).content}getFirebaseFormattedString(e){return String(e).replace(/[\.\#\$\[\]]/g,"-").trim()}formalizeNamesToArray(e){let t=String(e||"");return t=t.split(_configerer.configerer.SEPARATE_TONE_SINGER)[0].trim(),t=t.replace(/[, \/#!$%\^&\*;:{}=_`、~()()]/g,"_").trim(),t=this.getFirebaseFormattedString(t),t=t.replace(/_+/g,"_").replace(/^_+|_+$/g,"").trim(),t.split("_").map(e=>String(e).trim()).filter(e=>""!==e)}getShuffledArrayWithLimitCountHighPerformance(e,t){let r=new Array(t),n=e.length,i=new Array(n);for(t>n&&(t=n);t--;){let a=Math.floor(Math.random()*n);r[t]=e[a in i?i[a]:a],i[a]=--n in i?i[n]:n}return r}getFileNameFromPath(e,t=!1){const r=e.split("/").pop();return t?r:r.split(".").shift()}getFileNameExtensionFromPath(e){return e.split("/").pop()}getPathOfReplaceLastDir(e,t){const r=e.split("/");return r.pop(),r.push(t),r.join("/")}getExtensionFromPath(e){if(!e)return"";const t=String(e).split("/").pop().split(".");return t.length>1?t.pop():""}getFolderPathOfSpecificPath(e){const t=e.split("/");return t.pop(),t.join("/")}getFolderNameOfFilePath(e){if(this.isValidFilePath(e))return e.split("/").at(-2);throw new _exceptioner.default(9999,`64255615 path is not valid '${e}'`)}isUnderTargetPath(e,t){const r=e.split("/");return this.has(r,t)}getFileDirPath(e,t=!0){return String(e).split("/").slice(0,-1).join("/")+(t?"/":"")}isPathEqualsFileType(e,t){const r=e.split(".").pop();return this.isEqual(r,t)}isValidFilePath(e){const t=this.getExtensionFromPath(e);return(Array.isArray(t)?t.length:"object"==typeof t&&null!==t?Object.keys(t).length:String(t).length)>0}getArrayOfSize(e,t=1){return e.slice(0,t)}getShuffledArrayWithLimitCount(e,t){return this.getShuffledArrayWithLimitCountHighPerformance(e,t)}getRandomItemOfArray(e,...t){if(!Array.isArray(e))throw new _exceptioner.default(9999,`why are you so stupid, typeof array should be array, not ==> ${e} `);const r=e.filter(e=>!t.includes(e)),n=(Array.isArray(r)?r.length:"object"==typeof r&&null!==r?Object.keys(r).length:String(r).length)>0?r:e,i=this.getShuffledArrayWithLimitCount(n,1);return i.length>0?i[0]:void 0}appendMapOfKeyArray(e,t,...r){this.isUndefinedNullEmpty(e[t])?e[t]=[...r]:e[t].push(...r)}getMergedArrayBy(e=[],t=[],r){if(!r||0===e.length||0===t.length)return[...e];const n=new Map(t.map(e=>[e[r],e]));return e.map(e=>({...n.get(e[r])||{},...e}))}getShuffledItemFromArray(e){return[...e].sort(()=>Math.random()-.5)[0]}getShuffledArray(e){return[...e].sort(()=>Math.random()-.5)}isJson(e){e="string"!=typeof e?JSON.stringify(e):e;try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e}getObjectValue(e){return this.isObject(e)?Object.values(e)[0]:""}getObject(e,t){const r={};return r[e]=t,r}getStringOfCreditCardFormatted(e=0){return e.replace(/\D/g,"").replace(/(\d{4})(?=\d)/g,"$1-").slice(0,19)}getObjectKey(e){return this.isObject(e)?Object.keys(e)[0]:""}printf(){this.appendInfo("i can use in web || react.js")}isKeywordRule(e){if(void 0===e||null==e||"object"==typeof e&&0===Object.keys(e).length||"string"==typeof e&&0===e.length)throw new Error("PARAMS CAN NOT BE EMPTY");if("string"!=typeof e)throw new Error("PARAMS SHOULD BE STRING");if(e.length>20)throw new Error("EXCEED 20 WORDS IS NOT ALLOWED")}getItsKeyByValue(e,t){return Object.keys(e).find(r=>e[r]===t)}startsWith(e,t=[]){return null!=e&&(Array.isArray(t)?t:[t]).some(t=>String(e).startsWith(t))}replaceAll(e,t,r){return null==e?"":String(e).replaceAll(t,r)}replaceAllWithSets(e="",...t){let r=e;for(const e of t){if(this.isOrEquals(void 0,e.from,e.to))throw(0,_exceptioner.default)(9999,"from or to can't be empty");r=this.replaceAll(r,e.from,e.to)}return r}replaceArrayByContentIndex(e,t,r){const n=e.indexOf(t);e[n]=r}deepFlat(e,t="_"){let r="";const n=[[e,""]];for(;n.length>0;){const[e,i]=n.pop();if(Array.isArray(e))for(let t=e.length-1;t>=0;t--)n.push([e[t],i]);else if(this.isObject(e)){const r=Object.keys(e);for(let a=r.length-1;a>=0;a--){const o=r[a];n.push([e[o],i+o+t])}}else{const n=String(String(e).trim());n.length>0?r+=(r.length>0?t:"")+i+n:i.length>0&&r.length>0?r+=t:i.length>0&&0===r.length&&(r+=i.endsWith(t)?i.slice(0,-t.length):i)}}return r.endsWith(t)&&(r=r.slice(0,-t.length)),r}joinEscapeChar(e){return(e+"").replace(/[\\"']/g,"\\$&").replace(/\u0000/g,"\\0")}getValueWithIntegerType(e){try{const t=parseInt(e);return isNaN(t)?0:t}catch(e){return 0}}getValueOfPriority(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return t}async asyncPool(e,t,r){const n=[],i=[];for(const a of t){const o=Promise.resolve().then(()=>r(a,t));if(n.push(o),e<=t.length){const t=o.then(()=>i.splice(i.indexOf(t),1));i.push(t),i.length>=e&&await Promise.race(i)}}return Promise.all(n)}getAttrValueInSequence(e,...t){for(const r of t)if(!(null==e[r]||"object"==typeof e[r]&&0===Object.keys(e[r]).length||"string"==typeof e[r]&&0===e[r].length))return e[r];return e}toDBC(e){for(var t="",r=0;r<e.length;r++)32===e.charCodeAt(r)&&(t+=String.fromCharCode(12288)),e.charCodeAt(r)<127&&(t+=String.fromCharCode(e.charCodeAt(r)+65248));return t}toCDB(e){for(var t="",r=0;r<e.length;r++)12288!==e.charCodeAt(r)?e.charCodeAt(r)>65280&&e.charCodeAt(r)<65375?t+=String.fromCharCode(e.charCodeAt(r)-65248):t+=String.fromCharCode(e.charCodeAt(r)):t+=String.fromCharCode(e.charCodeAt(r)-12256);return t}findIndexes(e,t){const r=[];let n=!0,i=0;for(;n;)i=e.findIndex((e,r)=>r>=i+1&&t(e,r)),i>-1?r.push(i):n=!1;return r}getSliceArrayOfSpecificIndexes(e,...t){const r=[],n=Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length;for(const i of t){if("number"!=typeof i||Number.isNaN(i))throw new _exceptioner.default(9999,`59941278 index should be number => ${i}, ${e}`);if(i>n-1)throw new _exceptioner.default(9999,`5994123 index=>${i} is not valid, exceed than array size=${n}, ${e}`);r.push(e.at(i))}return r}indexesOf(e,t){const r=[];let n=-1;for(;-1!==(n=e.indexOf(t,n+1));)r.push(n);return r}getIndexOfContext(e,t){return e.findIndex(e=>this.isEqual(e.trim(),t))}toOneLineString(e){return null==e?"":String(e).replace(/\n/g,"")}ttoSpaceLessString(e){return null==e?"":String(e).replace(/\s/g,"")}toNewLineLessString(e){return String(e).split("\n").map(e=>String(e).trim()).join("")}exist(e){return null===!e&&void 0===!e}isUndefinedNullEmpty(e){const t=null==e,r=!("string"!=typeof e&&!Array.isArray(e)&&!this.isObject(e))&&(null==e||"object"==typeof e&&0===Object.keys(e).length||"string"==typeof e&&0===e.length);return t||r}isAndConditionOfUndefinedNullEmpty(...e){for(const t of e)if(!this.isUndefinedNullEmpty(t))return!1;return!0}isOrConditionOfUndefinedNullEmpty(...e){for(const t of e)if(this.isUndefinedNullEmpty(t))return!0;return!1}getStringHandledByEachLine(e,t=(e,t,r)=>!0,r="\n"){const n=e.split(r);for(const e of n)t(e,n.indexOf(e),n);return n.join(r)}getSegmentsOfEachLine(e){return e.split("\n")}getNormalizedStringEndWith(e,t){e=this.toCDB(e),t=this.toCDB(t);const r=(this.dropRightWhile(e).join(e=>!this.isEqual(e,t)),"");return null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?e:r}getNormalizedStringNotStartWith(e,...t){e=this.toCDB(e);const r=(this.dropWhile(e).join(e=>this.has(t,e)),"");return null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?e:r}getNormalizedStringNotEndWith(e,...t){e=this.toCDB(e);const r=(this.dropRightWhile(e).join(e=>this.has(t,e)),"");return null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?e:r}getTodayTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD")}getCustomFormatOfDatePresent(e,t="YY/MM"){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format(t)}getSimpleDateYYMMDDFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD")}getSimpleTimeYYMMDDHHmmFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD HH:mm")}getECPayCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatV2(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatYMDHM(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm")}getCurrentTimeFormatYMDHMS(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormat(e){return(0,_dayjs.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD-HH-mm-ss")}getCurrentMillionSecTimeFormat(e){return(0,_dayjs.default)(e||void 0).format("YYYY-MM-DD-HH-mm-ss-SSS")}isBetweenTimeStamp(e=this.getCurrentTimeStamp(),t,r){return(0,_dayjs.default)(e).isBetween(t,r)}isBeforeTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isBefore(t)}isAfterTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_dayjs.default)(e).isAfter(t)}formatTimeByLocale(e,t="zh-tw",r="Asia/Taipei",n=!0){const i=t.toLowerCase(),a=n?"YYYY/MM/DD HH:mm":"YYYY/MM/DD hh:mm A";return(0,_dayjs.default)(e).tz(r).locale(i).format(a)}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=(0,_dayjs.default)().valueOf()){let r=(0,_dayjs.default)(t);return Object.entries(e).forEach(([e,t])=>{0!==t&&(r=r.add(t,e))}),r.valueOf()}getTimeStampByStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeStampFromSpecificFormat(e,t="YYYY/MM/DD HH:mm:ss"){return(0,_dayjs.default)(e,t).valueOf()}getTimeStampFromECPayStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss")}getTimeFormatOfDurationToMillionSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒SSS")}getTimeFormatOfDurationToSecond(e){return _dayjs.default.utc(e).format("HH小時mm分鐘ss秒")}getTimeFormatOfDurationToDay(e){return _dayjs.default.utc(e).format("DD天HH小時mm分鐘ss秒")}getChineseTimeFormat(e){return(0,_dayjs.default)(e).format("LLLL")}getMinuteFormatOfDuration(e){return _dayjs.default.duration(e).asMinutes()}getSecondFormatOfDuration(e){return _dayjs.default.duration(e).asSeconds()}getDayFormatOfDuration(e){return _dayjs.default.duration(e).asDays()}getDurationOfMillionSec(e){const t=(0,_dayjs.default)(),r=(0,_dayjs.default)(e);return Math.abs(t.diff(r))}getCurrentTimeStamp(){return(0,_dayjs.default)().valueOf()}isStringContainInLines(e,t){for(let r of String(e).split("\n"))if(this.has(r,t))return!0;return!1}camel(...e){return this.camelCase(e.join("_"))}upperCamel(...e){return this.upperFirst(this.camel(...e))}array2Obj(e){const t={};for(const r of e)t[`${this.getObjectKey(r)}`]=this.getObjectValue(r);return t}arrayToObjWith(e,t){const r={};for(const n of e){const e=t(n),i=r[e];i&&Array.isArray(i)?i.push(n):r[e]=[n]}return r}isEmptyString(e){return null==e||this.isEqual(String(e).trim(),"")}syncSetTimeout(e,t,r=()=>{}){!function n(i){i?r():setTimeout(function(){e(),n(!0)},t)}()}mergeArrayBy(e="id",...t){return Object.values(t.flat().reduce((t,r)=>(r[e]&&(t[r[e]]={...t[r[e]]||{},...r}),t),{}))}getRelativePath(e,t){return this.dropWhile(e,(e,r)=>this.isEqual(e,t[r])).join("")}dropItemsByIndex(e,t,r){this.removeMutate(e,(e,n,i)=>r>=n&&n>=t)}isEven(e){return e%2==0}isOdd(e){return 1===Math.abs(e%2)}getVisibleOrHidden(e){return{visibility:e?"visible":"hidden"}}getNumberOfPercentageToFloat(e){let t=e.replace("%","");return parseFloat(t)/100}getVisibleOrNone(e,t=!1){return{display:e?t?"flex":"inherit":"none"}}integerToString(e){switch(e){case 0:return"A";case 1:return"B";case 2:return"C";case 3:return"D";case 4:return"E";case 5:return"F";case 6:return"G";case 7:return"H";case 8:return"I";case 9:return"J";case 10:return"K";case 11:return"L";case 12:return"M";case 13:return"N";default:return"Z"}}toObjectMap(e,...t){const r=[];for(const n of e){const e={};for(const r of t){const t=r.func?r.func:e=>e;e[r.to]=this.isUndefinedNullEmpty(r.from)||!this.isObject(n)?t(n):t(n[r.from])}r.push(e)}return r}exeAll(e,...t){if(Array.isArray(e))for(const r of e)for(const e of t)e(r);else{if(!this.isObject(e))throw new _exceptioner.default(9999,"7841212 type can't be array or object");for(const r in e)for(const n of t)e[r]=n(e[r])}return e}getObjectWhile(e,t,r=e=>!0){const n={};for(const i in e)r(e,t,i)&&(n[i]=e[i]);return n}getIntersectionObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0!==t[r])}getDifferenceObject(e,t){return this.getObjectWhile(e,t,(e,t,r)=>void 0===t[r])}isObjectContainAndEqual(e,t){let r=!0;for(const n in e)if(void 0===t[n]||t[n]!==e[n]){r=!1;break}return r}getStringOfPop(e,t){if("string"!=typeof e)throw new _exceptioner.default(9999,"445115,type should be string but ==> "+typeof e);const r=e.split(t);return r.pop(),r.join(t)}getStringOfShift(e,t){if("string"!=typeof e)throw new _exceptioner.default(9999,"445116,type should be string but ==> "+typeof e);const r=e.split(t);return r.shift(),r.join(t)}toObjectWithAttributeKey(e,t){const r={};for(const n of e){const e=n[t];if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`48157232 pk can't be empty => '${e}'`);r[e]=n}return r}getObjectOfArraySpecifyAttr(e,t){return this.toObjectWithAttributeKey(e,t)}getStateOfStringContainsSign(e,...t){for(const r of t)if(this.has(e,r))return{exists:!0,sign:r};return{exists:!1}}constraintOfParam(e,t,...r){let n=!1;const i=null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length||this.and(...r.map(e=>e.logic));switch(t){case"array":Array.isArray(e)&&i&&(n=!0);break;case"object":this.isObject(e)&&i&&(n=!0);break;case"string":"string"==typeof e&&i&&(n=!0);break;case"number":"number"==typeof e&&!Number.isNaN(e)&&i&&(n=!0);break;case"other":if(i)return!0}const a=null==r||"object"==typeof r&&0===Object.keys(r).length||"string"==typeof r&&0===r.length?"":`, ${r.map(e=>e.message).join(" | ")}`;if(!1===n)throw new _exceptioner.default(9999,`7474423 type should be ${t} but get '${typeof t}' ${a} `)}getSliceArrayWithMutate(e,t){return this.removeMutate(e,(e,r)=>r<t)}getArrayOfInteraction(e,t){return e.filter(e=>!t.includes(e))}getArrayOfMoveToSpecificIndex(e,t,r){if(!Array.isArray(e))throw new Error("First argument must be an array.");const n=e.length;if(t<0||t>=n||r<0||r>=n)return console.warn("Invalid 'from' or 'to' index for getArrayOfMoveToSpecificIndexOptimized."),[...e];if(t===r)return[...e];const i=[...e],[a]=i.splice(t,1);return i.splice(r,0,a),i}getArrayOfMoveItemToSpecificIndex(e,t,r){const n=e.indexOf(t);return this.getArrayOfMoveToSpecificIndex(e,n,r)}getArrayOfMoveSpecificItemToAside(e,t,r=!0){const n=e.indexOf(t);return this.getArrayOfMoveSpecificIndexToAside(e,n,r)}getArrayOfMoveSpecificIndexToAside(e,t,r=!0){const n=(Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length)-1;return this.getArrayOfMoveToSpecificIndex(e,t,r?n:0)}getECPayCheckMacValue(e,t="5294y06JbISpM5x9",r="v77hoKGq4kWxNNIS"){const n=structuredClone(e);delete n.CheckMacValue;const i=Object.keys(n).sort((e,t)=>e>t?1:-1);let a="";for(const e of i)a+=`${e}=${n[e]}&`;return a=`HashKey=${t}&${a}HashIV=${r}`,a=encodeURIComponent(a).toLowerCase(),a=a.replace(/%20/g,"+").replace(/%2d/g,"-").replace(/%5f/g,"_").replace(/%2e/g,".").replace(/%21/g,"!").replace(/%2a/g,"*").replace(/%28/g,"(").replace(/%29/g,")").replace(/%20/g,"+"),_cryptoJs.default.SHA256(a).toString(_cryptoJs.default.enc.Hex).toUpperCase()}getStringOfHandledHtml(e,t=e=>!0){const r=(0,_nodeHtmlParser.parse)(e);return t(r),r.toString()}getSpecifyObjectBy(e,t){for(const r of e)if(t(r))return r}validatePayloadObjectValid(e,t=[],r=this.getRandomHash(10)){if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`${r} content(pay-load) is undefined || empty`);for(const n of t)if("string"==typeof n){if(this.isUndefinedNullEmpty(e[n]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${n}' is not Exist`)}else if(this.isObject(n)){const t=this.getObjectKey(n);if(!this.getObjectValue(n)(e[t]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${t}' is not valid of custom rule`)}return!0}getArrayOfSummarizeBy(e,t,r){const n={};for(const i of e){const e=i[t];void 0!==n[e]?n[e]=n[e]+i[r]:n[e]=i[r]}const i=[];for(const e in n){const a={};a[t]=e,a[r]=n[e],i.push(a)}return i}getHeadStringSplitBy(e,t=this.getSeparatorOfUnique()){return String(e).split(t).shift()}getTailStringSplitBy(e,t=this.getSeparatorOfUnique()){return String(e).split(t).pop()}getSlicesByIndexes(e=[],t=[]){const r=[];return t.forEach((n,i,a)=>{if(this.isEqual(i,t.length-1))return!1;const o=e.slice(n,t[i+1]);r.push(o)}),r}findIndexes(e,t){const r=[];let n=!0,i=0;for(;n;)i=e.findIndex((e,r)=>r>=i+1&&t(e,r)),i>-1?r.push(i):n=!1;return r}isOverSpecificAge(e,t=18){return(0,_dayjs.default)().diff((0,_dayjs.default)(e),"years")>=t}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}isValidTaiwaneseID(e){if(!/^[A-Z][1-2]\d{8}$/.test(e))return!1;const t=[1,9,8,7,6,5,4,3,2,1];let r=10*(e.charCodeAt(0)-65)+parseInt(e.slice(1));for(let n=0;n<t.length;n++)r+=parseInt(e.charAt(n+1))*t[n];return r%10==0}validatePersonalInfoInput(e,t,r,n,i,a=12){return e.length<2?{valid:!1,message:"姓名至少要兩個字"}:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?/^[A-Z][1-2]\d{8}$/.test(r)?/^09\d{8}$/.test(n)?i&&""!==i?(0,_dayjs.default)().diff((0,_dayjs.default)(i),"years")<a?{valid:!1,message:`年齡不得小於 ${a} 歲`}:{valid:!0,message:"格式檢查通過"}:{valid:!1,message:"出生日期格式不正確"}:{valid:!1,message:"手機號碼格式不正確"}:{valid:!1,message:"身分證號碼格式不正確"}:{valid:!1,message:"電子郵件格式不正確"}}getStringOfFormatTimestampRange(e,t){const r=(0,_dayjs.default)(e),n=(0,_dayjs.default)(t),i=e=>e.format("YY/MM/DD");return r.year()===n.year()?`${i(r)} - ${n.format("MM/DD")}`:`${i(r)} - ${i(n)}`}getStringOfCalculateClassTime(e,t,r){const n=(0,_dayjs.default)(e),i=(0,_dayjs.default)(t).diff(n,"days")+1,a=Math.ceil(i/7)*r,o=Math.floor(a/60),s=a%60;return 0===s?`${o}小時`:`${o}小時${s}分鐘`}getNumberOfPeriodMinute(e,t){const r=(0,_dayjs.default)(e).format("HH:mm"),n=(0,_dayjs.default)(t).format("HH:mm"),i=(0,_dayjs.default)(r,"HH:mm"),a=(0,_dayjs.default)(n,"HH:mm");return _dayjs.default.duration(a.diff(i)).asMinutes()}getStringOfWeekTime(e,t,r){if(e<1||e>7)throw new Error("day 必須在 1 到 7 之間");const n=(0,_dayjs.default)(t).format("HH:mm"),i=(0,_dayjs.default)(r).format("HH:mm");return`${{1:"週一",2:"週二",3:"週三",4:"週四",5:"週五",6:"週六",7:"週日"}[e]} ${n}-${i}`}extractNumber(e){if(this.isUndefinedNullEmpty(e))return-1;const t=e.match(/\d+/);return t?Number(t[0]):-1}async fetchElementAttribute(e,t="innerText",r=""){return await e.evaluate(e=>e[t])}async fetchElementAttributes(e,t,r="",...n){const i=await e.$(t);if(!this.isUndefinedNullEmpty(i))try{return await i.evaluate((e,t)=>1===t.length?e[t.shift()]:{...t.map(t=>e[t])},n)}catch(e){return this.appendError(`1581532 ${t} fetch ${JSON.stringify(n)} fail, element is not found`),r}return r}async writeElementAttributes(e,t,...r){const n=await e.$(t);this.isUndefinedNullEmpty(n)?this.appendError(`1231232 ${t} fetch ${JSON.stringify(r)} fail, element is not found`):await n.evaluate((e,t)=>{t.map(t=>{const r=Object.entries(t),n=r[0][0],i=r[0][1];e[n]=i})},r)}getSliceArrayOfUnique(e){if(!Array.isArray(e)||0===e.length)return[];const t=e[0];if(this.isObject(t)&&key){const t=new Map(e.map(e=>[e[key],e]));return Array.from(t.values())}return this.isObject(t)?(console.warn("getSliceArrayOfUniqueOptimized: No key provided for object array, using potentially slow deep comparison."),e.filter((t,r)=>e.findIndex(e=>this.isEqual(t,e))===r)):Array.from(new Set(e))}getUniqueValuesBy(e,t="valueOfType"){return Array.from(new Set(e.map(e=>e[t])))}generateCombinations(...e){const t=e.map(e=>e.key);return e.reduce((e,t)=>(e[t.key]=t,e),{}),[...e.map(e=>e.options.map(t=>({key:e.key,value:t.value,label:t.label}))).reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),[[]]).map(e=>{const t={},r=[],n=[];for(const{key:i,value:a,label:o}of e)t[i]=a,r.push(`${i}_${a}`),n.push(`${o}`);return{trait:t,id:r.join("_"),content:n.join("|")}})].sort((e,r)=>{for(const n of t){if(e.trait[n]>r.trait[n])return 1;if(e.trait[n]<r.trait[n])return-1}return 0})}extractStaticSegments(e,t=[":"]){return e.trim().replace(/^\.?\/*|\/*$/g,"").split("/").filter(e=>e&&!t.some(t=>e.startsWith(t)))}mutateRemoveKeys(e,t){e.forEach((e,r)=>{const n=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)));Object.keys(e).forEach(t=>delete e[t]),Object.assign(e,n)})}removeKeysFromArrayObjects(e,t){return e.map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))))}formatTextWithEllipsis(e,t){const r=String(e);if(r.length<=t)return r;if(t<=6)return"";const n=t-6,i=Math.floor(n/2),a=n-i;return`${r.slice(0,i)}......${r.slice(-a)}`}getObjectBy(e,t=e=>!0!==e.checked){return Object.fromEntries(Object.entries(e).filter(([e,r])=>t(r)))}mutateBy(e,t=e=>e){const r=[...e].sort((e,r)=>{const n=t(e),i=t(r);if(Array.isArray(n)&&Array.isArray(i)){for(let e=0;e<Math.max(n.length,i.length);e++){if(n[e]>i[e])return 1;if(n[e]<i[e])return-1}return 0}return n>i?1:n<i?-1:0});e.splice(0,e.length,...r)}findUniqueStrings(...e){const t=e.flat().reduce((e,t)=>(e[t]=(e[t]||0)+1,e),{});return Object.entries(t).filter(([e,t])=>1===t).map(([e,t])=>e).filter(Boolean)}getObjectOfSpecifyKey(e,t){const r={};return r[t]=e,r}findUniqueNonReferenceStrings(...e){if(0===e.length)return[];const[t,...r]=e,n=r.flat().reduce((e,t)=>(e[t]=(e[t]||0)+1,e),{});return Object.entries(n).filter(([e,r])=>1===r&&!t.includes(e)).map(([e])=>e).filter(Boolean)}getArrayOfFillMissingValues(e){const t=()=>Array.from({length:8},()=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.floor(62*Math.random())]).join(""),r=new Set(e.map(e=>e.value).filter(Boolean));return e.map(e=>{if(null==e.value||"object"==typeof e.value&&0===Object.keys(e.value).length||"string"==typeof e.value&&0===e.value.length){let n;do{n=t()}while(r.has(n));return r.add(n),{...e,value:n}}return e})}isFirestoreAutoId(e){return"string"==typeof e&&20===e.length&&/^[A-Za-z0-9]{20}$/.test(e)}getAutoIdOfFirestore(){return this.getRandomHashV2(20)}getStringOfConvertTimeRange(e){const[t,r]=e.split("|"),n=t.split("(")[0],[i,a]=r.split("-"),o=e=>(0,_dayjs.default)(`${n} ${e}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDHHmm");return`${o(i)}-${o(a)}`}getTSOfSpecificDate(e,{end:t=!1}={}){const r=(0,_dayjs.default)(e.split("(")[0],"YYYY/MM/DD"),n=t?r.endOf("day"):r.startOf("day");return Number(n.format("YYYYMMDDHHmmss"))}isHttpsURL(e){if("string"!=typeof e)return!1;try{const t=decodeURIComponent(e.trim());return"https:"===new URL(t).protocol}catch(e){return!1}}generateUniqueCodeMap(e,t=3){if(t<2)throw new Error("代碼長度最少必須為 2。");const r=new Set,n=new Set;return e.reduce((e,i)=>{const a=this.camelCase(i);if(n.has(a))throw new Error(`23125453 Duplicate key detected: "${a}"`);return n.add(a),e[a]=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",n=e+"0123456789";let i;do{i=e[Math.floor(52*Math.random())];for(let e=1;e<t;e++)i+=n[Math.floor(62*Math.random())]}while(r.has(i));return r.add(i),i})(),e},{})}getPriceOfPercentageBehavior(e,t,r=!1){const n=this.toPercentageDecimal(t);return this.getNumberOfMultiplyCeil(e,r?1-n:1+n)}getFeeOfDiscount(e,t){return Math.round(e*this.toPercentageDecimal(t))}mergeArrayByKey(e){if(!Array.isArray(e))return e;const t={};for(const r of e)if("object"==typeof r&&null!==r&&r.constructor===Object)for(const[e,n]of Object.entries(r))t[e]?this.merge(t[e],n):t[e]=structuredClone(n);return e.length=0,Object.entries(t).forEach(([t,r])=>{e.push({[t]:r})}),e}getObjectOfStartEndDateTime(e){if(!e||"string"!=typeof e)return{startDate:"",startTime:"",endDate:"",endTime:""};const t=e.replace(/|/g," ").replace(/-/g,"-").replace(/\s+/g," ").trim(),r=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})/,n=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/;let i,a,o,s;if(r.test(t))[,i,a,o,s]=t.match(r);else{if(!n.test(t))return{startDate:"",startTime:"",endDate:"",endTime:""};[,i,a,s]=t.match(n),o=i}const u=new Date(`${i} ${a}`);if(new Date(`${o} ${s}`)<u)throw new Error(`End time cannot be earlier than start time: ${e}`);return{startDate:i,startTime:a,endDate:o,endTime:s}}getFilteredHeraPeriods(e,t){return e.filter(e=>e.idOfBooze!==t).uniqBy(e=>`${e.idOfBooze}_${e.idOfVariant}`).value()}checkPeriodConflict(e,t,r=1){const[n,i]=e.content.split("|"),a=n.split(" ")[0],[o,s]=i.split("-"),u=(0,_dayjs.default)(`${a} ${o}`,"YYYY/MM/DD HH:mm"),l=(0,_dayjs.default)(`${a} ${s}`,"YYYY/MM/DD HH:mm"),c=t.filter(e=>{const[t,r]=e.period.split("-"),n=(0,_dayjs.default)(t,"YYYYMMDDHHmm"),i=(0,_dayjs.default)(r,"YYYYMMDDHHmm");return u.isBefore(i)&&l.isAfter(n)});return{conflict:c.length>=r,items:c}}}var _default=exports.default=Utiller;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty")),_path2=_interopRequireDefault(require("path")),_fs=_interopRequireDefault(require("fs")),_promises=_interopRequireDefault(require("fs/promises")),_child_process=_interopRequireDefault(require("child_process")),_configerer=require("configerer"),_index=_interopRequireDefault(require("./index")),_index2=_interopRequireDefault(require("../exceptioner/index")),_del=_interopRequireDefault(require("del")),_fsExtra=_interopRequireDefault(require("fs-extra")),_inquirer=_interopRequireDefault(require("inquirer"));class NodeUtiller extends _index.default{constructor(...e){super(...e),(0,_defineProperty2.default)(this,"isPersistIntoLogFile",!0),(0,_defineProperty2.default)(this,"findFilePathByExtension",(e,t=[],...i)=>{const s=new RegExp(`^[^.].+.(${t.join("|")})$`);return this.findFilePathBy(e,e=>s.test(e.fileNameExtension),...i)}),(0,_defineProperty2.default)(this,"executeCommandLine",async e=>{const t=this;return this.appendInfo(`執行腳本 ${e}`),new Promise(function(i,s){_child_process.default.exec(e,(e,n,a)=>{if(t.appendInfo(`${n}`),t.appendInfo(`${a}`),e)return t.appendError(`執行錯誤: ${e}`),void s(e);i(n.trim())})})}),(0,_defineProperty2.default)(this,"getStringOfTerserCommandLine",e=>{const t=[];if(e.compress){const i=[];e.compress.drop_console&&i.push("drop_console=true"),e.compress.drop_debugger&&i.push("drop_debugger=true"),e.compress.passes&&i.push(`passes=${e.compress.passes}`),e.compress.dead_code&&i.push("dead_code=true"),e.compress.unused&&i.push("unused=true"),i.length>0&&t.push(`--compress ${i.join(",")}`)}return!0===e.mangle&&t.push("--mangle"),e.format&&(!0===e.format.beautify&&t.push("--beautify"),!1===e.format.comments?t.push("--no-comments"):"all"===e.format.comments?t.push("--comments all"):e.format.comments&&
|
|
2
2
|
// 例如:comments: /@license|@preserve/
|
|
3
|
-
t.push(`--comments "${e.format.comments}"`),e.format.indent_level&&t.push(`--format indent_level=${e.format.indent_level}`)),t.join(" ")}),(0,_defineProperty2.default)(this,"transformConfigs",e=>e.map(e=>({type:"input",name:e.name,message:e.description||e.name,validate:t=>!(e.require&&!t.trim())||`${e.name} is required!`}))),(0,_defineProperty2.default)(this,"getAnswerFromPromptQ",async(e=[{name:"name",require:!0,description:"type the name"}])=>{const t=this.transformConfigs(e);return _inquirer.default.prompt(t)}),(0,_defineProperty2.default)(this,"interactionByTerminalQ",async e=>{const t="./temp/monitor.json";let i=null;const s=e.map(e=>e.name),n=e.map(e=>e.path);new Set(s).size===s.length&&new Set(n).size===n.length||(console.error("[31m錯誤: 偵測到重複的名稱或路徑,請檢查資料來源。[0m"),process.exit(1));let a=null;try{const e=await _promises.default.readFile(t,"utf-8");a=JSON.parse(e)}catch(e){}const r=e.map(e=>({name:`${e.name} (${e.path})`,value:e})),o=async()=>(await _inquirer.default.prompt([{type:"checkbox",name:"selectedProjects",message:"請選擇要執行的子項 (15秒內未操作將使用上次紀錄):",choices:r,validate:e=>e.length>=1||"請至少選擇一個子項!"}])).selectedProjects;try{const e=await Promise.race([o(),new Promise((e,t)=>{i=setTimeout(()=>{a&&a.selectedProjects?(console.log("\n[33m[Timeout] 15秒未操作,自動載入上一次的選擇項目...[0m"),e(a.selectedProjects)):t(new Error("Timeout: 沒有上次紀錄可供載入"))},15e3)})]);i&&clearTimeout(i);const s={updateTime:Date.now(),selectedProjects:e},n=_path2.default.dirname(t);return await _promises.default.mkdir(n,{recursive:!0}),await _promises.default.writeFile(t,JSON.stringify(s,null,2)),e}catch(e){return i&&clearTimeout(i),console.error("[31m執行失敗:[0m",e?.message??"未知錯誤"),[]}}),(0,_defineProperty2.default)(this,"getPathAfterSpecificFolder",(e,t="src")=>{const i=e.split(_path2.default.sep);for(let e=i.length-1;e>=0;e--)if(i[e]===t)return"/"+i.slice(e+1).join("/");return""}),(0,_defineProperty2.default)(this,"getPathAfterSrc",e=>this.getPathAfterSpecificFolder(e))}findSpecificFolderByPath(e,t){const i=_path2.default.resolve(e).split(_path2.default.sep);for(;i.length;){const e=_path2.default.join(...i,t);if(_fs.default.existsSync(e))return e;i.pop()}return null}printf(){this.appendInfo("i can use in node.js only yo yo")}findFilePathBy(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return[];const s=[],n=_fs.default.readdirSync(e,{withFileTypes:!0});for(const a of n){if(i.includes(a.name))continue;const n=_path2.default.join(e,a.name);if(a.isDirectory())s.push(...this.findFilePathBy(n,t,...i));else if(a.isFile()){const e=this.getPathInfo(n);t(e)&&s.push(e)}}return s}isPathExist(e){return _fs.default.existsSync(e)}renameFile(e,t="fileName"){if(!this.isFile(e)||!t)return void this.appendError(`renameFile 錯誤, path: ${e}, newName: ${t}`);const i=_path2.default.dirname(e),s=_path2.default.extname(e),n=_path2.default.join(i,`${t}${s}`);_fs.default.renameSync(e,n)}getPathInfo(e){const t=_path2.default.resolve(e),i={path:e,absolute:t,isFile:!1,isDirectory:!0,dirName:void 0,folderName:void 0,dirPath:void 0,folderPath:void 0,extension:void 0,fileName:void 0,fileNameExtension:void 0,lastModifiedTime:void 0,name:void 0};if(this.isFile(t)){i.extension=t.split(".").pop();const e=t.split("/").pop().split(".");e.pop(),i.fileName=e.join("."),i.name=e.join("."),i.dirName=t.split("/").at(-2),i.folderName=t.split("/").at(-2),i.isFile=!0,i.dirPath=this.getFolderPathOfSpecificPath(t),i.folderPath=this.getFolderPathOfSpecificPath(t),i.isDirectory=!1,i.fileNameExtension=`${i.fileName}.${i.extension}`,i.lastModifiedTime=this.getFileLastModifiedTime(t)}return this.isDirectory(t)&&(i.dirName=t.split("/").pop()),i}syncExecuteCommandLine(e){const t=this;this.appendInfo(`執行腳本 ${e}`),_child_process.default.exec(`${e}`,(e,i,s)=>{t.appendInfo(`${i}`),t.appendInfo(`${s}`),null!==e&&t.appendError(`exec error: ${e}`)})}persistByPath(e){const t=_path2.default.isAbsolute(e),i=e.split("/").filter(Boolean),s=i[i.length-1],n=""!==_path2.default.extname(s);let a=t?_path2.default.sep:"";for(let e=0;e<i.length;e++)a=_path2.default.join(a,i[e]),_fs.default.existsSync(a)||(e===i.length-1&&n?_fs.default.writeFileSync(a,""):_fs.default.mkdirSync(a,{recursive:!1}));return _path2.default.resolve(e)}async copyFromFolderToDestFolder(e,t,i=!0,s=!1,n=()=>!0){if(!_fs.default.existsSync(e)||!_fs.default.existsSync(e))throw new _index2.default(8009,`${e} or ${t} is not exist!`);this.appendInfo(`正在複製ing ${e}/* => ${t}/* succeed`),_fsExtra.default.copySync(e,t,{preserveTimestamps:s,override:i,filter:n}),this.appendInfo(`複製成功 ${e}/* => ${t}/* succeed`)}cleanAllFiles(e){this.isDirectory(e)&&(this.appendInfo(`準備清除底下的所有 ${e}`),_fsExtra.default.emptyDirSync(e),this.appendInfo(`成功清除底下的所有 ${e}`))}async deleteSelfByPath(e,t){_fs.default.existsSync(e)&&(this.appendInfo(`準備刪掉 ${e},{force:${t}}`),await(0,_del.default)(e,{force:t}),this.appendInfo(`成功刪掉了 ${e}`))}async deleteFileOrFolder(e){this.appendInfo(`刪掉了 ${e}`),await(0,_del.default)(e)}async deleteChildByPath(e,t=!1){const i=this.getChildPathByPath(e);for(const e of i)await this.deleteSelfByPath(e.absolute,t)}getFileCountsOfFolder(e){return this.isDirectory(e)?_fs.default.readdirSync(e).length:-1}async reinstallNodeModules(e="../",...t){const i=[...t,"node_modules","utiller","configerer"],s=this.findFilePathBy(e,e=>this.isEqual(e.fileNameExtension,"package.json"),...i);for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`,s=`${t}package-lock.json`;await(0,_del.default)(s),this.appendInfo(`刪掉了 ${s}`),await(0,_del.default)(i),this.appendInfo(`刪掉了 ${i}`)}for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`;_fs.default.existsSync(i)||await this.executeCommandLine(`cd ${t} && npm install`)}}getNamesOfFolderChild(e){return this.getChildPathByPath(e).filter(e=>e.isDirectory).map(e=>e.dirName)}getChildPathByPath(e){try{return _fs.default.readdirSync(e).map(t=>this.getPathInfo(_path2.default.join(e,t)))}catch(e){throw new _index2.default(8002,e)}}copySingleFile(e,t,i,s=!1){const n=i&&i.trim()?_path2.default.join(t,i):t;if(_fs.default.existsSync(n)&&!s)throw new _index2.default(8006,n);_fs.default.copyFileSync(e,n)}ensureFolderExists(e){const t=_path2.default.resolve(e);_fs.default.existsSync(t)||_fs.default.mkdirSync(t,{recursive:!0})}getNodeEnvVariable(e,t=void 0){const i=process.env[e];return void 0===i?t:i}isDirectory(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isDirectory()}isFile(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isFile()}isImageFile(e){return["svg","png","jpg","jpeg"].includes(e.extension)}async cleanChildFiles(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return!1;const s=this.findFilePathBy(e,t,...i),n=s.filter(e=>!this.isImageFile(e));return await Promise.allSettled(n.map(e=>(this.cleanFileContent(e.absolute),this.appendInfo(`成功 cleanChildFiles() -> '${e.path}'`),Promise.resolve()))),s}cleanFileContent(e){this.syncDeleteFile(e)}async syncWithExistPackage(e="../"){const t=this.findFilePathBy(e,e=>this.isEqual(e.fileNameExtension,"package.json"),"node_modules");for(let e of t)try{this.isEqual(e.dirName,"..")||this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${e.dirName}`,`cd ${this.getFolderPathOfSpecificPath(e.absolute)}`)}catch(e){this.appendInfo(e.message)}}async packageTemplatify(e,t){const i=this.getChildPathByPath(e).map(e=>e.absolute.split("/").pop());if(this.has(i,t))throw new _index2.default(8004,` packageName ===> '${t}'`);const s=`${e}/${t}`;_fs.default.mkdirSync(s),_fs.default.copyFileSync("./template/sample.babel.config.js",`${s}/babel.config.js`),_fs.default.copyFileSync("./template/sample.terser.config.js",`${s}/terser.config.js`);const n=this.getJsonObjByFilePath("./template/sample.package.json");n.name=t,this.writeFileInJSON(`${s}/package.json`,n),this.persistByPath(`${s}/src`);const a=String.format(this.getFileContextInRaw("./template/sample.src.index.js"),t,"明悅",new Date);_fs.default.writeFileSync(`${s}/src/index.js`,a);const r=`${this.findSpecificFolderByPath(s,".idea")}/workspace.xml`;if(this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${t}`,`cd ${_path2.default.resolve(s)}`),_fs.default.existsSync(r)){const e=this.getFileContextInRaw(r).split("\n"),i=e.findIndex(e=>this.has(e,'name="RunManager'));this.insertToArray(e,i,`<configuration name="${t}" \n type="NodeJSConfigurationType" \n path-to-node="$USER_HOME$/.nvm/versions/node/v20.19.5/bin/node" \n node-parameters="--require @babel/register" \n path-to-js-file="${_path2.default.resolve(s)}/src/index.js" \n working-dir="${_path2.default.resolve(s)}" >`," <envs>",' <env name="self_debug" value="true" />',' <env name="is_node" value="true" />'," </envs>",' <method v="2" />',"</configuration>");const n=e.findIndex(e=>this.isEqual(String(e).trim(),"<list>"),i);this.insertToArray(e,n,` <item itemvalue="Node.js.${t}" />`),_fs.default.writeFileSync(r,e.join("\n"))}else this.appendError(`${r} not exist`);await this.executeCommandLine(`cd ${_path2.default.resolve(s)} && npm install`),this.appendInfo(`build ${t} succeed!`)}appendInfo(...e){return this.appendLog(_configerer.configerer.PATH_INFO_LOG,e,!1)}appendError(...e){return this.appendLog(_configerer.configerer.PATH_ERROR_LOG,e,!0)}appendLog(e,t,i=!1){const s=`${this.getCurrentTimeFormat()} ${i?"ERROR":"LOG"} : ${t.map(this.stringifyLog).join(" ,")}`;this.isProductionEnvironment()||(i?console.error(...t):console.log(...t)),this.isPersistIntoLogFile&&this.appendFile(e,s)}stringifyLog(e){return"object"==typeof e?JSON.stringify(e):String(e)}appendFile(e,t,i=!0,s=!1){try{const n=_path2.default.resolve(e);s&&_fs.default.existsSync(n)&&_fs.default.unlinkSync(n),_fs.default.existsSync(n)||this.persistByPath(n);const a=`${i?"\n":""}${t}`;_fs.default.appendFileSync(n,a)}catch(e){throw new _index2.default(8001,e)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=!1}getLogString(e){return e.map(e=>this.isJson(e)||this.isObject(e)||Array.isArray(e)?this.deepFlat(e):e).join(" ,")}async persistJsonFilePrettier(e,t,i=!1){e=_path2.default.resolve(e),this.appendFile(e,JSON.stringify(t),!0,!0),i||await this.prettier(e,120)}printCollectionToFile(e){const t=`./logs/__temp_${this.getCurrentTimeFormat()}.txt`;this.persistByPath("./logs/"),this.appendFile(t,this.deepFlat(e," \n\n, ")),this.appendInfo(`collectionToFile succeed, file name ==> ${t}`)}async readFileContentByPath(e,t={}){return t[e]??(t[e]=await _promises.default.readFile(e,"utf-8"))}singleFileTemplatify(e="./"){const t=this.findFilePathByExtension(e,["js"],"node_modules");for(const e of t){const t=this.getFileContextInRaw(e.absolute).trim();if(null==t||"object"==typeof t&&0===Object.keys(t).length||"string"==typeof t&&0===t.length){this.appendInfo(e.fileName,e.absolute);const t=this.isEqual(e.fileName,"index")?e.dirName:e.fileName;_fs.default.writeFileSync(e.absolute,String.format(this.getFileContextInRaw(".\n /template/s\n ample.src.index.js"),t,"明悅",new Date))}}}isFileEmpty(e){const t=this.getFileContextInRaw(e);return!t||!t.trim()}copySingleFileConservative(e,t){const{absolute:i,lastModifiedTime:s}=t;if(!this.isPathExist(i)||this.isFileEmpty(i))return void this.appendInfo(`${i} is empty file, ignore copy behavior`);const n=_fs.default.existsSync(e);n&&this.getFileLastModifiedTime(e)>s?this.appendInfo(`${e} is the latest, ignore this run`):(n||this.appendInfo(`${e} does not exist, safe to copy.`),this.ensureFolderExists(_path2.default.dirname(e)),this.copySingleFile(i,e,void 0,!0))}syncDeleteFile(e){_fs.default.existsSync(e)&&_fs.default.unlinkSync(e)}getFileContextInJSON(e){try{if(_fs.default.existsSync(e))return JSON.parse(_fs.default.readFileSync(e,"utf-8"))}catch(e){throw new _index2.default(9999,e.message)}return{}}getFileContextInRaw(e){return _fs.default.existsSync(e)?_fs.default.readFileSync(e,"utf-8"):""}writeFileInJSON(e,t){let i=JSON.stringify(t,null,2);_fs.default.writeFileSync(e,i)}async generatePackage(e="./",t=!1,i=!0,...s){let n=this.findFilePathByExtension(e,["json"],"node_modules","release");n=n.filter(e=>this.isEqual(e.fileName,"package")),n=n.map(e=>this.getFolderPathOfSpecificPath(e.absolute));for(const e of n)if(this.isAndEquals(...s.map(t=>()=>!this.has(e,t)))){const s=await this.generateTempFolderWithCleanSrc(e);await this.deleteSelfByPath(_path2.default.join(e,"release"),!0);const n=this.persistByPath(_path2.default.join(e,"release"));await this.executeCommandLine(`cd ${e} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const a=require(_path2.default.join(e,"./terser.config.js")),r=this.getStringOfTerserCommandLine(a);await this.executeCommandLine(`cd ${e}/release/lib && find . -type f -name "*.js" -exec terser {} -o {} ${r} \\;`);const o=_path2.default.join(e,"package.json");try{const s="sample.npm.module.index.js";this.copySingleFile(`/Users/davidtu/cross-achieve/legacy/idea-inventer/utiller/template/${s}`,n,"index.js",!0);const a=`${e}/release/index.js`;await this.executeCommandLine(`terser ${a} -o ${a} ${r}`);const l=_path2.default.join(e,"template");if(this.isPathExist(l)&&await this.copyFromFolderToDestFolder(l,this.persistByPath(_path2.default.join(n,"template"))),t){const{moduleName:e,version:t}=await this.upgradePackageJsonVersion(o);await this.updateVersionOfTemplate(e,t)}this.copySingleFile(o,_path2.default.join(n,"package.json"),void 0,!0),i||!this.isPathExist(_path2.default.join(n,"node_module"))?await this.executeCommandLine(`cd ${n} && yarn install --production`):this.appendInfo("ignore node-module install behavior"),this.appendInfo(`build ${e} succeed`),t&&await this.executeCommandLine(`cd ${n} && npm publish`)}catch(e){throw await this.deleteSelfByPath(n,!0),new _index2.default(9999,`generatePackage 報錯, ${e.message}`)}finally{await this.deleteSelfByPath(s,!0)}}}async updateVersionOfTemplate(e,t){const i=["/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/legacy/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/package.json"];for(const s of i)if(this.isPathExist(s)){console.log("🦴正在修改以下 path的版本 => ",s);let i=!1;const n=this.getJsonObjByFilePath(s);if(n&&n.dependencies&&n.dependencies[e]){n.dependencies[e]=`^${t}`;try{await this.writeJsonThanPrettier(s,n),i=!0}catch(e){i=!1}}i||await this.updateFileOfSpecificLine(s,i=>` "${e}":"^${t}"${String(String(i).trim()).endsWith(",")?",":""}`,t=>String(String(t).trim()).startsWith(`"${e}"`)),console.log("💯成功修改以下 path的版本 => ",s)}await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/legacy/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/legacy/idea-inventer/newp/template/",!0,!0)}async updateFileOfSpecificLine(e,t=e=>"updated",i=e=>!0){const s=this.getFileContextInRaw(e).split("\n"),n=s.findIndex(i);-1!==n&&(s[n]=t(s[n]),this.appendFile(e,s.join("\n"),!0,!0),await this.prettier(e))}async writeJsonThanPrettier(e,t){this.writeFileInJSON(e,t),await this.prettier(e)}async enrichEachPackageJson(e){const t=new Set(["package","admin.package","web.package","functions.package"]),i=this.findFilePathByExtension(e,["json"],"gen","node_modules","release").filter(e=>t.has(e.fileName));if(0!==i.length)for(const{absolute:e}of i){const t=this.getJsonObjByFilePath(e);t.scripts||={},t.scripts.updateConfigerer="npm update configerer --save",await this.writeJsonThanPrettier(e,t)}}insertShellCommand(e=_configerer.configerer.BASE_SHELL_SCRIPT,t,i){if(this.isStringContainInLines(this.getFileContextInRaw(e),t))throw new _index2.default(8007,`alias ${t} is exist`);{const s=`alias ${t}='${i}'`;this.appendFile(e,s)}}getAdminCredential(){return this.getJsonObjByFilePath("/Users/davidtu/cross-achieve/mimi/idea-inventer/firebaser/key/mimi19up-firebase-adminsdk.json")}isEmptyFile(e){if(!this.isPathExist(e))return!0;const t=this.getFileContextInRaw(e);return null==t||("string"==typeof t?0===t.trim().length:"object"==typeof t&&0===Object.keys(t).length)}isEmptyFolder(e){return 0===_fs.default.readdirSync(e).length}async prettier(e,t=250,i=[".mustache"]){const s=_path2.default.resolve(e),n=_path2.default.resolve("."),a=i.find(t=>e.endsWith(t));let r=s,o=!!a;try{if(o){const e=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=new RegExp(`${e}$`);r=s.replace(t,""),await _fs.default.rename(s,r)}await this.executeCommandLine(`cd "${n}" && npx prettier --write "${r}" --print-width ${t} --ignore-unknown`)}catch(t){console.error(`Prettier 執行錯誤 [${e}]:`,t.message)}finally{if(o&&r!==s)try{await _fs.default.access(r),await _fs.default.rename(r,s)}catch(e){}}}getFileLastModifiedTime(e){return _fs.default.statSync(e).mtimeMs}getJsonObjByFilePath(e){return this.appendInfo(`ready to json path:${e}`),JSON.parse(this.getFileContextInRaw(e))}async upgradePackageJsonVersion(e){if(this.isEqual("json",this.getPathInfo(e).extension)){const t=this.getJsonObjByFilePath(e);return t.version=this.getStringOfVersionIncrement(t.version),await this.writeJsonThanPrettier(e,t),{version:t.version,moduleName:t.name}}throw new _index2.default(8020,`path is not package.json, which is ${e}`)}async reWriteJsonAttribute(e,...t){const{extension:i}=this.getPathInfo(e);if("json"!==i)throw new _index2.default(9999,`reWriteJsonAttribute() => path is not package.json, which is ${e}`);const s=t.find(e=>"object"!=typeof e||null===e);if(s)throw new _index2.default(9999,`84451515 attr is not object, which is 'type=${typeof s} => ${s}'`);const n=this.getJsonObjByFilePath(e);for(const e of t)n[this.getObjectKey(e)]=this.getObjectValue(e);return await this.writeJsonThanPrettier(e,n),{version:n.version,moduleName:n.name}}getVersionOfPackageJson(e){return this.getAttributeValueOfJson(e,"version","1.0.0")}getAttributeValueOfJson(e,t,i=void 0){if(this.isEqual("json",this.getPathInfo(e).extension))return this.getJsonObjByFilePath(e)[t]??i;throw new _index2.default(8020,`path is not package.json, which is ${e}`)}getVersionOfJsFile(e){return this.getAttributeValueOfJsFile(e,"version","project without version notice")}getAttributeValueOfJsFile(e,t,i=void 0){if(this.isEqual(this.getExtensionFromPath(e),"js"))return require(_path2.default.resolve(e)).default[t]??i;throw new _index2.default(8020,`path is not js file, which is ${e}`)}async rewriteAttributeOfSourceJs(e,...t){if(!this.isPathExist(e))throw new _index2.default(9999,`4849813 ${e} is not exist`);for(const i of t){if(!this.isObject(i))throw new _index2.default(9999,`4984651 attr is not object, which is 'type=${typeof i} => ${i}'`);const t=this.getObjectKey(i),s=this.getObjectValue(i),n=this.getFileContextInRaw(e).split("\n"),a=n.findIndex(e=>String(String(e).trim()).startsWith(`${t}`));n[a]=` ${t}: '${s}',`,this.appendFile(e,n.join("\n"),!0,!0)}return t}async generateTempFolderWithCleanSrc(e){this.appendInfo("generateTempFolderWithCleanSrc",e);const t=_path2.default.join(e,"src"),i=_path2.default.join(e,"temp");if(!_fs.default.existsSync(t))return i;this.appendInfo("generateTempFolderWithCleanSrc","source",t),this.persistByPath(i),await this.copyFromFolderToDestFolder(t,i);const s=this.findFilePathBy(i);for(const{absolute:e}of s){const t=this.getFileContextInRaw(e).split("\n"),i=t.map(e=>e.trim()),s=i.findIndex(e=>e.startsWith("if (configerer.DEBUG_MODE)")),n=i.lastIndexOf("}");if(s>=0&&n>s){t.splice(s,n-s+1);const i=t.join("\n");this.appendFile(e,i,!0,!0),await this.executeCommandLine(`cd ${_path2.default.dirname(e)} && npx prettier --write "${e}"`)}}return i}rewriteFile2File(e,t){const i=this.getFileContextInRaw(e);if(!i.trim())throw new _index2.default(9999,`${e} 為空,避免覆蓋`);this.appendFile(t,i,!0,!0),this.appendInfo(`rewrite from:${e} => to:${t} 成功`)}getStringOfHeadOfFile(e){return this.isPathExist(e)?this.getFileContextInRaw(e).split("\n")[0]:""}isFileEditSucceed(e){if(!this.isPathExist(e))return!1;const t=this.getPathInfo(e),i=this.getFileContextInRaw(e).trim();if(""===i)return this.appendInfo(`74985465 path ${t.path} is empty file, file would not persist`),!1;try{const e=i.split("\n")[0].match(/const\s+([a-zA-Z_]\w*)\s*=\s*(true|false)\s*;?/);if(!e||(Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length)<3)return!1;if(!0==("true"===e[2]))return!0}catch(e){return this.appendError(`66445411 ${e.message}`),!1}return!1}joinRespectingDot(...e){const t=e[0]?.startsWith("./"),i=e[0]?.startsWith("./")?[e[0].slice(2),...e.slice(1)]:e,s=_path2.default.join(...i);return t&&!_path2.default.isAbsolute(s)?`./${s}`:s}}var _default=exports.default=NodeUtiller;
|
|
3
|
+
t.push(`--comments "${e.format.comments}"`),e.format.indent_level&&t.push(`--format indent_level=${e.format.indent_level}`)),t.join(" ")}),(0,_defineProperty2.default)(this,"transformConfigs",e=>e.map(e=>({type:"input",name:e.name,message:e.description||e.name,validate:t=>!(e.require&&!t.trim())||`${e.name} is required!`}))),(0,_defineProperty2.default)(this,"getAnswerFromPromptQ",async(e=[{name:"name",require:!0,description:"type the name"}])=>{const t=this.transformConfigs(e);return _inquirer.default.prompt(t)}),(0,_defineProperty2.default)(this,"interactionByTerminalQ",async e=>{const t="./temp/monitor.json";let i=null;const s=e.map(e=>e.name),n=e.map(e=>e.path);new Set(s).size===s.length&&new Set(n).size===n.length||(console.error("[31m錯誤: 偵測到重複的名稱或路徑,請檢查資料來源。[0m"),process.exit(1));let a=null;try{const e=await _promises.default.readFile(t,"utf-8");a=JSON.parse(e)}catch(e){}const r=e.map(e=>({name:`${e.name} (${e.path})`,value:e})),o=async()=>(await _inquirer.default.prompt([{type:"checkbox",name:"selectedProjects",message:"請選擇要執行的子項 (15秒內未操作將使用上次紀錄):",choices:r,validate:e=>e.length>=1||"請至少選擇一個子項!"}])).selectedProjects;try{const e=await Promise.race([o(),new Promise((e,t)=>{i=setTimeout(()=>{a&&a.selectedProjects?(console.log("\n[33m[Timeout] 15秒未操作,自動載入上一次的選擇項目...[0m"),e(a.selectedProjects)):t(new Error("Timeout: 沒有上次紀錄可供載入"))},15e3)})]);i&&clearTimeout(i);const s={updateTime:Date.now(),selectedProjects:e},n=_path2.default.dirname(t);return await _promises.default.mkdir(n,{recursive:!0}),await _promises.default.writeFile(t,JSON.stringify(s,null,2)),e}catch(e){return i&&clearTimeout(i),console.error("[31m執行失敗:[0m",e?.message??"未知錯誤"),[]}}),(0,_defineProperty2.default)(this,"getPathAfterSpecificFolder",(e,t="src")=>{const i=e.split(_path2.default.sep);for(let e=i.length-1;e>=0;e--)if(i[e]===t)return"/"+i.slice(e+1).join("/");return""}),(0,_defineProperty2.default)(this,"getPathAfterSrc",e=>this.getPathAfterSpecificFolder(e))}findSpecificFolderByPath(e,t){const i=_path2.default.resolve(e).split(_path2.default.sep);for(;i.length;){const e=_path2.default.join(...i,t);if(_fs.default.existsSync(e))return e;i.pop()}return null}printf(){this.appendInfo("i can use in node.js only yo yo")}findFilePathBy(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return[];const s=[],n=_fs.default.readdirSync(e,{withFileTypes:!0});for(const a of n){if(i.includes(a.name))continue;const n=_path2.default.join(e,a.name);if(a.isDirectory())s.push(...this.findFilePathBy(n,t,...i));else if(a.isFile()){const e=this.getPathInfo(n);t(e)&&s.push(e)}}return s}isPathExist(e){return _fs.default.existsSync(e)}renameFile(e,t="fileName"){if(!this.isFile(e)||!t)return void this.appendError(`renameFile 錯誤, path: ${e}, newName: ${t}`);const i=_path2.default.dirname(e),s=_path2.default.extname(e),n=_path2.default.join(i,`${t}${s}`);_fs.default.renameSync(e,n)}getPathInfo(e){const t=_path2.default.resolve(e),i={path:e,absolute:t,isFile:!1,isDirectory:!0,dirName:void 0,folderName:void 0,dirPath:void 0,folderPath:void 0,extension:void 0,fileName:void 0,fileNameExtension:void 0,lastModifiedTime:void 0,name:void 0};if(this.isFile(t)){i.extension=t.split(".").pop();const e=t.split("/").pop().split(".");e.pop(),i.fileName=e.join("."),i.name=e.join("."),i.dirName=t.split("/").at(-2),i.folderName=t.split("/").at(-2),i.isFile=!0,i.dirPath=this.getFolderPathOfSpecificPath(t),i.folderPath=this.getFolderPathOfSpecificPath(t),i.isDirectory=!1,i.fileNameExtension=`${i.fileName}.${i.extension}`,i.lastModifiedTime=this.getFileLastModifiedTime(t)}return this.isDirectory(t)&&(i.dirName=t.split("/").pop()),i}syncExecuteCommandLine(e){const t=this;this.appendInfo(`執行腳本 ${e}`),_child_process.default.exec(`${e}`,(e,i,s)=>{t.appendInfo(`${i}`),t.appendInfo(`${s}`),null!==e&&t.appendError(`exec error: ${e}`)})}persistByPath(e){const t=_path2.default.isAbsolute(e),i=e.split("/").filter(Boolean),s=i[i.length-1],n=""!==_path2.default.extname(s);let a=t?_path2.default.sep:"";for(let e=0;e<i.length;e++)a=_path2.default.join(a,i[e]),_fs.default.existsSync(a)||(e===i.length-1&&n?_fs.default.writeFileSync(a,""):_fs.default.mkdirSync(a,{recursive:!1}));return _path2.default.resolve(e)}async copyFromFolderToDestFolder(e,t,i=!0,s=!1,n=()=>!0){if(!_fs.default.existsSync(e)||!_fs.default.existsSync(e))throw new _index2.default(8009,`${e} or ${t} is not exist!`);this.appendInfo(`正在複製ing ${e}/* => ${t}/* succeed`),_fsExtra.default.copySync(e,t,{preserveTimestamps:s,override:i,filter:n}),this.appendInfo(`複製成功 ${e}/* => ${t}/* succeed`)}cleanAllFiles(e){this.isDirectory(e)&&(this.appendInfo(`準備清除底下的所有 ${e}`),_fsExtra.default.emptyDirSync(e),this.appendInfo(`成功清除底下的所有 ${e}`))}async deleteSelfByPath(e,t){_fs.default.existsSync(e)&&(this.appendInfo(`準備刪掉 ${e},{force:${t}}`),await(0,_del.default)(e,{force:t}),this.appendInfo(`成功刪掉了 ${e}`))}async deleteFileOrFolder(e){this.appendInfo(`刪掉了 ${e}`),await(0,_del.default)(e)}async deleteChildByPath(e,t=!1){const i=this.getChildPathByPath(e);for(const e of i)await this.deleteSelfByPath(e.absolute,t)}getFileCountsOfFolder(e){return this.isDirectory(e)?_fs.default.readdirSync(e).length:-1}async reinstallNodeModules(e="../",...t){const i=[...t,"node_modules","utiller","configerer"],s=this.findFilePathBy(e,e=>this.isEqual(e.fileNameExtension,"package.json"),...i);for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`,s=`${t}package-lock.json`;await(0,_del.default)(s),this.appendInfo(`刪掉了 ${s}`),await(0,_del.default)(i),this.appendInfo(`刪掉了 ${i}`)}for(const e of s){const t=this.getFileDirPath(e.absolute),i=`${t}node_modules`;_fs.default.existsSync(i)||await this.executeCommandLine(`cd ${t} && npm install`)}}getNamesOfFolderChild(e){return this.getChildPathByPath(e).filter(e=>e.isDirectory).map(e=>e.dirName)}getChildPathByPath(e){try{return _fs.default.readdirSync(e).map(t=>this.getPathInfo(_path2.default.join(e,t)))}catch(e){throw new _index2.default(8002,e)}}copySingleFile(e,t,i,s=!1){let n=i&&i.trim()?_path2.default.join(t,i):t;if(_fs.default.existsSync(n)&&_fs.default.statSync(n).isDirectory()){const t=_path2.default.basename(e);n=_path2.default.join(n,t)}if(_fs.default.existsSync(n)&&!s)throw new _index2.default(8006,n);const a=_path2.default.dirname(n);_fs.default.existsSync(a)||_fs.default.mkdirSync(a,{recursive:!0}),_fs.default.copyFileSync(e,n)}ensureFolderExists(e){const t=_path2.default.resolve(e);_fs.default.existsSync(t)||_fs.default.mkdirSync(t,{recursive:!0})}getNodeEnvVariable(e,t=void 0){const i=process.env[e];return void 0===i?t:i}isDirectory(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isDirectory()}isFile(e){return!!this.isPathExist(e)&&_fs.default.lstatSync(e).isFile()}isImageFile(e){return["svg","png","jpg","jpeg"].includes(e.extension)}async cleanChildFiles(e,t=()=>!0,...i){if(!_fs.default.existsSync(e))return!1;const s=this.findFilePathBy(e,t,...i),n=s.filter(e=>!this.isImageFile(e));return await Promise.allSettled(n.map(e=>(this.cleanFileContent(e.absolute),this.appendInfo(`成功 cleanChildFiles() -> '${e.path}'`),Promise.resolve()))),s}cleanFileContent(e){this.syncDeleteFile(e)}async syncWithExistPackage(e="../"){const t=this.findFilePathBy(e,e=>this.isEqual(e.fileNameExtension,"package.json"),"node_modules");for(let e of t)try{this.isEqual(e.dirName,"..")||this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${e.dirName}`,`cd ${this.getFolderPathOfSpecificPath(e.absolute)}`)}catch(e){this.appendInfo(e.message)}}async packageTemplatify(e,t){const i=this.getChildPathByPath(e).map(e=>e.absolute.split("/").pop());if(this.has(i,t))throw new _index2.default(8004,` packageName ===> '${t}'`);const s=`${e}/${t}`;_fs.default.mkdirSync(s),_fs.default.copyFileSync("./template/sample.babel.config.js",`${s}/babel.config.js`),_fs.default.copyFileSync("./template/sample.terser.config.js",`${s}/terser.config.js`);const n=this.getJsonObjByFilePath("./template/sample.package.json");n.name=t,this.writeFileInJSON(`${s}/package.json`,n),this.persistByPath(`${s}/src`);const a=String.format(this.getFileContextInRaw("./template/sample.src.index.js"),t,"明悅",new Date);_fs.default.writeFileSync(`${s}/src/index.js`,a);const r=`${this.findSpecificFolderByPath(s,".idea")}/workspace.xml`;if(this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${t}`,`cd ${_path2.default.resolve(s)}`),_fs.default.existsSync(r)){const e=this.getFileContextInRaw(r).split("\n"),i=e.findIndex(e=>this.has(e,'name="RunManager'));this.insertToArray(e,i,`<configuration name="${t}" \n type="NodeJSConfigurationType" \n path-to-node="$USER_HOME$/.nvm/versions/node/v20.19.5/bin/node" \n node-parameters="--require @babel/register" \n path-to-js-file="${_path2.default.resolve(s)}/src/index.js" \n working-dir="${_path2.default.resolve(s)}" >`," <envs>",' <env name="self_debug" value="true" />',' <env name="is_node" value="true" />'," </envs>",' <method v="2" />',"</configuration>");const n=e.findIndex(e=>this.isEqual(String(e).trim(),"<list>"),i);this.insertToArray(e,n,` <item itemvalue="Node.js.${t}" />`),_fs.default.writeFileSync(r,e.join("\n"))}else this.appendError(`${r} not exist`);await this.executeCommandLine(`cd ${_path2.default.resolve(s)} && npm install`),this.appendInfo(`build ${t} succeed!`)}appendInfo(...e){return this.appendLog(_configerer.configerer.PATH_INFO_LOG,e,!1)}appendError(...e){return this.appendLog(_configerer.configerer.PATH_ERROR_LOG,e,!0)}appendLog(e,t,i=!1){const s=`${this.getCurrentTimeFormat()} ${i?"ERROR":"LOG"} : ${t.map(this.stringifyLog).join(" ,")}`;this.isProductionEnvironment()||(i?console.error(...t):console.log(...t)),this.isPersistIntoLogFile&&this.appendFile(e,s)}stringifyLog(e){return"object"==typeof e?JSON.stringify(e):String(e)}appendFile(e,t,i=!0,s=!1){try{const n=_path2.default.resolve(e);s&&_fs.default.existsSync(n)&&_fs.default.unlinkSync(n),_fs.default.existsSync(n)||this.persistByPath(n);const a=`${i?"\n":""}${t}`;_fs.default.appendFileSync(n,a)}catch(e){throw new _index2.default(8001,e)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=!1}getLogString(e){return e.map(e=>this.isJson(e)||this.isObject(e)||Array.isArray(e)?this.deepFlat(e):e).join(" ,")}async persistJsonFilePrettier(e,t,i=!1){e=_path2.default.resolve(e),this.appendFile(e,JSON.stringify(t),!0,!0),i||await this.prettier(e,120)}printCollectionToFile(e){const t=`./logs/__temp_${this.getCurrentTimeFormat()}.txt`;this.persistByPath("./logs/"),this.appendFile(t,this.deepFlat(e," \n\n, ")),this.appendInfo(`collectionToFile succeed, file name ==> ${t}`)}async readFileContentByPath(e,t={}){return t[e]??(t[e]=await _promises.default.readFile(e,"utf-8"))}singleFileTemplatify(e="./"){const t=this.findFilePathByExtension(e,["js"],"node_modules");for(const e of t){const t=this.getFileContextInRaw(e.absolute).trim();if(null==t||"object"==typeof t&&0===Object.keys(t).length||"string"==typeof t&&0===t.length){this.appendInfo(e.fileName,e.absolute);const t=this.isEqual(e.fileName,"index")?e.dirName:e.fileName;_fs.default.writeFileSync(e.absolute,String.format(this.getFileContextInRaw(".\n /template/s\n ample.src.index.js"),t,"明悅",new Date))}}}isFileEmpty(e){const t=this.getFileContextInRaw(e);return!t||!t.trim()}copySingleFileConservative(e,t){const{absolute:i,lastModifiedTime:s}=t;if(!this.isPathExist(i)||this.isFileEmpty(i))return void this.appendInfo(`${i} is empty file, ignore copy behavior`);const n=_fs.default.existsSync(e);n&&this.getFileLastModifiedTime(e)>s?this.appendInfo(`${e} is the latest, ignore this run`):(n||this.appendInfo(`${e} does not exist, safe to copy.`),this.ensureFolderExists(_path2.default.dirname(e)),this.copySingleFile(i,e,void 0,!0))}syncDeleteFile(e){_fs.default.existsSync(e)&&_fs.default.unlinkSync(e)}getFileContextInJSON(e){try{if(_fs.default.existsSync(e))return JSON.parse(_fs.default.readFileSync(e,"utf-8"))}catch(e){throw new _index2.default(9999,e.message)}return{}}getFileContextInRaw(e){return _fs.default.existsSync(e)?_fs.default.readFileSync(e,"utf-8"):""}writeFileInJSON(e,t){let i=JSON.stringify(t,null,2);_fs.default.writeFileSync(e,i)}async generatePackage(e="./",t=!1,i=!0,...s){let n=this.findFilePathByExtension(e,["json"],"node_modules","release");n=n.filter(e=>this.isEqual(e.fileName,"package")),n=n.map(e=>this.getFolderPathOfSpecificPath(e.absolute));for(const e of n)if(this.isAndEquals(...s.map(t=>()=>!this.has(e,t)))){const s=await this.generateTempFolderWithCleanSrc(e);await this.deleteSelfByPath(_path2.default.join(e,"release"),!0);const n=this.persistByPath(_path2.default.join(e,"release"));await this.executeCommandLine(`cd ${e} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const a=require(_path2.default.join(e,"./terser.config.js")),r=this.getStringOfTerserCommandLine(a);await this.executeCommandLine(`cd ${e}/release/lib && find . -type f -name "*.js" -exec terser {} -o {} ${r} \\;`);const o=_path2.default.join(e,"package.json");try{const s="sample.npm.module.index.js";this.copySingleFile(`/Users/davidtu/cross-achieve/legacy/idea-inventer/utiller/template/${s}`,n,"index.js",!0);const a=`${e}/release/index.js`;await this.executeCommandLine(`terser ${a} -o ${a} ${r}`);const l=_path2.default.join(e,"template");if(this.isPathExist(l)&&await this.copyFromFolderToDestFolder(l,this.persistByPath(_path2.default.join(n,"template"))),t){const{moduleName:e,version:t}=await this.upgradePackageJsonVersion(o);await this.updateVersionOfTemplate(e,t)}this.copySingleFile(o,_path2.default.join(n,"package.json"),void 0,!0),i||!this.isPathExist(_path2.default.join(n,"node_module"))?await this.executeCommandLine(`cd ${n} && yarn install --production`):this.appendInfo("ignore node-module install behavior"),this.appendInfo(`build ${e} succeed`),t&&await this.executeCommandLine(`cd ${n} && npm publish`)}catch(e){throw await this.deleteSelfByPath(n,!0),new _index2.default(9999,`generatePackage 報錯, ${e.message}`)}finally{await this.deleteSelfByPath(s,!0)}}}async updateVersionOfTemplate(e,t){const i=["/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/legacy/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/legacy/idea-inventer/free_marker/package.json"];for(const s of i)if(this.isPathExist(s)){console.log("🦴正在修改以下 path的版本 => ",s);let i=!1;const n=this.getJsonObjByFilePath(s);if(n&&n.dependencies&&n.dependencies[e]){n.dependencies[e]=`^${t}`;try{await this.writeJsonThanPrettier(s,n),i=!0}catch(e){i=!1}}i||await this.updateFileOfSpecificLine(s,i=>` "${e}":"^${t}"${String(String(i).trim()).endsWith(",")?",":""}`,t=>String(String(t).trim()).startsWith(`"${e}"`)),console.log("💯成功修改以下 path的版本 => ",s)}await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/legacy/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/legacy/idea-inventer/newp/template/",!0,!0)}async updateFileOfSpecificLine(e,t=e=>"updated",i=e=>!0){const s=this.getFileContextInRaw(e).split("\n"),n=s.findIndex(i);-1!==n&&(s[n]=t(s[n]),this.appendFile(e,s.join("\n"),!0,!0),await this.prettier(e))}async writeJsonThanPrettier(e,t){this.writeFileInJSON(e,t),await this.prettier(e)}async enrichEachPackageJson(e){const t=new Set(["package","admin.package","web.package","functions.package"]),i=this.findFilePathByExtension(e,["json"],"gen","node_modules","release").filter(e=>t.has(e.fileName));if(0!==i.length)for(const{absolute:e}of i){const t=this.getJsonObjByFilePath(e);t.scripts||={},t.scripts.updateConfigerer="npm update configerer --save",await this.writeJsonThanPrettier(e,t)}}insertShellCommand(e=_configerer.configerer.BASE_SHELL_SCRIPT,t,i){if(this.isStringContainInLines(this.getFileContextInRaw(e),t))throw new _index2.default(8007,`alias ${t} is exist`);{const s=`alias ${t}='${i}'`;this.appendFile(e,s)}}getAdminCredential(){return this.getJsonObjByFilePath("/Users/davidtu/cross-achieve/mimi/idea-inventer/firebaser/key/mimi19up-firebase-adminsdk.json")}isEmptyFile(e){if(!this.isPathExist(e))return!0;const t=this.getFileContextInRaw(e);return null==t||("string"==typeof t?0===t.trim().length:"object"==typeof t&&0===Object.keys(t).length)}isEmptyFolder(e){return 0===_fs.default.readdirSync(e).length}async prettier(e,t=250,i=[".mustache"]){const s=_path2.default.resolve(e),n=_path2.default.resolve("."),a=i.find(t=>e.endsWith(t));let r=s,o=!!a;try{if(o){const e=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t=new RegExp(`${e}$`);r=s.replace(t,""),await _fs.default.rename(s,r)}await this.executeCommandLine(`cd "${n}" && npx prettier --write "${r}" --print-width ${t} --ignore-unknown`)}catch(t){console.error(`Prettier 執行錯誤 [${e}]:`,t.message)}finally{if(o&&r!==s)try{await _fs.default.access(r),await _fs.default.rename(r,s)}catch(e){}}}getFileLastModifiedTime(e){return _fs.default.statSync(e).mtimeMs}getJsonObjByFilePath(e){return this.appendInfo(`ready to json path:${e}`),JSON.parse(this.getFileContextInRaw(e))}async upgradePackageJsonVersion(e){if(this.isEqual("json",this.getPathInfo(e).extension)){const t=this.getJsonObjByFilePath(e);return t.version=this.getStringOfVersionIncrement(t.version),await this.writeJsonThanPrettier(e,t),{version:t.version,moduleName:t.name}}throw new _index2.default(8020,`path is not package.json, which is ${e}`)}async reWriteJsonAttribute(e,...t){const{extension:i}=this.getPathInfo(e);if("json"!==i)throw new _index2.default(9999,`reWriteJsonAttribute() => path is not package.json, which is ${e}`);const s=t.find(e=>"object"!=typeof e||null===e);if(s)throw new _index2.default(9999,`84451515 attr is not object, which is 'type=${typeof s} => ${s}'`);const n=this.getJsonObjByFilePath(e);for(const e of t)n[this.getObjectKey(e)]=this.getObjectValue(e);return await this.writeJsonThanPrettier(e,n),{version:n.version,moduleName:n.name}}getVersionOfPackageJson(e){return this.getAttributeValueOfJson(e,"version","1.0.0")}getAttributeValueOfJson(e,t,i=void 0){if(this.isEqual("json",this.getPathInfo(e).extension))return this.getJsonObjByFilePath(e)[t]??i;throw new _index2.default(8020,`path is not package.json, which is ${e}`)}getVersionOfJsFile(e){return this.getAttributeValueOfJsFile(e,"version","project without version notice")}getAttributeValueOfJsFile(e,t,i=void 0){if(this.isEqual(this.getExtensionFromPath(e),"js"))return require(_path2.default.resolve(e)).default[t]??i;throw new _index2.default(8020,`path is not js file, which is ${e}`)}async rewriteAttributeOfSourceJs(e,...t){if(!this.isPathExist(e))throw new _index2.default(9999,`4849813 ${e} is not exist`);for(const i of t){if(!this.isObject(i))throw new _index2.default(9999,`4984651 attr is not object, which is 'type=${typeof i} => ${i}'`);const t=this.getObjectKey(i),s=this.getObjectValue(i),n=this.getFileContextInRaw(e).split("\n"),a=n.findIndex(e=>String(String(e).trim()).startsWith(`${t}`));n[a]=` ${t}: '${s}',`,this.appendFile(e,n.join("\n"),!0,!0)}return t}async generateTempFolderWithCleanSrc(e){this.appendInfo("generateTempFolderWithCleanSrc",e);const t=_path2.default.join(e,"src"),i=_path2.default.join(e,"temp");if(!_fs.default.existsSync(t))return i;this.appendInfo("generateTempFolderWithCleanSrc","source",t),this.persistByPath(i),await this.copyFromFolderToDestFolder(t,i);const s=this.findFilePathBy(i);for(const{absolute:e}of s){const t=this.getFileContextInRaw(e).split("\n"),i=t.map(e=>e.trim()),s=i.findIndex(e=>e.startsWith("if (configerer.DEBUG_MODE)")),n=i.lastIndexOf("}");if(s>=0&&n>s){t.splice(s,n-s+1);const i=t.join("\n");this.appendFile(e,i,!0,!0),await this.executeCommandLine(`cd ${_path2.default.dirname(e)} && npx prettier --write "${e}"`)}}return i}rewriteFile2File(e,t){const i=this.getFileContextInRaw(e);if(!i.trim())throw new _index2.default(9999,`${e} 為空,避免覆蓋`);this.appendFile(t,i,!0,!0),this.appendInfo(`rewrite from:${e} => to:${t} 成功`)}getStringOfHeadOfFile(e){return this.isPathExist(e)?this.getFileContextInRaw(e).split("\n")[0]:""}isFileEditSucceed(e){if(!this.isPathExist(e))return!1;const t=this.getPathInfo(e),i=this.getFileContextInRaw(e).trim();if(""===i)return this.appendInfo(`74985465 path ${t.path} is empty file, file would not persist`),!1;try{const e=i.split("\n")[0].match(/const\s+([a-zA-Z_]\w*)\s*=\s*(true|false)\s*;?/);if(!e||(Array.isArray(e)?e.length:"object"==typeof e&&null!==e?Object.keys(e).length:String(e).length)<3)return!1;if(!0==("true"===e[2]))return!0}catch(e){return this.appendError(`66445411 ${e.message}`),!1}return!1}joinRespectingDot(...e){const t=e[0]?.startsWith("./"),i=e[0]?.startsWith("./")?[e[0].slice(2),...e.slice(1)]:e,s=_path2.default.join(...i);return t&&!_path2.default.isAbsolute(s)?`./${s}`:s}}var _default=exports.default=NodeUtiller;
|
package/package.json
CHANGED