utiller 1.0.411 → 1.0.413
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/index.js +1 -21
- package/lib/exceptioner/ERRORs.js +1 -1
- package/lib/exceptioner/index.js +1 -1
- package/lib/index.js +1 -1
- package/lib/pooller/index.js +1 -1
- package/lib/utiller/index.js +1 -1
- package/lib/utiller/nodeutiller.js +3 -8
- package/package.json +4 -3
- package/template/sample.package.json +1 -1
- package/template/sample.terser.config.js +46 -0
- package/lib/words/index.js +0 -1
package/index.js
CHANGED
|
@@ -1,21 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* developer:david
|
|
3
|
-
* email:freshingmoon0725@gmail.com
|
|
4
|
-
* */
|
|
5
|
-
|
|
6
|
-
Object.defineProperty(exports, "__esModule", {
|
|
7
|
-
value: true
|
|
8
|
-
});
|
|
9
|
-
|
|
10
|
-
var _index = require("./lib");
|
|
11
|
-
|
|
12
|
-
Object.keys(_index).forEach(function (key) {
|
|
13
|
-
if (key === "default" || key === "__esModule") return;
|
|
14
|
-
if (key in exports && exports[key] === _index[key]) return;
|
|
15
|
-
Object.defineProperty(exports, key, {
|
|
16
|
-
enumerable: true,
|
|
17
|
-
get: function get() {
|
|
18
|
-
return _index[key];
|
|
19
|
-
}
|
|
20
|
-
});
|
|
21
|
-
});
|
|
1
|
+
Object.defineProperty(exports,"__esModule",{value:!0});var _index=require("./lib");Object.keys(_index).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===_index[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return _index[e]}}))});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;const ERRORs={2001:{message:"update item, id is required"},3001:{message:"get table error"},3002:{message:"show schema error"},3003:{message:"get object schema stmt error"},3004:{message:"lazy insert"},3005:{message:"drop all fail"},3006:{message:"delete record error"},3007:{message:"drop table error"},3008:{message:"orderBy,order SQLRules Error"},3009:{message:"createTableAndIndex, create table fail"},3010:{message:"alter columns fail"},3011:{message:"update record fail"},3012:{message:"create index fail"},3013:{message:"create table fail"},3014:{message:"insertRecord"},3015:{message:"fetch indexes error"},3016:{message:"more than 1 unique_index in table"},4001:{message:"priority state is wrong"},4002:{message:"task type isn't function"},4003:{message:"task type isn't array"},4004:{message:"task not exist when try to delete"},4005:{message:"state not valid"},4006:{message:"task param should be async function"},4007:{message:"除了runByTask以外, getTaskInfoDependOnPriority() 不能走到這裡, taskQueue裡面不能沒有Task"},4008:{message:"如果要用runInBackground的task發生Error,就必須設定 backgoundtasklistener,不能讓task發生錯誤而沒有紀錄"},4009:{message:"如果走到了這一層, 代表 Pooller runInBackGround() 在無預期的狀況下被停止了, 代表assign task throw ERROR, 請善用setTaskFailHandler()"},4010:{message:"assign task timeout happen"},4011:{message:"不能走到這裡, 目前被動式的機制只支援runByEachTask, runByParams"},8001:{message:"append file fail"},8002:{message:"open dir fail"},8003:{message:"not file nor dictionary,should get it"},8004:{message:"package exist in current path"},8005:{message:"input name is not valid"},8006:{message:"file exists when trying to copy"},8007:{message:"alias exist in shell script"},8008:{message:"persist folder fail"},8009:{message:"copy folder should be exist"},8010:{message:"the key can't exceed the length of 22"},8011:{message:"beautify class fail,but let it pass"},8012:{message:"incest props should define view,type either"},8013:{message:"render view type is out of condition, check why"},8014:{message:"type is not supported"},8015:{message:"build firestore error"},8016:{message:"class generator is necessary!!!"},8017:{message:"className type is not valid!"},8018:{message:"this platform is not supported"},8019:{message:"find no source.js file"},8020:{message:"package.json has something wrong"},9999:{message:"super stupid error"},7001:{message:"state is wrong"},7002:{message:"initial should be override"},7003:{message:"css style duplicated defined"},7004:{message:"there's no ref target"},7005:{message:"can't happen this param type"},7006:{message:"view must instance of BaseComponent,otherwise found no root cause"},7007:{message:"result result should be either succeed or fail"},7008:{message:"in array can't be empty, otherwise it get abnormal next page"},6001:{message:"single page work fail"}};var _default=exports.default=ERRORs;
|
package/lib/exceptioner/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _configerer=require("configerer"),_ERRORs=_interopRequireDefault(require("./ERRORs")),_index=require("../index.js"),_lodash=_interopRequireDefault(require("lodash"));class MyException extends Error{constructor(e,...i){const r=_ERRORs.default[e];if(void 0===r)throw new MyException(9999,`code ''${e}'' is not define in ERRORs.js`);super(`${r.message}`),this.uid=void 0===_index.utiller?"777Debug777":_index.utiller.getRandomValue(0,1e11),this.code=e,this.infos="",this._msg=r.message;for(const e of i)void 0!==e&&(this.infos+=`## ${void 0===_index.utiller?`777Debug777-${e}`:_index.utiller.getAttrValueInSequence(e,"message","msg")}`);this.message=`UID:${this.uid} CODE:${this.code} REASON:${this._msg} INFO:${this.infos}`,_configerer.configerer.MODULE_MSG.SHOW_ERROR&&_index.utiller.appendError(this.message)}static msg(e){return JSON.stringify(e)}getErrorCode(){return this.code}isConstraintError(){return this.message&&this.message.indexOf("SQLITE_CONSTRAINT")>0}}var _default=exports.default=MyException;
|
package/lib/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"exceptioner",{enumerable:!0,get:function(){return _exceptioner.default}}),Object.defineProperty(exports,"pooller",{enumerable:!0,get:function(){return _pooller.default}}),exports.utiller=void 0;var _exceptioner=_interopRequireDefault(require("./exceptioner")),_pooller=_interopRequireDefault(require("./pooller")),_lodash=_interopRequireDefault(require("lodash"));let instance=exports.utiller=void 0;if(void 0===process||_lodash.default.isUndefined(process.version)||_lodash.default.isEmpty(process.version)){const e=require("./utiller/index");exports.utiller=instance=new e.default}else{const e=require("./utiller/nodeutiller");exports.utiller=instance=new e.default}
|
package/lib/pooller/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _lodash=_interopRequireDefault(require("lodash"));var _index2=require("../index.js");var _configerer=require("configerer");var _exceptioner=_interopRequireDefault(require("../exceptioner"));function _classPrivateFieldInitSpec(e,t,a){_checkPrivateRedeclaration(e,t),t.set(e,a)}function _checkPrivateRedeclaration(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function _classPrivateFieldGet(s,a){return s.get(_assertClassBrand(s,a))}function _assertClassBrand(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}const SPECIFICITY_DEBUG=false;var _run=new WeakMap;class InfinitePool{constructor(maxWorkers=_configerer.configerer.POOLLER_WORKER_DEFAULT,name=_index2.utiller.getRandomValue(0,100000000000)){(0,_defineProperty2.default)(this,"isRunInBackgroundMode",false);(0,_defineProperty2.default)(this,"state",_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK);(0,_defineProperty2.default)(this,"enableOfTaskSleepByInterval",_configerer.configerer.POOLLER_ENABLE_TASK_SLEEP_BY_INTERVAL);(0,_defineProperty2.default)(this,"taskSleepInterval",_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT);(0,_defineProperty2.default)(this,"enableOfTaskTimeout",_configerer.configerer.POOLLER_ENABLE_TIMEOUT);(0,_defineProperty2.default)(this,"timeOfTaskTimeout",_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT);(0,_defineProperty2.default)(this,"handlerOfAssignTaskFail",undefined);(0,_defineProperty2.default)(this,"maximumOfWorker",void 0);(0,_defineProperty2.default)(this,"disableFirstRun",false);(0,_defineProperty2.default)(this,"queueOfWaitingParam",[]);(0,_defineProperty2.default)(this,"countsOfRunByTimes",-1);(0,_defineProperty2.default)(this,"queueOfAssignTask",{});(0,_defineProperty2.default)(this,"queueOfExecutingTask",[]);(0,_defineProperty2.default)(this,"isQueuePolling",false);(0,_defineProperty2.default)(this,"initialTaskCompleted",false);(0,_defineProperty2.default)(this,"mapOfHashNTask",{});(0,_defineProperty2.default)(this,"mapOfHashNCallbackWrapper",{});(0,_defineProperty2.default)(this,"nameOfCurrentPool",``);(0,_defineProperty2.default)(this,"atomicBgInstance",undefined);(0,_defineProperty2.default)(this,"setPoolId",(id=this.nameOfCurrentPool)=>{this.nameOfCurrentPool=id});(0,_defineProperty2.default)(this,"getPoolId",()=>{return this.nameOfCurrentPool});(0,_defineProperty2.default)(this,"stopInBackground",async()=>{this.terminate();let attempts=0;const maxAttempts=30;while(_lodash.default.size(this.queueOfExecutingTask)>0&&attempts<maxAttempts){await _index2.utiller.syncDelay(500);this.printLogMessage(`784512, 卡在 stopInBackground 出不來,${this.getLogMessageOfExecutingTaskQueueCount()}`);this.showState();attempts++}if(_lodash.default.size(this.queueOfExecutingTask)>0){this.printLogMessage(`stopInBackground 超時,仍有 ${_lodash.default.size(this.queueOfExecutingTask)} 個任務在執行`,true);return false}return true});(0,_defineProperty2.default)(this,"isRunning",()=>{return this.isQueuePolling});(0,_defineProperty2.default)(this,"getCountOfAssignTaskInQueue",()=>{let size=0;for(const prior of _configerer.configerer.POOLLER_PRIORITY){size+=this.queueOfAssignTask[prior].length}return size});(0,_defineProperty2.default)(this,"add",(task,priority="low")=>{if(typeof task==="function"){if(_configerer.configerer.POOLLER_PRIORITY.indexOf(priority)<0){throw new _exceptioner.default(4001,`priority can't be ${priority}`)}const hash=_index2.utiller.getRandomHash();const taskInfo={task,hash};this.appendHashTaskMap(taskInfo);this.queueOfAssignTask[priority].push(taskInfo);return hash}else{throw new _exceptioner.default(4002,`task can't be ${typeof task}`)}});(0,_defineProperty2.default)(this,"updateExecuteTaskState",hash=>{const task=_lodash.default.find(this.queueOfExecutingTask,each=>_lodash.default.isEqual(each.hash,hash));if(task){this.printLogMessage(`847875153, 客端委託的任務: ${hash},更改狀態為 'ING'`);task.state="ING"}});(0,_defineProperty2.default)(this,"taskWrapper",(assignedTask,hashOfTask,param)=>()=>{const self=this;let timeoutHash="";let assignedTaskResult;let assignedTaskError;let isAssignedTaskCompleted=true;return new Promise((resolve,reject)=>{if(self.enableOfTaskTimeout){timeoutHash=setTimeout(()=>{try{this.printLogMessage(`982532, taskWrapper執行中,發生timeout: ${self.timeOfTaskTimeout} ms`);throw new _exceptioner.default(4010,self.getPoollerLogFormat(`TASK HASH:${hashOfTask} IS TIMEOUT ${self.timeOfTaskTimeout} ms ${param?`,PARAMS IS ${JSON.stringify(param)}`:""}`))}catch(error){reject(error)}},self.timeOfTaskTimeout)}this.printLogMessage(`984135, 客端委託的task開始執行 ${hashOfTask}`);self.updateExecuteTaskState(hashOfTask);assignedTask(param).then(result=>{this.printLogMessage(`984545, 客端委託的任務(TASK HASH:${hashOfTask}),resolve回應: ${result}`);assignedTaskResult=result;isAssignedTaskCompleted=true}).catch(error=>{this.printLogMessage(`989652, 客端委託的任務,reject回應: ${error.message}`,true,error);assignedTaskError=error;isAssignedTaskCompleted=false}).finally(()=>{clearTimeout(timeoutHash);resolve();this.printLogMessage(`98942,(TASK HASH:${hashOfTask}) taskWrapper()裡面第一個promise(為了timeout設計)完成了`)})}).then(()=>{if(!isAssignedTaskCompleted){throw assignedTaskError}else{this.printLogMessage(`9894841,(TASK HASH:${hashOfTask}) taskWrapper()裡面第二個promise(整個任務)完成了`);return`${this.getLogMessageOfTaskHash(hashOfTask)} completed`}}).catch(error=>{isAssignedTaskCompleted=false;assignedTaskError=error;if(!self.isWait4ResultTask(hashOfTask)){if(self.handlerOfAssignTaskFail!==undefined){try{self.handlerOfAssignTaskFail(assignedTaskError)}catch(handlerError){this.printLogMessage(`錯誤處理器執行失敗: ${handlerError.message}`,true,handlerError)}}else{this.printLogMessage(`任務執行失敗但未設置錯誤處理器: ${assignedTaskError.message}`,true,assignedTaskError)}}}).finally(()=>{const result={assignedTaskCompleted:isAssignedTaskCompleted,resolve:assignedTaskResult,reject:assignedTaskError};self.removeResolveOrRejectPromiseByHash(hashOfTask,result);this.printLogMessage(`98943213, ${this.getLogMessageOfTaskHash(hashOfTask)} taskWrapper()裡面第2個promise完成了`,false,result)})});(0,_defineProperty2.default)(this,"adds",(tasks,priority="low")=>{const hashes=[];if(_lodash.default.isArray(tasks)){for(const task of tasks){hashes.push(this.add(task,priority))}}else{throw new _exceptioner.default(4003,`should be async function array, not ${typeof tasks}`)}return hashes});(0,_defineProperty2.default)(this,"removeTaskMapByHash",hash=>{delete this.mapOfHashNTask[hash]});(0,_defineProperty2.default)(this,"beforeRun",()=>{this.isQueuePolling=true});(0,_defineProperty2.default)(this,"afterRun",()=>{this.clearCache()});(0,_defineProperty2.default)(this,"runInInfinite",async(task=[],interval)=>{this.beforeRun();if(_lodash.default.isFunction(task))this.add(task);else if(_lodash.default.isArray(task))this.adds(task);else throw new _exceptioner.default(4006,`type of task is ===> ${typeof task}`);this.enableTaskSleepInterval(_lodash.default.isNumber(interval),interval);this.setState(_configerer.configerer.POOLLER_STATE.RUN_INFINITE);while(!this.ruleOfStopInfiniteRun()){this.printLogMessage(`415123, runInInfinite() 正在無限Loop中, ${this.getLogMessageOfExecutingTaskQueueCount()}`);await _classPrivateFieldGet(_run,this).call(this)}});(0,_defineProperty2.default)(this,"ruleOfStopInfiniteRun",()=>{return!this.isRunning()&&this.isExecutingTaskQueueEmpty()});(0,_defineProperty2.default)(this,"isExecutingTaskQueueEmpty",()=>{return _lodash.default.size(this.queueOfExecutingTask)===0});(0,_defineProperty2.default)(this,"appendParamInToQueue",(...params)=>{this.triggerBgInstance();this.queueOfWaitingParam.push(...params)});(0,_defineProperty2.default)(this,"runByParams",async(functionOfAsyncTask,...params)=>{if(functionOfAsyncTask===undefined){functionOfAsyncTask=this.queueOfAssignTask["low"].shift().task}if(!_lodash.default.isFunction(functionOfAsyncTask))throw new _exceptioner.default(4006,`runByParams error, typeof task can't be ${typeof functionOfAsyncTask}`);if(!_lodash.default.isArray(params))throw new _exceptioner.default(4006,`runByParams error, typeof params can't be ${typeof params}`);this.beforeRun();this.add(functionOfAsyncTask);this.appendParamInToQueue(...params);this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS);while(_lodash.default.size(this.queueOfWaitingParam)>0){await _classPrivateFieldGet(_run,this).call(this)}while(!this.isExecutingTaskQueueEmpty()){await _index2.utiller.syncDelay(100);this.printLogMessage(`等待執行中的任務完成,剩餘: ${_lodash.default.size(this.queueOfExecutingTask)}`)}this.printLogMessage(`951281952, runByParams() 結束了while()`);this.terminate()});(0,_defineProperty2.default)(this,"runByEachTask",async(tasks=[])=>{this.id=_index2.utiller.getRandomHash(15);this.beforeRun();this.adds(tasks);this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK);while(!this.ruleOfStopInfiniteRun()){await _classPrivateFieldGet(_run,this).call(this,this.id);if(this.getCountOfAssignTaskInQueue()<=0){this.terminate();this.printLogMessage(`788121, runByEachTask() 因為 taskOfWaitingQueue 清空而停止`)}await _index2.utiller.syncDelay(10);this.printLogMessage(`788143, runByEachTask() 為了讓while不要停止運算`)}this.printLogMessage(`7881952, runByEachTask() 結束了while()`)});(0,_defineProperty2.default)(this,"runByTimes",async(functionOfAsyncTask,times=1)=>{if(this.maximumOfWorker!==1){this.printLogMessage(`警告: runByTimes 模式建議使用 1 個 worker,當前為 ${this.maximumOfWorker}`,true)}this.countsOfRunByTimes=times;this.add(functionOfAsyncTask);this.beforeRun();this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES);while(!this.ruleOfStopInfiniteRun()&&this.countsOfRunByTimes>0){await _classPrivateFieldGet(_run,this).call(this)}});(0,_defineProperty2.default)(this,"runInBackGround",(asyncfunc,...params)=>{this.isRunInBackgroundMode=true;if(!(typeof asyncfunc==="function")){throw new _exceptioner.default(4002,`_asyncfunc can't be ${typeof asyncfunc}`)}return setTimeout(async()=>{try{await asyncfunc.apply(this,params)}catch(error){if(error instanceof _exceptioner.default){this.printLogMessage(`7812123, runInBackGround() 執行錯誤: ${error.message}`,true,error)}else{throw new _exceptioner.default(4009,{message:`${this.getPoollerLogFormat("")}`},error)}}finally{this.terminate();this.printLogMessage(`7812123, runInBackGround() 走到finally`)}},1)});(0,_defineProperty2.default)(this,"getPoollerLogFormat",msg=>{return`POOLLER NAME: ${this.getPoolId()}${_lodash.default.isEmpty(msg)?"":" , "}${msg}`});(0,_defineProperty2.default)(this,"setTaskFailHandler",(listener=error=>console.log(error.message))=>{this.handlerOfAssignTaskFail=listener});(0,_defineProperty2.default)(this,"rulesOfAppendToExecutingTask",()=>{switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:return this.isRunning()&&!this.isExecutingQueueFull()&&_lodash.default.size(this.queueOfWaitingParam)>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}});(0,_defineProperty2.default)(this,"appendTaskToExecuteQueue",(hash,promise)=>{if(_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES)){this.countsOfRunByTimes=this.countsOfRunByTimes-1}const task={state:"NOT",hash:hash,task:promise};this.printLogMessage(`4484451, 增加了一個assignedTask ${this.getLogMessageOfTaskHash(hash)} 到 QueueOfExecutingTask ,${this.getLogMessageOfExecutingTaskQueueCount()}`,false,task);this.queueOfExecutingTask.push(task)});(0,_defineProperty2.default)(this,"getLogMessageOfExecutingTaskQueueCount",()=>{return`ExecutingTaskQueueCount: ${_lodash.default.size(this.queueOfExecutingTask)}`});(0,_defineProperty2.default)(this,"getLogMessageOfAssignTaskQueueCount",()=>{return`AssignTaskQueueCount: ${this.getCountOfAssignTaskInQueue()}`});(0,_defineProperty2.default)(this,"getLogMessageOfTaskHash",hash=>{return`TASK HASH: ${hash}`});(0,_defineProperty2.default)(this,"showState",()=>{_index2.utiller.appendInfo(this.getPoollerLogFormat(`workerCount: ${this.maximumOfWorker}`));_index2.utiller.appendInfo(this.getPoollerLogFormat(`taskQueue(還在排隊的Task): ${this.getCountOfAssignTaskInQueue()}`));_index2.utiller.appendInfo(this.getPoollerLogFormat(`QueueOfExecutingTask(正在執行的AsyncTask, 超過workerCount就是bug): ${_lodash.default.size(this.queueOfExecutingTask)}`));_index2.utiller.appendInfo(this.getPoollerLogFormat(`mapOfHashNTask(還沒執行到的AsyncTask reference的暫存區): ${_lodash.default.size(this.mapOfHashNTask)}`))});_classPrivateFieldInitSpec(this,_run,async()=>{const self=this;async function execute(){const tasks=_lodash.default.filter(self.queueOfExecutingTask,each=>_lodash.default.isEqual(each.state,"NOT")).map(each=>{const taskWrapper=each.task;return taskWrapper()});self.printLogMessage(`454652321, 開始任務(taskWrapper): run() 裡面的execute開始執行, task(state = NOT)的長度 ${_lodash.default.size(tasks)}`);const result=_lodash.default.size(tasks)>0?await Promise.race(tasks):"4542131684, task is empty";self.printLogMessage(`54121445161, 結束任務(taskWrapper): run() 裡面的execute結束執行`);return result}async function emptyTask(){self.printLogMessage(`因為max count of worker為0,所以指派一個簡單的任務`);await _index2.utiller.syncDelay(10)}await this.syncTaskDispatcher();if(this.maximumOfWorker===0){await emptyTask()}else if(!this.isExecutingTaskQueueEmpty()){this.printLogMessage(`4512211, 開始任務(taskWrapper): ${this.getLogMessageOfExecutingTaskQueueCount()}`);const task=await execute();this.printLogMessage(`4512213 完畢任務(taskWrapper:${task}), ${this.getLogMessageOfExecutingTaskQueueCount()}, ${this.getLogMessageOfAssignTaskQueueCount()}`)}else{this.printLogMessage(`4574152 不應該走到這裏,但是 minor issue`,true)}if(this.queueOfExecutingTask.length>this.maximumOfWorker)this.printLogMessage(`4512214 一定是改壞了!!!!!!!!!!, ${this.getLogMessageOfExecutingTaskQueueCount} `,true);self.printLogMessage(`5478421212, 離開 run()`)});(0,_defineProperty2.default)(this,"getTaskInfoForRepetitiveRun",originalTaskInfo=>{const newTaskInfo={task:originalTaskInfo.task,hash:_index2.utiller.getRandomHash()};this.appendHashTaskMap(newTaskInfo);return newTaskInfo});(0,_defineProperty2.default)(this,"getTaskInfoDependOnPriority",()=>{for(const prior of _configerer.configerer.POOLLER_PRIORITY){if(this.queueOfAssignTask[prior].length>0){switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.queueOfAssignTask[prior].shift();case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:const originalTaskInfo=this.queueOfAssignTask[prior][0];return this.getTaskInfoForRepetitiveRun(originalTaskInfo);default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}}}if(!_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK))throw new _exceptioner.default(4007)});(0,_defineProperty2.default)(this,"removeResolveOrRejectPromiseByHash",(hash,result)=>{const callbackWrapper=this.mapOfHashNCallbackWrapper[hash];if(callbackWrapper!==undefined){this.printLogMessage(`5644153248, removeResolveOrRejectPromiseByHash 拿掉了完成的任務(${this.getLogMessageOfTaskHash(hash)})`);try{callbackWrapper(result)}catch(callbackError){this.printLogMessage(`回調執行失敗: ${callbackError.message}`,true,callbackError)}finally{delete this.mapOfHashNCallbackWrapper[hash]}}this.removePromiseFromExecutingQueue(hash)});(0,_defineProperty2.default)(this,"removePromiseFromExecutingQueue",hash=>{this.printLogMessage(`56448412, QueueOfExecutingTask 拿掉了完成的任務 ${this.getLogMessageOfTaskHash(hash)}`);_lodash.default.remove(this.queueOfExecutingTask,each=>_lodash.default.isEqual(hash,each.hash))});(0,_defineProperty2.default)(this,"runInfiniteInBackground",(functionOfAsyncTask,interval)=>{return this.invokeInstanceOfBackground(this.runInInfinite,functionOfAsyncTask,interval)});(0,_defineProperty2.default)(this,"runByParamInBackGround",(functionOfAsyncTask,...params)=>{return this.invokeInstanceOfBackground(this.runByParams,functionOfAsyncTask,...params)});(0,_defineProperty2.default)(this,"runByTimesInBackGround",(functionOfAsyncTask,times)=>{return this.invokeInstanceOfBackground(this.runByTimes,functionOfAsyncTask,times)});(0,_defineProperty2.default)(this,"runByEachTaskInBackGround",(...params)=>{return this.invokeInstanceOfBackground(this.runByEachTask,...params)});(0,_defineProperty2.default)(this,"invokeInstanceOfBackground",(state,...params)=>{if(this.atomicBgInstance!==undefined)clearTimeout(this.atomicBgInstance);this.atomicBgInstance=this.runInBackGround(state,...params);return this});this.maximumOfWorker=maxWorkers;this.setPoolId(_lodash.default.toString(name));for(const prior of _configerer.configerer.POOLLER_PRIORITY){this.queueOfAssignTask[prior]=[]}}enableQueueTerminateBySleepCount(enable=true,interval=_configerer.configerer.POOLLER_QUEUE_TIME_OF_SLEEP_INTERVAL_DEFAULT,times=_configerer.configerer.POOLLER_QUEUE_MAX_SLEEP_COUNTS_DEFAULT){this.enableOfQueueTerminateSleepCount=enable;this.queueMaxSleepCounts=times;this.intervalOfQueueSleep=interval}clearCache(){this.queueOfExecutingTask.length=0;this.mapOfHashNTask={};this.queueOfAssignTask={}}terminate(){this.isQueuePolling=false}printLogMessage(message,error=false,...infos){if(SPECIFICITY_DEBUG)_index2.utiller.printLogMessage(this.getPoollerLogFormat(message),error,...infos)}setWorker(counts){this.maximumOfWorker=counts}cleanTaskInterval(){this.taskSleepInterval={min:0,max:0}}enableTaskSleepInterval(enable=true,interval=_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT){this.enableOfTaskSleepByInterval=enable;if(_lodash.default.isNumber(interval)){interval={min:interval,max:interval}}this.taskSleepInterval=interval}enableTaskTimeout(enable=true,millionSec=_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT){this.enableOfTaskTimeout=enable;this.timeOfTaskTimeout=millionSec}async addTaskAndWait4Result(asyncTask,priority="low",taskName="noName"){this.triggerBgInstance();return new Promise((resolve,reject)=>{const callbackWrapper=result=>{if(result.assignedTaskCompleted){resolve(result.resolve)}else{reject(result.reject)}};const hash=this.add(asyncTask,priority);this.registerHash4Result(hash,callbackWrapper)})}registerHash4Result(hash,callback){this.mapOfHashNCallbackWrapper[hash]=callback}appendHashTaskMap(taskInfo){this.mapOfHashNTask[taskInfo.hash]=taskInfo}getTaskInfoByHash(hash){return this.mapOfHashNTask[hash]}remove(hash){let taskInfo=this.getTaskInfoByHash(hash);if(taskInfo){for(const prior of _configerer.configerer.POOLLER_PRIORITY){const _index=_lodash.default.indexOf(this.queueOfAssignTask[prior],taskInfo);if(_index>=0){this.queueOfAssignTask[prior].splice(_index,1);this.removeTaskMapByHash(hash);return true}}return false}else{throw new _exceptioner.default(4004,hash)}}setState(_state){this.state=_state}checkAndMarkInitialTaskStatus(){if(!this.initialTaskCompleted){this.initialTaskCompleted=true;return false}return this.initialTaskCompleted}setDisableFirstRun(disable=true){this.disableFirstRun=disable}triggerBgInstance(){if(!this.isRunInBackgroundMode||this.isQueuePolling){return}if(this.state===_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK){this.runByEachTaskInBackGround();return}else if(this.state===_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS){this.runByParamInBackGround();return}throw new _exceptioner.default(4011,`this.state is ==> ${_index2.utiller.getItsKeyByValue(_configerer.configerer.POOLLER_STATE,this.state)}`)}isExecutingQueueFull(){return _lodash.default.size(this.queueOfExecutingTask)>=this.maximumOfWorker}isTaskQueueEmpty(){return this.getCountOfAssignTaskInQueue()===0}async syncTaskDispatcher(){this.printLogMessage(`448984466, 走進來了 syncTaskDispatcher()`);const initialTaskShouldNotRun=this.disableFirstRun&&!this.checkAndMarkInitialTaskStatus();const isExecutingTaskAlmostFull=this.queueOfExecutingTask.length>=this.maximumOfWorker-1;const comparison=this.checkAndMarkInitialTaskStatus()&&isExecutingTaskAlmostFull&&this.enableOfTaskSleepByInterval;if(initialTaskShouldNotRun||comparison){const restInInterval=await _index2.utiller.syncDelayRandom(this.taskSleepInterval.min,this.taskSleepInterval.max);this.printLogMessage(`4484121, 走到睡覺區 enableOfTaskSleepByInterval:${this.enableOfTaskSleepByInterval} || ${restInInterval} ms`)}while(this.rulesOfAppendToExecutingTask()){const taskInfo=this.getTaskInfoDependOnPriority();if(taskInfo){const promise=this.taskWrapper(taskInfo.task,taskInfo.hash,this.queueOfWaitingParam.shift());if(this.state===_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK){this.removeTaskMapByHash(taskInfo.hash)}this.appendTaskToExecuteQueue(taskInfo.hash,promise)}else{this.printLogMessage(`848451 也許有未知的issue,保險起見break`,true);break}}this.printLogMessage(`4489844821, 離開了 syncTaskDispatcher()`)}isWait4ResultTask(hash){return this.mapOfHashNCallbackWrapper[hash]!==undefined}}var _default=exports.default=InfinitePool;
|
|
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")),_lodash=_interopRequireDefault(require("lodash")),_index2=require("../index.js"),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner"));function _classPrivateFieldInitSpec(e,t,s){_checkPrivateRedeclaration(e,t),t.set(e,s)}function _checkPrivateRedeclaration(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function _classPrivateFieldGet(e,t){return e.get(_assertClassBrand(e,t))}function _assertClassBrand(e,t,s){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:s;throw new TypeError("Private element is not present on this object")}const SPECIFICITY_DEBUG=!1;var _run=new WeakMap;class InfinitePool{constructor(e=_configerer.configerer.POOLLER_WORKER_DEFAULT,t=_index2.utiller.getRandomValue(0,1e11)){(0,_defineProperty2.default)(this,"isRunInBackgroundMode",!1),(0,_defineProperty2.default)(this,"state",_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK),(0,_defineProperty2.default)(this,"enableOfTaskSleepByInterval",_configerer.configerer.POOLLER_ENABLE_TASK_SLEEP_BY_INTERVAL),(0,_defineProperty2.default)(this,"taskSleepInterval",_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT),(0,_defineProperty2.default)(this,"enableOfTaskTimeout",_configerer.configerer.POOLLER_ENABLE_TIMEOUT),(0,_defineProperty2.default)(this,"timeOfTaskTimeout",_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT),(0,_defineProperty2.default)(this,"handlerOfAssignTaskFail",void 0),(0,_defineProperty2.default)(this,"maximumOfWorker",void 0),(0,_defineProperty2.default)(this,"disableFirstRun",!1),(0,_defineProperty2.default)(this,"queueOfWaitingParam",[]),(0,_defineProperty2.default)(this,"countsOfRunByTimes",-1),(0,_defineProperty2.default)(this,"queueOfAssignTask",{}),(0,_defineProperty2.default)(this,"queueOfExecutingTask",[]),(0,_defineProperty2.default)(this,"isQueuePolling",!1),(0,_defineProperty2.default)(this,"initialTaskCompleted",!1),(0,_defineProperty2.default)(this,"mapOfHashNTask",{}),(0,_defineProperty2.default)(this,"mapOfHashNCallbackWrapper",{}),(0,_defineProperty2.default)(this,"nameOfCurrentPool",""),(0,_defineProperty2.default)(this,"atomicBgInstance",void 0),(0,_defineProperty2.default)(this,"setPoolId",(e=this.nameOfCurrentPool)=>{this.nameOfCurrentPool=e}),(0,_defineProperty2.default)(this,"getPoolId",()=>this.nameOfCurrentPool),(0,_defineProperty2.default)(this,"stopInBackground",async()=>{this.terminate();let e=0;for(;_lodash.default.size(this.queueOfExecutingTask)>0&&e<30;)await _index2.utiller.syncDelay(500),this.printLogMessage(`784512, 卡在 stopInBackground 出不來,${this.getLogMessageOfExecutingTaskQueueCount()}`),this.showState(),e++;return!(_lodash.default.size(this.queueOfExecutingTask)>0&&(this.printLogMessage(`stopInBackground 超時,仍有 ${_lodash.default.size(this.queueOfExecutingTask)} 個任務在執行`,!0),1))}),(0,_defineProperty2.default)(this,"isRunning",()=>this.isQueuePolling),(0,_defineProperty2.default)(this,"getCountOfAssignTaskInQueue",()=>{let e=0;for(const t of _configerer.configerer.POOLLER_PRIORITY)e+=this.queueOfAssignTask[t].length;return e}),(0,_defineProperty2.default)(this,"add",(e,t="low")=>{if("function"==typeof e){if(_configerer.configerer.POOLLER_PRIORITY.indexOf(t)<0)throw new _exceptioner.default(4001,`priority can't be ${t}`);const s=_index2.utiller.getRandomHash(),i={task:e,hash:s};return this.appendHashTaskMap(i),this.queueOfAssignTask[t].push(i),s}throw new _exceptioner.default(4002,"task can't be "+typeof e)}),(0,_defineProperty2.default)(this,"updateExecuteTaskState",e=>{const t=_lodash.default.find(this.queueOfExecutingTask,t=>_lodash.default.isEqual(t.hash,e));t&&(this.printLogMessage(`847875153, 客端委託的任務: ${e},更改狀態為 'ING'`),t.state="ING")}),(0,_defineProperty2.default)(this,"taskWrapper",(e,t,s)=>()=>{const i=this;let a,r,n="",o=!0;return new Promise((u,f)=>{i.enableOfTaskTimeout&&(n=setTimeout(()=>{try{throw this.printLogMessage(`982532, taskWrapper執行中,發生timeout: ${i.timeOfTaskTimeout} ms`),new _exceptioner.default(4010,i.getPoollerLogFormat(`TASK HASH:${t} IS TIMEOUT ${i.timeOfTaskTimeout} ms ${s?`,PARAMS IS ${JSON.stringify(s)}`:""}`))}catch(e){f(e)}},i.timeOfTaskTimeout)),this.printLogMessage(`984135, 客端委託的task開始執行 ${t}`),i.updateExecuteTaskState(t),e(s).then(e=>{this.printLogMessage(`984545, 客端委託的任務(TASK HASH:${t}),resolve回應: ${e}`),a=e,o=!0}).catch(e=>{this.printLogMessage(`989652, 客端委託的任務,reject回應: ${e.message}`,!0,e),r=e,o=!1}).finally(()=>{clearTimeout(n),u(),this.printLogMessage(`98942,(TASK HASH:${t}) taskWrapper()裡面第一個promise(為了timeout設計)完成了`)})}).then(()=>{if(o)return this.printLogMessage(`9894841,(TASK HASH:${t}) taskWrapper()裡面第二個promise(整個任務)完成了`),`${this.getLogMessageOfTaskHash(t)} completed`;throw r}).catch(e=>{if(o=!1,r=e,!i.isWait4ResultTask(t))if(void 0!==i.handlerOfAssignTaskFail)try{i.handlerOfAssignTaskFail(r)}catch(e){this.printLogMessage(`錯誤處理器執行失敗: ${e.message}`,!0,e)}else this.printLogMessage(`任務執行失敗但未設置錯誤處理器: ${r.message}`,!0,r)}).finally(()=>{const e={assignedTaskCompleted:o,resolve:a,reject:r};i.removeResolveOrRejectPromiseByHash(t,e),this.printLogMessage(`98943213, ${this.getLogMessageOfTaskHash(t)} taskWrapper()裡面第2個promise完成了`,!1,e)})}),(0,_defineProperty2.default)(this,"adds",(e,t="low")=>{const s=[];if(!_lodash.default.isArray(e))throw new _exceptioner.default(4003,"should be async function array, not "+typeof e);for(const i of e)s.push(this.add(i,t));return s}),(0,_defineProperty2.default)(this,"removeTaskMapByHash",e=>{delete this.mapOfHashNTask[e]}),(0,_defineProperty2.default)(this,"beforeRun",()=>{this.isQueuePolling=!0}),(0,_defineProperty2.default)(this,"afterRun",()=>{this.clearCache()}),(0,_defineProperty2.default)(this,"runInInfinite",async(e=[],t)=>{if(this.beforeRun(),_lodash.default.isFunction(e))this.add(e);else{if(!_lodash.default.isArray(e))throw new _exceptioner.default(4006,"type of task is ===> "+typeof e);this.adds(e)}for(this.enableTaskSleepInterval(_lodash.default.isNumber(t),t),this.setState(_configerer.configerer.POOLLER_STATE.RUN_INFINITE);!this.ruleOfStopInfiniteRun();)this.printLogMessage(`415123, runInInfinite() 正在無限Loop中, ${this.getLogMessageOfExecutingTaskQueueCount()}`),await _classPrivateFieldGet(_run,this).call(this)}),(0,_defineProperty2.default)(this,"ruleOfStopInfiniteRun",()=>!this.isRunning()&&this.isExecutingTaskQueueEmpty()),(0,_defineProperty2.default)(this,"isExecutingTaskQueueEmpty",()=>0===_lodash.default.size(this.queueOfExecutingTask)),(0,_defineProperty2.default)(this,"appendParamInToQueue",(...e)=>{this.triggerBgInstance(),this.queueOfWaitingParam.push(...e)}),(0,_defineProperty2.default)(this,"runByParams",async(e,...t)=>{if(void 0===e&&(e=this.queueOfAssignTask.low.shift().task),!_lodash.default.isFunction(e))throw new _exceptioner.default(4006,"runByParams error, typeof task can't be "+typeof e);if(!_lodash.default.isArray(t))throw new _exceptioner.default(4006,"runByParams error, typeof params can't be "+typeof t);for(this.beforeRun(),this.add(e),this.appendParamInToQueue(...t),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS);_lodash.default.size(this.queueOfWaitingParam)>0;)await _classPrivateFieldGet(_run,this).call(this);for(;!this.isExecutingTaskQueueEmpty();)await _index2.utiller.syncDelay(100),this.printLogMessage(`等待執行中的任務完成,剩餘: ${_lodash.default.size(this.queueOfExecutingTask)}`);this.printLogMessage("951281952, runByParams() 結束了while()"),this.terminate()}),(0,_defineProperty2.default)(this,"runByEachTask",async(e=[])=>{for(this.id=_index2.utiller.getRandomHash(15),this.beforeRun(),this.adds(e),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK);!this.ruleOfStopInfiniteRun();)await _classPrivateFieldGet(_run,this).call(this,this.id),this.getCountOfAssignTaskInQueue()<=0&&(this.terminate(),this.printLogMessage("788121, runByEachTask() 因為 taskOfWaitingQueue 清空而停止")),await _index2.utiller.syncDelay(10),this.printLogMessage("788143, runByEachTask() 為了讓while不要停止運算");this.printLogMessage("7881952, runByEachTask() 結束了while()")}),(0,_defineProperty2.default)(this,"runByTimes",async(e,t=1)=>{for(1!==this.maximumOfWorker&&this.printLogMessage(`警告: runByTimes 模式建議使用 1 個 worker,當前為 ${this.maximumOfWorker}`,!0),this.countsOfRunByTimes=t,this.add(e),this.beforeRun(),this.setState(_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES);!this.ruleOfStopInfiniteRun()&&this.countsOfRunByTimes>0;)await _classPrivateFieldGet(_run,this).call(this)}),(0,_defineProperty2.default)(this,"runInBackGround",(e,...t)=>{if(this.isRunInBackgroundMode=!0,"function"!=typeof e)throw new _exceptioner.default(4002,"_asyncfunc can't be "+typeof e);return setTimeout(async()=>{try{await e.apply(this,t)}catch(e){if(!(e instanceof _exceptioner.default))throw new _exceptioner.default(4009,{message:`${this.getPoollerLogFormat("")}`},e);this.printLogMessage(`7812123, runInBackGround() 執行錯誤: ${e.message}`,!0,e)}finally{this.terminate(),this.printLogMessage("7812123, runInBackGround() 走到finally")}},1)}),(0,_defineProperty2.default)(this,"getPoollerLogFormat",e=>`POOLLER NAME: ${this.getPoolId()}${_lodash.default.isEmpty(e)?"":" , "}${e}`),(0,_defineProperty2.default)(this,"setTaskFailHandler",(e=e=>{})=>{this.handlerOfAssignTaskFail=e}),(0,_defineProperty2.default)(this,"rulesOfAppendToExecutingTask",()=>{switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:return this.isRunning()&&!this.isExecutingQueueFull()&&_lodash.default.size(this.queueOfWaitingParam)>0;case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:return this.isRunning()&&!this.isExecutingQueueFull()&&this.getCountOfAssignTaskInQueue()>0;default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}}),(0,_defineProperty2.default)(this,"appendTaskToExecuteQueue",(e,t)=>{_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_TIMES)&&(this.countsOfRunByTimes=this.countsOfRunByTimes-1);const s={state:"NOT",hash:e,task:t};this.printLogMessage(`4484451, 增加了一個assignedTask ${this.getLogMessageOfTaskHash(e)} 到 QueueOfExecutingTask ,${this.getLogMessageOfExecutingTaskQueueCount()}`,!1,s),this.queueOfExecutingTask.push(s)}),(0,_defineProperty2.default)(this,"getLogMessageOfExecutingTaskQueueCount",()=>`ExecutingTaskQueueCount: ${_lodash.default.size(this.queueOfExecutingTask)}`),(0,_defineProperty2.default)(this,"getLogMessageOfAssignTaskQueueCount",()=>`AssignTaskQueueCount: ${this.getCountOfAssignTaskInQueue()}`),(0,_defineProperty2.default)(this,"getLogMessageOfTaskHash",e=>`TASK HASH: ${e}`),(0,_defineProperty2.default)(this,"showState",()=>{_index2.utiller.appendInfo(this.getPoollerLogFormat(`workerCount: ${this.maximumOfWorker}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`taskQueue(還在排隊的Task): ${this.getCountOfAssignTaskInQueue()}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`QueueOfExecutingTask(正在執行的AsyncTask, 超過workerCount就是bug): ${_lodash.default.size(this.queueOfExecutingTask)}`)),_index2.utiller.appendInfo(this.getPoollerLogFormat(`mapOfHashNTask(還沒執行到的AsyncTask reference的暫存區): ${_lodash.default.size(this.mapOfHashNTask)}`))}),_classPrivateFieldInitSpec(this,_run,async()=>{const e=this;if(await this.syncTaskDispatcher(),0===this.maximumOfWorker)await async function(){e.printLogMessage("因為max count of worker為0,所以指派一個簡單的任務"),await _index2.utiller.syncDelay(10)}();else if(this.isExecutingTaskQueueEmpty())this.printLogMessage("4574152 不應該走到這裏,但是 minor issue",!0);else{this.printLogMessage(`4512211, 開始任務(taskWrapper): ${this.getLogMessageOfExecutingTaskQueueCount()}`);const t=await async function(){const t=_lodash.default.filter(e.queueOfExecutingTask,e=>_lodash.default.isEqual(e.state,"NOT")).map(e=>(0,e.task)());e.printLogMessage(`454652321, 開始任務(taskWrapper): run() 裡面的execute開始執行, task(state = NOT)的長度 ${_lodash.default.size(t)}`);const s=_lodash.default.size(t)>0?await Promise.race(t):"4542131684, task is empty";return e.printLogMessage("54121445161, 結束任務(taskWrapper): run() 裡面的execute結束執行"),s}();this.printLogMessage(`4512213 完畢任務(taskWrapper:${t}), ${this.getLogMessageOfExecutingTaskQueueCount()}, ${this.getLogMessageOfAssignTaskQueueCount()}`)}this.queueOfExecutingTask.length>this.maximumOfWorker&&this.printLogMessage(`4512214 一定是改壞了!!!!!!!!!!, ${this.getLogMessageOfExecutingTaskQueueCount} `,!0),e.printLogMessage("5478421212, 離開 run()")}),(0,_defineProperty2.default)(this,"getTaskInfoForRepetitiveRun",e=>{const t={task:e.task,hash:_index2.utiller.getRandomHash()};return this.appendHashTaskMap(t),t}),(0,_defineProperty2.default)(this,"getTaskInfoDependOnPriority",()=>{for(const e of _configerer.configerer.POOLLER_PRIORITY)if(this.queueOfAssignTask[e].length>0)switch(this.state){case _configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK:return this.queueOfAssignTask[e].shift();case _configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS:case _configerer.configerer.POOLLER_STATE.RUN_BY_TIMES:case _configerer.configerer.POOLLER_STATE.RUN_INFINITE:const t=this.queueOfAssignTask[e][0];return this.getTaskInfoForRepetitiveRun(t);default:throw new _exceptioner.default(4005,`this.state ==> ${this.state}`)}if(!_lodash.default.isEqual(this.state,_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK))throw new _exceptioner.default(4007)}),(0,_defineProperty2.default)(this,"removeResolveOrRejectPromiseByHash",(e,t)=>{const s=this.mapOfHashNCallbackWrapper[e];if(void 0!==s){this.printLogMessage(`5644153248, removeResolveOrRejectPromiseByHash 拿掉了完成的任務(${this.getLogMessageOfTaskHash(e)})`);try{s(t)}catch(e){this.printLogMessage(`回調執行失敗: ${e.message}`,!0,e)}finally{delete this.mapOfHashNCallbackWrapper[e]}}this.removePromiseFromExecutingQueue(e)}),(0,_defineProperty2.default)(this,"removePromiseFromExecutingQueue",e=>{this.printLogMessage(`56448412, QueueOfExecutingTask 拿掉了完成的任務 ${this.getLogMessageOfTaskHash(e)}`),_lodash.default.remove(this.queueOfExecutingTask,t=>_lodash.default.isEqual(e,t.hash))}),(0,_defineProperty2.default)(this,"runInfiniteInBackground",(e,t)=>this.invokeInstanceOfBackground(this.runInInfinite,e,t)),(0,_defineProperty2.default)(this,"runByParamInBackGround",(e,...t)=>this.invokeInstanceOfBackground(this.runByParams,e,...t)),(0,_defineProperty2.default)(this,"runByTimesInBackGround",(e,t)=>this.invokeInstanceOfBackground(this.runByTimes,e,t)),(0,_defineProperty2.default)(this,"runByEachTaskInBackGround",(...e)=>this.invokeInstanceOfBackground(this.runByEachTask,...e)),(0,_defineProperty2.default)(this,"invokeInstanceOfBackground",(e,...t)=>(void 0!==this.atomicBgInstance&&clearTimeout(this.atomicBgInstance),this.atomicBgInstance=this.runInBackGround(e,...t),this)),this.maximumOfWorker=e,this.setPoolId(_lodash.default.toString(t));for(const e of _configerer.configerer.POOLLER_PRIORITY)this.queueOfAssignTask[e]=[]}enableQueueTerminateBySleepCount(e=!0,t=_configerer.configerer.POOLLER_QUEUE_TIME_OF_SLEEP_INTERVAL_DEFAULT,s=_configerer.configerer.POOLLER_QUEUE_MAX_SLEEP_COUNTS_DEFAULT){this.enableOfQueueTerminateSleepCount=e,this.queueMaxSleepCounts=s,this.intervalOfQueueSleep=t}clearCache(){this.queueOfExecutingTask.length=0,this.mapOfHashNTask={},this.queueOfAssignTask={}}terminate(){this.isQueuePolling=!1}printLogMessage(e,t=!1,...s){}setWorker(e){this.maximumOfWorker=e}cleanTaskInterval(){this.taskSleepInterval={min:0,max:0}}enableTaskSleepInterval(e=!0,t=_configerer.configerer.POOLLER_TASK_OF_INTERVAL_DEFAULT){this.enableOfTaskSleepByInterval=e,_lodash.default.isNumber(t)&&(t={min:t,max:t}),this.taskSleepInterval=t}enableTaskTimeout(e=!0,t=_configerer.configerer.POOLLER_TASK_TIMEOUT_DEFAULT){this.enableOfTaskTimeout=e,this.timeOfTaskTimeout=t}async addTaskAndWait4Result(e,t="low",s="noName"){return this.triggerBgInstance(),new Promise((s,i)=>{const a=this.add(e,t);this.registerHash4Result(a,e=>{e.assignedTaskCompleted?s(e.resolve):i(e.reject)})})}registerHash4Result(e,t){this.mapOfHashNCallbackWrapper[e]=t}appendHashTaskMap(e){this.mapOfHashNTask[e.hash]=e}getTaskInfoByHash(e){return this.mapOfHashNTask[e]}remove(e){let t=this.getTaskInfoByHash(e);if(t){for(const s of _configerer.configerer.POOLLER_PRIORITY){const i=_lodash.default.indexOf(this.queueOfAssignTask[s],t);if(i>=0)return this.queueOfAssignTask[s].splice(i,1),this.removeTaskMapByHash(e),!0}return!1}throw new _exceptioner.default(4004,e)}setState(e){this.state=e}checkAndMarkInitialTaskStatus(){return this.initialTaskCompleted?this.initialTaskCompleted:(this.initialTaskCompleted=!0,!1)}setDisableFirstRun(e=!0){this.disableFirstRun=e}triggerBgInstance(){if(this.isRunInBackgroundMode&&!this.isQueuePolling)if(this.state!==_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK){if(this.state!==_configerer.configerer.POOLLER_STATE.RUN_BY_PARAMS)throw new _exceptioner.default(4011,`this.state is ==> ${_index2.utiller.getItsKeyByValue(_configerer.configerer.POOLLER_STATE,this.state)}`);this.runByParamInBackGround()}else this.runByEachTaskInBackGround()}isExecutingQueueFull(){return _lodash.default.size(this.queueOfExecutingTask)>=this.maximumOfWorker}isTaskQueueEmpty(){return 0===this.getCountOfAssignTaskInQueue()}async syncTaskDispatcher(){this.printLogMessage("448984466, 走進來了 syncTaskDispatcher()");const e=this.disableFirstRun&&!this.checkAndMarkInitialTaskStatus(),t=this.queueOfExecutingTask.length>=this.maximumOfWorker-1,s=this.checkAndMarkInitialTaskStatus()&&t&&this.enableOfTaskSleepByInterval;if(e||s){const e=await _index2.utiller.syncDelayRandom(this.taskSleepInterval.min,this.taskSleepInterval.max);this.printLogMessage(`4484121, 走到睡覺區 enableOfTaskSleepByInterval:${this.enableOfTaskSleepByInterval} || ${e} ms`)}for(;this.rulesOfAppendToExecutingTask();){const e=this.getTaskInfoDependOnPriority();if(!e){this.printLogMessage("848451 也許有未知的issue,保險起見break",!0);break}{const t=this.taskWrapper(e.task,e.hash,this.queueOfWaitingParam.shift());this.state===_configerer.configerer.POOLLER_STATE.RUN_BY_EACH_TASK&&this.removeTaskMapByHash(e.hash),this.appendTaskToExecuteQueue(e.hash,t)}}this.printLogMessage("4489844821, 離開了 syncTaskDispatcher()")}isWait4ResultTask(e){return void 0!==this.mapOfHashNCallbackWrapper[e]}}var _default=exports.default=InfinitePool;
|
package/lib/utiller/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _lodash=_interopRequireDefault(require("lodash"));var _cryptoJs=_interopRequireDefault(require("crypto-js"));var _configerer=require("configerer");var _exceptioner=_interopRequireDefault(require("../exceptioner"));var _momentTimezone=_interopRequireDefault(require("moment-timezone"));var _uuid=require("uuid");var _nodeHtmlParser=require("node-html-parser");String.format=function(){let param=[];for(let i=0,l=arguments.length;i<l;i++){param.push(arguments[i])}let statement=param[0];param.shift();return statement.replace(/\{(\d+)\}/g,function(m,n){return param[n]})};class Utiller{removeAttributeBy(object,predicate=value=>_lodash.default.isUndefined(value)){for(const key in object){if(predicate(object[key])){delete object[key]}}}getNumberOfNormalize(value,defaultValue=0){if(_lodash.default.isNumber(value))return value;try{const force=_lodash.default.toNumber(value);return _lodash.default.isNumber(force)&&!isNaN(force)?force:defaultValue}catch(error){Util.appendError(`448561684561 ${error.message}`)}return defaultValue}getStringOfNormalize(value,defaultValue="",trim=false){if(_lodash.default.isString(value))return trim?_lodash.default.trim(value):value;try{const force=_lodash.default.toString(value);return this.isOrEquals(force,"","undefined")?defaultValue:trim?_lodash.default.trim(force):force}catch(error){Util.appendError(`448616845453 ${error.message}`)}return defaultValue}isValidVersionOfString(versionName){if(this.isUndefinedNullEmpty(versionName)){return false}const numbers=versionName.split(".");for(const number of numbers){const toNum=_lodash.default.toNumber(number);if(!_lodash.default.isNumber(toNum)||isNaN(toNum))return false}return true}getSeparatorOfUnique(){return"\u0F0D\u0F0D"}getStringOfVersionIncrement(stringOfVersion,delta=1){const numbers=stringOfVersion.split(".").map(each=>_lodash.default.toNumber(each));const last=numbers.length-1;numbers[last]=numbers[last]+delta;return numbers.join(".")}setLocaleOfMoment(locale="en"){_momentTimezone.default.locale(locale)}getUuidOfV4(){return(0,_uuid.v4)()}constructor(){(0,_defineProperty2.default)(this,"mapOfIdNTimeoutId",{});(0,_defineProperty2.default)(this,"getEnvironment",()=>{return this.env});(0,_defineProperty2.default)(this,"isProductionEnvironment",()=>{return _lodash.default.isEqual(this.getEnvironment(),"prod")});(0,_defineProperty2.default)(this,"asyncUnitTaskFunction",(millionSec=2000,_funparam="\u9810\u8A2D\u7684param",errorSimulator)=>async(param=this.getRandomHash(10))=>{const randomValue=this.getRandomValue(millionSec,millionSec*1.2);try{const symbol=randomValue;this.appendInfo(`before executed ===> i'm symbol of ${symbol}, ready to be executed, inner param = ${_funparam}`);await this.syncDelay(randomValue);if(_lodash.default.isFunction(errorSimulator)&&errorSimulator(param))throw Error("force to made error happen");this.appendInfo(`after executed ===> i'm symbol of ${symbol}, the task cost ${randomValue} million-seconds ${param?`i hav params ===> ${param}`:""}`);return{randomValue,symbol,param}}catch(error){this.appendError(new Error(`asyncUnitTask() catch error ${error.message}`))}finally{this.appendInfo(`wow.... finally got you`)}});(0,_defineProperty2.default)(this,"test",word=>{return async()=>{await Util.syncDelay(3000);console.log("\u7D93\u904E\u4E86\u4E09\u79D2");await Util.syncDelay(4000);console.log("\u7D93\u904E\u4E86\u56DB\u79D2");await Util.syncDelay(5000);console.log("\u7D93\u904E\u4E86\u4E94\u79D2");await Util.syncDelay(6000);console.log("\u7D93\u904E\u4E86\u516D\u79D2");return`3423809432804 ${word}`}});(0,_defineProperty2.default)(this,"findLowestValue",(items,key="price")=>{const minPrice=_lodash.default.minBy(items,key)[key];return Math.floor(minPrice)});(0,_defineProperty2.default)(this,"findHighestValue",(items,key="price")=>{const maxPrice=_lodash.default.maxBy(items,key)[key];return Math.floor(maxPrice)});(0,_defineProperty2.default)(this,"getStringOfValueRange",(items,key="price",sign="$")=>{const minV=_lodash.default.minBy(items,key)[key];const maxV=_lodash.default.maxBy(items,key)[key];return maxV===minV?`$${minV}`:`${sign}${minV} - ${sign}${maxV}`});(0,_defineProperty2.default)(this,"getCallersName",()=>{let callerName;try{throw new Error}catch(e){let re=/(\w+)@|at (\w+) \(/g,st=e.stack,m;re.exec(st),m=re.exec(st);if(!_lodash.default.isNull(m))callerName=m[1]||m[2]}if(_lodash.default.startsWith("asyncGeneratorStep",callerName))callerName="";return callerName});(0,_defineProperty2.default)(this,"getRandomValue",(min,max)=>{min=Math.ceil(min);max=Math.floor(max);return Math.floor(Math.random()*(max-min+1))+min});(0,_defineProperty2.default)(this,"insertToArray",(array,index,...items)=>{if(!Array.isArray(array)){throw new Error("First argument must be an array.")}const insertAt=Math.max(0,Math.min(index+1,array.length));array.splice(insertAt,0,...items)});(0,_defineProperty2.default)(this,"getStringOfYearADConvertToMinguoYear",(gregorianYear,full=false)=>{const minguoYear=gregorianYear-1911;if(minguoYear>0){return`${full?"\u6C11\u570B":""}${minguoYear}${full?"\u5E74":""}`}else{return`${full?"\u6C11\u570B":""}前${Math.abs(minguoYear)}${full?"\u5E74":""}`}});(0,_defineProperty2.default)(this,"convertDateToTimestamp",date=>{return(0,_momentTimezone.default)(date).valueOf()});(0,_defineProperty2.default)(this,"measureExecutionTime",async(fn,...param)=>{const startTime=Date.now();await fn(...param);const endTime=Date.now();const durationInMilliseconds=endTime-startTime;const duration=_momentTimezone.default.duration(durationInMilliseconds,"milliseconds");const hours=Math.floor(duration.asHours());const minutes=duration.minutes();const seconds=duration.seconds();const milliseconds=duration.milliseconds();const totalSeconds=(durationInMilliseconds/1000).toFixed(3);this.appendInfo(`${hours}小時 ${minutes}分 ${seconds}.${milliseconds.toString().padStart(3,"0")}秒 (合計 ${totalSeconds} 秒)`)});(0,_defineProperty2.default)(this,"formatPriceWithCurrency",(number,locale)=>{if(typeof number!=="number"||typeof locale!=="string"){throw new TypeError("Invalid input: number must be a number and locale must be a string.")}return new Intl.NumberFormat(locale,{style:"currency",currency:new Intl.Locale(locale).maximize().currency||"USD",minimumFractionDigits:0}).format(number)});(0,_defineProperty2.default)(this,"formatPrice",(number,locale)=>{if(typeof number!=="number"){throw new TypeError("Invalid input: number must be a number.")}if(!locale){return number.toLocaleString("en-US")}return new Intl.NumberFormat(locale,{style:"currency",currency:new Intl.Locale(locale).maximize().currency||"USD",minimumFractionDigits:0}).format(number)});(0,_defineProperty2.default)(this,"generateUniversalKeywords",(sentence,maxLength=50,maxNgramLength=4)=>{if(!sentence||typeof sentence!=="string"){return[]}if(typeof _lodash.default==="undefined"){console.error("Lodash is not available. Please ensure it is imported.");return[]}let textToProcess=sentence.trim();let keywords=[];maxNgramLength=Math.max(2,maxNgramLength);if(textToProcess.length>maxLength){console.warn(`警告:輸入字串長度為 ${textToProcess.length},已根據 maxLength: ${maxLength} 截斷。`);textToProcess=textToProcess.substring(0,maxLength)}const englishWords=textToProcess.match(/[a-zA-Z]+/g)||[];englishWords.forEach(word=>{if(word.length>=2){keywords.push(word.toUpperCase());keywords.push(word.toLowerCase());const capitalized=word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();keywords.push(capitalized)}});const specKeywordsRegex=/\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;const specKeywords=(textToProcess.match(specKeywordsRegex)||[]).filter(k=>k.length>=2).map(k=>k.toLowerCase());keywords.push(...specKeywords);let cleanText=textToProcess.toLowerCase();cleanText=cleanText.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," ");cleanText=cleanText.replace(/[!@#$%^&*()_+={}\[\]:;"'<>,.?\/\\|`~]/g," ").replace(/系列|一組|單色|多款|套組|全套|專用|迷你|頂級|高品質|超閃|奢華|最新|款式|新款|超亮|的|與|和|閃|美甲/g," ").replace(/\s+/g,"").trim();const minLength=2;for(let len=minLength;len<=maxNgramLength;len++){for(let i=0;i<=cleanText.length-len;i++){const keyword=cleanText.substring(i,i+len);keywords.push(keyword)}}const finalKeywords=_lodash.default.chain(keywords).filter(k=>k.length>=2).filter(k=>k.length>2||!/^[\u4e00-\u9fa5a-z0-9]$/.test(k)).uniq().sortBy().value();return finalKeywords});(0,_defineProperty2.default)(this,"mutateIndexOfArrayItem",(array,object,index=0)=>{if(!Array.isArray(array)||!_lodash.default.isObject(object))return array;const currentIndex=_lodash.default.findIndex(array,item=>_lodash.default.isEqual(item,object));if(currentIndex===-1)return array;array.splice(currentIndex,1);const targetIndex=_lodash.default.clamp(index,0,array.length);array.splice(targetIndex,0,object);return array});(0,_defineProperty2.default)(this,"getArrayOfModifyObject2Index",(array,object,index=0)=>{if(!Array.isArray(array)||!_lodash.default.isObject(object))return array;const cloned=_lodash.default.cloneDeep(array);const currentIndex=_lodash.default.findIndex(cloned,item=>_lodash.default.isEqual(item,object));if(currentIndex===-1)return array;cloned.splice(currentIndex,1);const targetIndex=_lodash.default.clamp(index,0,cloned.length);cloned.splice(targetIndex,0,object);return cloned});(0,_defineProperty2.default)(this,"generateLabelValuePairsWithOrigin",(origin=[{label:"aa",value:1203},{label:"cc",value:1204},{label:"gg",value:2}],latest=["aa","bb"])=>{const usedValues=new Set(origin.map(o=>o.value));return _lodash.default.chain(latest).uniq().map(label=>{const originItem=_lodash.default.find(origin,{label});if(originItem){return{label,value:originItem.value}}let value;do{value=_lodash.default.random(2,999999999)}while(usedValues.has(value));usedValues.add(value);return{label,value}}).value()});(0,_defineProperty2.default)(this,"getItemsOfMarkMatching",(sourceArray=[],values=[],valueKey="value",flagKey="belong")=>{const valuesSet=new Set(values);return _lodash.default.map(sourceArray,item=>({...item,[flagKey]:valuesSet.has(item[valueKey])}))});(0,_defineProperty2.default)(this,"generateVariants",(arrays,labelSeparator="\uFF5C",valueSeparator="-")=>{const nonEmptyArrays=arrays.filter(arr=>arr.length>0);if(nonEmptyArrays.length===0)return[];if(nonEmptyArrays.length===1){return nonEmptyArrays[0].map(item=>({label:item.label,value:item.value}))}const combinations=_lodash.default.reduce(nonEmptyArrays,(acc,curr)=>_lodash.default.flatMap(acc,a=>curr.map(b=>[...a,b])),[[]]);return combinations.map(comb=>({label:comb.map(item=>item.label).join(labelSeparator),value:comb.map(item=>item.value).join(valueSeparator)}))});(0,_defineProperty2.default)(this,"renameKeysInArray",(arr,...keyMappings)=>{const mapping=Object.fromEntries(keyMappings);return arr.map(item=>_lodash.default.mapKeys(item,(value,key)=>mapping[key]||key))});(0,_defineProperty2.default)(this,"getArrayOfMergeBySpecificId",(array1,array2,idKey="id")=>{if(!Array.isArray(array2))return array1;const map2=_lodash.default.keyBy(array2,item=>_lodash.default.get(item,idKey));return array1.map(item=>{const id=_lodash.default.get(item,idKey);const match=map2[id];return match?_lodash.default.merge({},item,match):item})});(0,_defineProperty2.default)(this,"toPercentageDecimal",num=>{if(_lodash.default.isNil(num))return 1;if(_lodash.default.isString(num)){num=num.replace(/%/g,"").trim()}const parsed=_lodash.default.toNumber(num);if(!_lodash.default.isFinite(parsed))return 1;return _lodash.default.round(parsed/100,10)});(0,_defineProperty2.default)(this,"getNumberOfMultiplyCeil",(a,b,precision=0)=>{const factor=Math.pow(10,precision);return Math.ceil(a*b*factor)/factor});(0,_defineProperty2.default)(this,"generateGoogleCalendarLink",({title,startDate,startTime,endDate,endTime,location,details})=>{const startDateTime=(0,_momentTimezone.default)(`${startDate} ${startTime}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDTHHmmss");const endDateTime=(0,_momentTimezone.default)(`${endDate} ${endTime}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDTHHmmss");const params=new URLSearchParams;if(title)params.append("text",title);if(startDateTime&&endDateTime)params.append("dates",`${startDateTime}/${endDateTime}`);if(details)params.append("details",details);if(location)params.append("location",location);params.append("ctz","Asia/Taipei");params.append("trp","true");return`https://calendar.google.com/calendar/r/eventedit?${params.toString()}`});(0,_defineProperty2.default)(this,"generateTimeTreeLink",({title,startDate,startTime,endDate,endTime,location,memo})=>{const params=new URLSearchParams;if(title)params.append("title",title);if(startDate)params.append("start_date",startDate.replace(/\//g,"-"));if(startTime)params.append("start_time",startTime);if(endDate)params.append("end_date",endDate.replace(/\//g,"-"));if(endTime)params.append("end_time",endTime);if(location)params.append("location",location);if(memo)params.append("memo",memo);return`https://timetreeapp.com/plans/new?${params.toString()}`});(0,_defineProperty2.default)(this,"generateIcsContent",({title,startDate,startTime,endDate,endTime,location,details})=>{const startDateTime=_momentTimezone.default.tz(`${startDate} ${startTime}`,"YYYY/MM/DD HH:mm","Asia/Taipei").format("YYYYMMDDTHHmmss");const endDateTime=_momentTimezone.default.tz(`${endDate} ${endTime}`,"YYYY/MM/DD HH:mm","Asia/Taipei").format("YYYYMMDDTHHmmss");const stamp=(0,_momentTimezone.default)().utc().format("YYYYMMDDTHHmmss")+"Z";const uid=Date.now().toString(36)+Math.random().toString(36).substring(2,5)+"@gemini-app.com";const escapeIcs=text=>text.replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n");const lines=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//Gemini AI//NONSGML v1.0//EN","BEGIN:VEVENT",`UID:${uid}`,`DTSTAMP:${stamp}`];if(startDateTime)lines.push(`DTSTART;TZID=Asia/Taipei:${startDateTime}`);if(endDateTime)lines.push(`DTEND;TZID=Asia/Taipei:${endDateTime}`);if(title)lines.push(`SUMMARY:${escapeIcs(title)}`);if(location)lines.push(`LOCATION:${escapeIcs(location)}`);if(details)lines.push(`DESCRIPTION:${escapeIcs(details)}`);lines.push("END:VEVENT","END:VCALENDAR");return lines.join("\r\n")});(0,_defineProperty2.default)(this,"generateAllCalendarLinks",event=>{const googleLink=this.generateGoogleCalendarLink(event);const timeTreeEvent={...event,memo:event.details};const timeTreeLink=this.generateTimeTreeLink(timeTreeEvent);const icsContent=this.generateIcsContent(event);const icsLink=`data:text/calendar;charset=utf8,${encodeURIComponent(icsContent)}`;return{google:googleLink,timeTree:timeTreeLink,ics:icsLink}});(0,_defineProperty2.default)(this,"getArrayOfMappingRef",(current,reference)=>{return _lodash.default.map(current,currentObj=>{const referenceObj=_lodash.default.find(reference,{value:currentObj.value});return referenceObj?_lodash.default.merge({},currentObj,referenceObj):currentObj})});(0,_defineProperty2.default)(this,"areAllValuesTheSameOnKeys",(array,...keys)=>{if(!array||array.length<=1||keys.length===0){return true}for(const keyName of keys){const firstValue=array[0]?.[keyName];const isCurrentKeySame=_lodash.default.every(array,item=>{return item[keyName]===firstValue});if(!isCurrentKeySame){return false}}return true});this.init();this.env="dev"}performActionWithoutTimingIssue(task=()=>true,wait=10){this.syncDelay(wait).then(()=>task())}executeTimeoutTask(functionOfAsyncTask,ms=1000,id=this.getRandomHash(),...params){const self=this;const idOfCurrentTimeoutTask=this.mapOfIdNTimeoutId[id];if(idOfCurrentTimeoutTask)clearTimeout(idOfCurrentTimeoutTask);const idOfTimeoutTask=setTimeout(async(...param)=>{await functionOfAsyncTask();delete self.mapOfIdNTimeoutId[id]},ms,...params);self.mapOfIdNTimeoutId[id]=idOfTimeoutTask}printLogMessage(message,error=false,...infos){if(!this.isProductionEnvironment()){if(error){this.appendError(message,...infos)}else{this.appendInfo(message,...infos)}}}init(){}setEnvironment(env){this.env=env}appendInfo(...logs){if(this.isProductionEnvironment())return;console.log(...logs)}appendError(...logs){if(this.isProductionEnvironment())return;console.error(...logs)}async syncDelay(delayInms=2000){return new Promise(resolve=>{setTimeout(()=>{resolve(delayInms)},delayInms)})}startWithRegex(string="",rule="."){let pattern=new RegExp(`^${rule}`,"i");return pattern.test(string)}accumulate(target,conditions){let beginning=target;for(const condition of conditions){if(condition!==undefined&&_lodash.default.isFunction(condition)){beginning=condition(beginning)}}return beginning}isOrEquals(target,...several){for(const each of several){if(_lodash.default.isEqual(target,each))return true}return false}isAndEquals(...predicates){for(const predicate of predicates){if(!predicate()){return false}}return true}getStringOfHeadMatch(string,regex,flag="g"){const result=string.match(new RegExp(regex,flag));return this.isUndefinedNullEmpty(result)?undefined:result[0]}or(...booleans){for(const boo of booleans){if(_lodash.default.isBoolean(boo)&&boo)return true}return false}and(...booleans){for(const boo of booleans){if(!!!boo)return false}return true}nth(array,index=-1){return _lodash.default.nth(array,index%_lodash.default.size(array))}getExistOne(...candidates){for(const candidate of candidates){if(candidate)return candidate}}getStringOfDropHeadSign(string,sign){return _lodash.default.dropWhile(Array.from(string),each=>_lodash.default.isEqual(each,sign)).join("")}isAndWith(self,predicate,...several){for(const each of several){if(!predicate(self,each))return false}return true}async syncDelayRandom(min=3000,max=5000){const random=this.getRandomValue(min,max);await this.syncDelay(random);return random}has(collection,item,precisely=false){if(_lodash.default.isArray(collection)){if(precisely)return _lodash.default.findIndex(collection,each=>_lodash.default.isEqual(item,each))>-1;else return _lodash.default.indexOf(collection,item)>-1}if(_lodash.default.isObject(item)){return collection[item]}if(_lodash.default.isString(collection)){return collection.indexOf(item)>-1}return false}containsBy(array,item){return _lodash.default.findIndex(array,each=>_lodash.default.isEqual(each,item))>=0}getStringOfInsideParentheses(string,rule=`.`){return this.getStringOfRule(string,rule,"(",")")}getStringOfInsideBrackets(string,rule=`.`){return this.getStringOfRule(string,rule,"[","]")}getStringOfInsideBraces(string,rule=`.`){return this.getStringOfRule(string,rule,"{","}")}getStringOfRule(string,rule=`.`,left="{",right="}"){return this.getStringOfHeadMatch(string,`(?<=\\${left})${rule}+?(?=\\${right})`)}getRandomHash(length=20){const randomBytes=_cryptoJs.default.lib.WordArray.random(length);const base64String=_cryptoJs.default.enc.Base64.stringify(randomBytes);return base64String.substring(0,length)}getRandomHashV2(length){const characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let result="";for(let i=0;i<length;i++){const randomIndex=Math.floor(Math.random()*characters.length);result+=characters.charAt(randomIndex)}return result}getEncryptString(texts,key=_configerer.configerer.ENCRYPT_KEY,alwaysTheSame=false){const maxLengthOfKey=22;if(key.length>maxLengthOfKey)throw new _exceptioner.default(8010,_lodash.default.size(key));const ivOfCrypto=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");const keyOfCrypto=alwaysTheSame?_cryptoJs.default.enc.Base64.parse(`${key}${_lodash.default.range(0,maxLengthOfKey-key.length).join("")}`):key;return _cryptoJs.default.AES.encrypt(texts,keyOfCrypto,{iv:ivOfCrypto}).toString()}getEncryptStringV2(texts,key=_configerer.configerer.ENCRYPT_KEY,alwaysTheSame=false){const maxLengthOfKey=22;if(key.length>maxLengthOfKey)throw new _exceptioner.default(8010,_lodash.default.size(key));const ivOfCrypto=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");const keyOfCrypto=alwaysTheSame?_cryptoJs.default.enc.Base64.parse(`${key}${_lodash.default.range(0,maxLengthOfKey-key.length).join("")}`):key;return _cryptoJs.default.AES.encrypt(JSON.stringify({content:texts}),keyOfCrypto,{iv:ivOfCrypto}).toString()}getDecryptString(ciphertext,key=_configerer.configerer.ENCRYPT_KEY){const maxLengthOfKey=22;if(key.length>maxLengthOfKey)throw new _exceptioner.default(8010,_lodash.default.size(key));const ivOfCrypto=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const value=_cryptoJs.default.AES.decrypt(ciphertext,key,{iv:ivOfCrypto}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(value.trim()))return value}catch(e){}return _cryptoJs.default.AES.decrypt(ciphertext,_cryptoJs.default.enc.Base64.parse(`${key}${_lodash.default.range(0,maxLengthOfKey-key.length).join("")}`),{iv:ivOfCrypto}).toString(_cryptoJs.default.enc.Utf8)}getDecryptStringV2(ciphertext,key=_configerer.configerer.ENCRYPT_KEY){const maxLengthOfKey=22;if(key.length>maxLengthOfKey)throw new _exceptioner.default(8010,_lodash.default.size(key));const ivOfCrypto=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const stringOfObj=_cryptoJs.default.AES.decrypt(ciphertext,key,{iv:ivOfCrypto}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(stringOfObj.trim())){const obj=JSON.parse(stringOfObj);return obj.content}}catch(e){}const stringOfObj=_cryptoJs.default.AES.decrypt(ciphertext,_cryptoJs.default.enc.Base64.parse(`${key}${_lodash.default.range(0,maxLengthOfKey-key.length).join("")}`),{iv:ivOfCrypto}).toString(_cryptoJs.default.enc.Utf8);const obj=JSON.parse(stringOfObj);return obj.content}getFirebaseFormattedString(texts){return _lodash.default.replace(texts,/[\.\#\$\[\]]/g,"-").trim()}formalizeNamesToArray(singerString){let normalize=singerString;normalize=normalize.split(_configerer.configerer.SEPARATE_TONE_SINGER)[0].trim();normalize=_lodash.default.replace(normalize,/[,\/#!$%\^&\*;:{}=_`、~()()]/g,"_").trim();normalize=this.getFirebaseFormattedString(normalize);normalize=_lodash.default.replace(normalize,/\_\_+/g,"_").trim();while(_lodash.default.endsWith(normalize,"_")){normalize=normalize.slice(0,-1).trim()}const words=normalize.split("_");return _lodash.default.map(words,word=>_lodash.default.trim(word))}getShuffledArrayWithLimitCountHighPerformance(arr,n){let result=new Array(n),len=arr.length,taken=new Array(len);if(n>len)n=len;while(n--){let x=Math.floor(Math.random()*len);result[n]=arr[x in taken?taken[x]:x];taken[x]=--len in taken?taken[len]:len}return result}getFileNameFromPath(path,extension=false){const segments=path.split("/");const target=segments.pop();return extension?target:target.split(".").shift()}getFileNameExtensionFromPath(path){const name=path.split("/").pop();return name}getPathOfReplaceLastDir(path,name){const split=path.split("/");split.pop();split.push(name);return split.join("/")}getExtensionFromPath(path){const name=path.split("/").pop();const segments=name.split(".");return _lodash.default.size(segments)>1?segments.pop():""}getFolderPathOfSpecificPath(path){const split=path.split("/");split.pop();return split.join("/")}getFolderNameOfFilePath(path){if(this.isValidFilePath(path)){const splits=path.split("/");return _lodash.default.nth(splits,-2)}else{throw new _exceptioner.default(9999,`64255615 path is not valid '${path}'`)}}isUnderTargetPath(absolute,target){const segments=absolute.split("/");return this.has(segments,target)}getFileDirPath(path,slash=true){return _lodash.default.join(_lodash.default.initial(_lodash.default.split(path,"/")),"/")+(slash?"/":"")}isPathEqualsFileType(path,type){const extension=path.split(".").pop();return _lodash.default.isEqual(extension,type)}isValidFilePath(path){const extension=this.getExtensionFromPath(path);return _lodash.default.size(extension)>0}getArrayOfSize(array,n=1){return _lodash.default.take(array,n)}getShuffledArrayWithLimitCount(arr,n){return this.getShuffledArrayWithLimitCountHighPerformance(arr,n)}getRandomItemOfArray(array,...ignores){if(!_lodash.default.isArray(array))throw new _exceptioner.default(9999,`why are you so stupid, typeof array should be array, not ==> ${array} `);const filter=_lodash.default.without(array,...ignores);const target=_lodash.default.size(filter)>0?filter:array;const item=this.getShuffledArrayWithLimitCount(target,1);return item.length>0?item[0]:undefined}appendMapOfKeyArray(object,key,...value){if(this.isUndefinedNullEmpty(object[key])){object[key]=[...value]}else{object[key].push(...value)}}getMergedArrayBy(major=[],sub=[],key){if(!key||major.length===0||sub.length===0){return[...major]}const subMap=new Map(sub.map(item=>[item[key],item]));return major.map(majorItem=>{const subItem=subMap.get(majorItem[key]);return{...(subItem||{}),...majorItem}})}getShuffledItemFromArray(arr){let shuffled=_lodash.default.shuffle(arr);return shuffled[0]}getShuffledArray(arr){let shuffled=_lodash.default.shuffle(arr);return shuffled}isJson(item){item=typeof item!=="string"?JSON.stringify(item):item;try{item=JSON.parse(item)}catch(e){return false}if(typeof item==="object"&&item!==null){return true}return false}getObjectValue(obj){if(_lodash.default.isObject(obj)){return Object.values(obj)[0]}return""}getObject(key,value){const object={};object[key]=value;return object}getStringOfCreditCardFormatted(string=0){const inputValue=string.replace(/\D/g,"");const result=inputValue.replace(/(\d{4})(?=\d)/g,"$1-");return result.slice(0,19)}getObjectKey(obj){if(_lodash.default.isObject(obj)){return Object.keys(obj)[0]}return""}printf(){this.appendInfo("i can use in web || react.js")}isKeywordRule(constraint){if(_lodash.default.isUndefined(constraint)||_lodash.default.isEmpty(constraint))throw new Error("PARAMS CAN NOT BE EMPTY");if(!_lodash.default.isString(constraint))throw new Error("PARAMS SHOULD BE STRING");if(constraint.length>20)throw new Error("EXCEED 20 WORDS IS NOT ALLOWED")}getItsKeyByValue(object,value){return Object.keys(object).find(key=>object[key]===value)}startWiths(string,key=[]){for(const _key of key){if(_lodash.default.startsWith(string,_key)){return true}}return false}replaceAll(string,patten,to){return _lodash.default.replace(string,new RegExp(`${patten}`,`g`),to)}replaceAllWithSets(string="",...patterns){let after=string;for(const pattern of patterns){if(this.isOrEquals(undefined,pattern.from,pattern.to)){throw(0,_exceptioner.default)(9999,`from or to can't be empty`)}after=this.replaceAll(after,pattern.from,pattern.to)}return after}replaceArrayByContentIndex(array,current,latest){const index=_lodash.default.indexOf(array,current);array[index]=latest}deepFlat(collection,sign="_"){let result="";const stack=[[collection,""]];while(stack.length>0){const[current,prefix]=stack.pop();if(_lodash.default.isArray(current)){for(let i=current.length-1;i>=0;i--){stack.push([current[i],prefix])}}else if(_lodash.default.isObject(current)){const keys=Object.keys(current);for(let i=keys.length-1;i>=0;i--){const key=keys[i];stack.push([current[key],prefix+key+sign])}}else{const valueString=_lodash.default.trim(String(current));if(valueString.length>0){result+=(result.length>0?sign:"")+prefix+valueString}else if(prefix.length>0&&result.length>0){result+=sign}else if(prefix.length>0&&result.length===0){result+=prefix.endsWith(sign)?prefix.slice(0,-sign.length):prefix}}}if(result.endsWith(sign)){result=result.slice(0,-sign.length)}return result}joinEscapeChar(str){return(str+"").replace(/[\\"']/g,"\\$&").replace(/\u0000/g,"\\0")}getValueWithIntegerType(whatever){try{const value=parseInt(whatever);return isNaN(value)?0:value}catch(error){return 0}}getValueOfPriority(...compares){for(const compare of compares){if(!this.isUndefinedNullEmpty(compare))return compare}return undefined}async asyncPool(poolLimit,array,iteratorFn){const ret=[];const executing=[];for(const item of array){const p=Promise.resolve().then(()=>{return iteratorFn(item,array)});ret.push(p);if(poolLimit<=array.length){const e=p.then(()=>{return executing.splice(executing.indexOf(e),1)});executing.push(e);if(executing.length>=poolLimit){await Promise.race(executing)}}}return Promise.all(ret)}getAttrValueInSequence(info,...attrs){for(const attr of attrs){if(!_lodash.default.isEmpty(info[attr])){return info[attr]}}return info}toDBC(txtstring){var tmp="";for(var i=0;i<txtstring.length;i++){if(txtstring.charCodeAt(i)===32){tmp=tmp+String.fromCharCode(12288)}if(txtstring.charCodeAt(i)<127){tmp=tmp+String.fromCharCode(txtstring.charCodeAt(i)+65248)}}return tmp}toCDB(str){var tmp="";for(var i=0;i<str.length;i++){if(str.charCodeAt(i)===12288){tmp+=String.fromCharCode(str.charCodeAt(i)-12256);continue}if(str.charCodeAt(i)>65280&&str.charCodeAt(i)<65375){tmp+=String.fromCharCode(str.charCodeAt(i)-65248)}else{tmp+=String.fromCharCode(str.charCodeAt(i))}}return tmp}findIndexes(array,predicate){const indexes=[];let hasIndex=true;let indexOfLatest=0;while(hasIndex){indexOfLatest=_lodash.default.findIndex(array,predicate,indexOfLatest+1);if(indexOfLatest>-1){indexes.push(indexOfLatest)}else{hasIndex=false}}return indexes}getSliceArrayOfSpecificIndexes(array,...indexes){const items=[];const size=_lodash.default.size(array);for(const index of indexes){if(!_lodash.default.isNumber(index))throw new _exceptioner.default(9999,`59941278 index should be number => ${index}, ${array}`);if(index>size-1)throw new _exceptioner.default(9999,`5994123 index=>${index} is not valid, exceed than array size=${size}, ${array}`);items.push(_lodash.default.nth(array,index))}return items}indexesOf(arr,val){const indexes=[];let i=-1;while((i=arr.indexOf(val,i+1))!==-1){indexes.push(i)}return indexes}getIndexOfContext(context,stmt){return _lodash.default.findIndex(context,per=>{return _lodash.default.isEqual(per.trim(),stmt)})}toOneLineString(string){return _lodash.default.join(_lodash.default.split(string,"\n"),"")}toSpaceLessString(string){return _lodash.default.split(string,"").map(each=>_lodash.default.trim(each)).join("")}toNewLineLessString(string){return _lodash.default.split(string,"\n").map(each=>_lodash.default.trim(each)).join("")}exist(obj){return!_lodash.default.isNull(obj)&&!_lodash.default.isUndefined(obj)}isUndefinedNullEmpty(obj){const first=obj===undefined||obj===null;const second=_lodash.default.isString(obj)||_lodash.default.isArray(obj)||_lodash.default.isObject(obj)?_lodash.default.isEmpty(obj):false;return first||second}isAndConditionOfUndefinedNullEmpty(...objs){for(const obj of objs){if(!this.isUndefinedNullEmpty(obj))return false}return true}isOrConditionOfUndefinedNullEmpty(...objs){for(const obj of objs){if(this.isUndefinedNullEmpty(obj))return true}return false}getStringHandledByEachLine(string,predict=(segment,index,segments)=>true,separator="\n"){const segments=string.split(separator);for(const segment of segments){predict(segment,_lodash.default.indexOf(segments,segment),segments)}return segments.join(separator)}getSegmentsOfEachLine(string){return string.split("\n")}getNormalizedStringEndWith(string,predicate){string=this.toCDB(string);predicate=this.toCDB(predicate);const after=_lodash.default.join(_lodash.default.dropRightWhile(string,each=>!_lodash.default.isEqual(each,predicate)),"");return _lodash.default.isEmpty(after)?string:after}getNormalizedStringNotStartWith(string,...predicate){string=this.toCDB(string);const after=_lodash.default.join(_lodash.default.dropWhile(string,each=>this.has(predicate,each)),"");return _lodash.default.isEmpty(after)?string:after}getNormalizedStringNotEndWith(string,...predicate){string=this.toCDB(string);const after=_lodash.default.join(_lodash.default.dropRightWhile(string,each=>this.has(predicate,each)),"");return _lodash.default.isEmpty(after)?string:after}getTodayTimeFormat(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YYYY-MM-DD")}getCustomFormatOfDatePresent(ts,format="YY/MM"){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format(format)}getSimpleDateYYMMDDFormat(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YY/MM/DD")}getSimpleTimeYYMMDDHHmmFormat(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YY/MM/DD HH:mm")}getECPayCurrentTimeFormat(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatV2(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatYMDHM(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm")}getCurrentTimeFormatYMDHMS(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormat(ts){return(0,_momentTimezone.default)(ts?ts:this.getCurrentTimeStamp()).format("YYYY-MM-DD-HH-mm-ss")}getCurrentMillionSecTimeFormat(ts){return(0,_momentTimezone.default)(ts?ts:undefined).format("YYYY-MM-DD-HH-mm-ss-SSS")}isBetweenTimeStamp(target=this.getCurrentTimeStamp(),min,max){return(0,_momentTimezone.default)(target).isBetween(min,max)}isBeforeTimeStamp(target=this.getCurrentTimeStamp(),time){return(0,_momentTimezone.default)(target).isBefore(time)}isAfterTimeStamp(target=this.getCurrentTimeStamp(),time){return(0,_momentTimezone.default)(target).isAfter(time)}formatTimeByLocale(ts,location="zh-TW",timezone="Asia/Taipei",use24Hour=true){_momentTimezone.default.locale(location);const m=(0,_momentTimezone.default)(ts).tz(timezone);const formatStr=use24Hour?"YYYY/MM/DD HH:mm":"YYYY/MM/DD hh:mm A";return m.format(formatStr)}getTimeStampWithConditions(param={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},target=this.getCurrentTimeStamp()){let base=(0,_momentTimezone.default)(target);for(const each in param){const number=param[each];const unit=each;if(number>0){base=base.add(number,unit)}if(number<0){base=base.subtract(Math.abs(number),unit)}}return base.valueOf()}getTimeStampByStringFormat(string){return this.getTimeStampFromSpecificFormat(string,"YYYY/MM/DD HH:mm:ss").valueOf()}getTimeStampFromSpecificFormat(string,format="YYYY/MM/DD HH:mm:ss"){return(0,_momentTimezone.default)(string,format).valueOf()}getTimeStampFromECPayStringFormat(string){return this.getTimeStampFromSpecificFormat(string,"YYYY/MM/DD HH:mm:ss").valueOf()}getTimeFormatOfDurationToMillionSecond(duration){return _momentTimezone.default.utc(duration).format("HH\u5C0F\u6642mm\u5206\u9418ss\u79D2SSS")}getTimeFormatOfDurationToSecond(duration){return _momentTimezone.default.utc(duration).format("HH\u5C0F\u6642mm\u5206\u9418ss\u79D2")}getTimeFormatOfDurationToDay(duration){return _momentTimezone.default.utc(duration).format("DD\u5929HH\u5C0F\u6642mm\u5206\u9418ss\u79D2")}getChineseTimeFormat(ts){_momentTimezone.default.locale("zh-TW");return(0,_momentTimezone.default)(ts).format("LLLL")}getMinuteFormatOfDuration(ds){return _momentTimezone.default.duration(ds).asMinutes()}getSecondFormatOfDuration(ds){return _momentTimezone.default.duration(ds).asSeconds()}getDayFormatOfDuration(ds){return _momentTimezone.default.duration(ds).asDays()}getDurationOfMillionSec(dateOrTimeStamp){const currentTimestamp=this.getCurrentTimeStamp();const targetTimeStamp=(0,_momentTimezone.default)(dateOrTimeStamp).valueOf();const queue=_lodash.default.sortBy([{ts:currentTimestamp},{ts:targetTimeStamp}],each=>each.ts).map(each=>each.ts);let after=(0,_momentTimezone.default)(queue.pop());let before=(0,_momentTimezone.default)(queue.shift());let duration=_momentTimezone.default.duration(after.diff(before));let ms=duration.asMilliseconds();return ms}getCurrentTimeStamp(){return(0,_momentTimezone.default)().valueOf()}isStringContainInLines(context,key){for(let each of _lodash.default.split(context,"\n")){if(this.has(each,key))return true}return false}camel(...words){return _lodash.default.camelCase(words.join("_"))}upperCamel(...words){return _lodash.default.upperFirst(this.camel(...words))}array2Obj(array){const obj={};for(const each of array){obj[`${this.getObjectKey(each)}`]=this.getObjectValue(each)}return obj}arrayToObjWith(array,predicate){const obj={};for(const item of array){const key=predicate(item);const content=obj[key];if(content&&_lodash.default.isArray(content)){content.push(item)}else{obj[key]=[item]}}return obj}isEmptyString(string){return _lodash.default.isEqual(_lodash.default.trim(string),"")}mergeObject(...obj){return _lodash.default.merge(...obj)}syncSetTimeout(func,ms,callback=()=>{}){(function sync(done){if(!done){setTimeout(function(){func();sync(true)},ms);return}callback()})()}mergeArrayBy(identifier="id",...array){return Object.values(array.flat().reduce((acc,item)=>{if(item[identifier])acc[item[identifier]]={...(acc[item[identifier]]||{}),...item};return acc},{}))}getRelativePath(pathName,rootName){return _lodash.default.dropWhile(pathName,(each,index)=>{return _lodash.default.isEqual(each,rootName[index])}).join("")}dropItemsByIndex(array,from,end){_lodash.default.remove(array,(value,index,array)=>end>=index&&index>=from)}isEven(n){return n%2===0}isOdd(n){return Math.abs(n%2)===1}enrichZhTw(){_momentTimezone.default.locale("zh-tw",{months:"\u4E00\u6708_\u4E8C\u6708_\u4E09\u6708_\u56DB\u6708_\u4E94\u6708_\u516D\u6708_\u4E03\u6708_\u516B\u6708_\u4E5D\u6708_\u5341\u6708_\u5341\u4E00\u6708_\u5341\u4E8C\u6708".split("_"),monthsShort:"1\u6708_2\u6708_3\u6708_4\u6708_5\u6708_6\u6708_7\u6708_8\u6708_9\u6708_10\u6708_11\u6708_12\u6708".split("_"),weekdays:"\u661F\u671F\u65E5_\u661F\u671F\u4E00_\u661F\u671F\u4E8C_\u661F\u671F\u4E09_\u661F\u671F\u56DB_\u661F\u671F\u4E94_\u661F\u671F\u516D".split("_"),weekdaysShort:"\u5468\u65E5_\u5468\u4E00_\u5468\u4E8C_\u5468\u4E09_\u5468\u56DB_\u5468\u4E94_\u5468\u516D".split("_"),weekdaysMin:"\u65E5_\u4E00_\u4E8C_\u4E09_\u56DB_\u4E94_\u516D".split("_"),longDateFormat:{LT:"Ah\u9EDEmm\u5206",LTS:"Ah\u9EDEm\u5206s\u79D2",L:"YYYY-MM-DD",LL:"YYYY\u5E74MMMD\u65E5",LLL:"YYYY\u5E74MMMD\u65E5Ah\u9EDEmm\u5206",LLLL:"YYYY\u5E74MMMD\u65E5ddddAh\u9EDEmm\u5206",l:"YYYY-MM-DD",ll:"YYYY\u5E74MMMD\u65E5",lll:"YYYY\u5E74MMMD\u65E5Ah\u9EDEmm\u5206",llll:"YYYY\u5E74MMMD\u65E5ddddAh\u9EDEmm\u5206"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(h,meridiem){let hour=h;if(hour===12){hour=0}if(meridiem==="\u51CC\u6668"||meridiem==="\u65E9\u4E0A"||meridiem==="\u4E0A\u5348"){return hour}else if(meridiem==="\u4E0B\u5348"||meridiem==="\u665A\u4E0A"){return hour+12}else{return hour>=11?hour:hour+12}},meridiem:function(hour,minute,isLower){const hm=hour*100+minute;if(hm<600){return"\u51CC\u6668"}else if(hm<900){return"\u65E9\u4E0A"}else if(hm<1130){return"\u4E0A\u5348"}else if(hm<1230){return"\u4E2D\u5348"}else if(hm<1800){return"\u4E0B\u5348"}else{return"\u665A\u4E0A"}},calendar:{sameDay:function(){return this.minutes()===0?"[\u4ECA\u5929]Ah[\u9EDE\u6574]":"[\u4ECA\u5929]LT"},nextDay:function(){return this.minutes()===0?"[\u660E\u5929]Ah[\u9EDE\u6574]":"[\u660E\u5929]LT"},lastDay:function(){return this.minutes()===0?"[\u6628\u5929]Ah[\u9EDE\u6574]":"[\u6628\u5929]LT"},nextWeek:function(){let startOfWeek,prefix;startOfWeek=(0,_momentTimezone.default)().startOf("week");prefix=this.diff(startOfWeek,"days")>=7?"[\u4E0B]":"[\u672C]";return this.minutes()===0?prefix+"dddA\u9EDE\u6574":prefix+"dddAh\u9EDEmm"},lastWeek:function(){let startOfWeek,prefix;startOfWeek=(0,_momentTimezone.default)().startOf("week");prefix=this.unix()<startOfWeek.unix()?"[\u4E0A]":"[\u672C]";return this.minutes()===0?prefix+"dddAh\u9EDE\u6574":prefix+"dddAh\u9EDEmm"},sameElse:"LL"},ordinalParse:/\d{1,2}(日|月|周)/,ordinal:function(number,period){switch(period){case"d":case"D":case"DDD":return number+"\u65E5";case"M":return number+"\u6708";case"w":case"W":return number+"\u5468";default:return number}},relativeTime:{future:"%s\u5185",past:"%s\u524D",s:"\u5E7E\u79D2",m:"1 \u5206\u9418",mm:"%d \u5206\u9418",h:"1 \u5C0F\u6642",hh:"%d \u5C0F\u6642",d:"1 \u5929",dd:"%d \u5929",M:"1 \u500B\u6708",MM:"%d \u4E2A\u6708",y:"1 \u5E74",yy:"%d \u5E74"},week:{dow:1,doy:4}})}getVisibleOrHidden(judgement){return{visibility:judgement?"visible":"hidden"}}getNumberOfPercentageToFloat(percentage){let cleanedPercentage=percentage.replace("%","");let floatNumber=parseFloat(cleanedPercentage)/100;return floatNumber}getVisibleOrNone(judgement,flex=false){return{display:judgement?flex?"flex":"inherit":"none"}}stringToInteger(string){string=_lodash.default.toUpper(string);switch(string){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(integer){switch(integer){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(array,...rules){const newbies=[];for(const each of array){const object={};for(const rule of rules){const func=rule.func?rule.func:stmt=>stmt;object[rule.to]=this.isUndefinedNullEmpty(rule.from)||!_lodash.default.isObject(each)?func(each):func(each[rule.from])}newbies.push(object)}return newbies}exeAll(collection,...funcs){if(_lodash.default.isArray(collection)){for(const each of collection){for(const func of funcs){func(each)}}}else if(_lodash.default.isObject(collection)){for(const each in collection){for(const func of funcs){collection[each]=func(collection[each])}}}else{throw new _exceptioner.default(9999,`7841212 type can't be array or object`)}return collection}getObjectWhile(major,minor,predicate=target=>true){const collection={};for(const key in major){if(predicate(major,minor,key)){collection[key]=major[key]}}return collection}getIntersectionObject(objOfMajor,objOfMinor){return this.getObjectWhile(objOfMajor,objOfMinor,(major,minor,key)=>minor[key]!==undefined)}getDifferenceObject(objOfMajor,objOfMinor){return this.getObjectWhile(objOfMajor,objOfMinor,(major,minor,key)=>minor[key]===undefined)}isObjectContainAndEqual(targetObject,mainObject){let equal=true;for(const key in targetObject){if(mainObject[key]===undefined||mainObject[key]!==targetObject[key]){equal=false;break}}return equal}getStringOfPop(string,separator){if(!_lodash.default.isString(string)){throw new _exceptioner.default(9999,`445115,type should be string but ==> ${typeof string}`)}const segments=string.split(separator);segments.pop();return segments.join(separator)}getStringOfShift(string,separator){if(!_lodash.default.isString(string)){throw new _exceptioner.default(9999,`445116,type should be string but ==> ${typeof string}`)}const segments=string.split(separator);segments.shift();return segments.join(separator)}toObjectWithAttributeKey(array,attrKeyOfPK){const object={};for(const each of array){const pk=each[attrKeyOfPK];if(this.isUndefinedNullEmpty(pk)){throw new _exceptioner.default(9999,`48157232 pk can't be empty => '${pk}'`)}object[pk]=each}return object}getObjectOfArraySpecifyAttr(array,attr){return this.toObjectWithAttributeKey(array,attr)}getStateOfStringContainsSign(string,...signs){for(const sign of signs){if(this.has(string,sign)){return{exists:true,sign}}}return{exists:false}}constraintOfParam(collection,type,...others){let result=false;const validOfOthersCondition=_lodash.default.isEmpty(others)?true:this.and(...others.map(each=>each.logic));switch(type){case"array":if(_lodash.default.isArray(collection)&&validOfOthersCondition)result=true;break;case"object":if(_lodash.default.isObject(collection)&&validOfOthersCondition)result=true;break;case"string":if(_lodash.default.isString(collection)&&validOfOthersCondition)result=true;break;case"number":if(_lodash.default.isNumber(collection)&&validOfOthersCondition)result=true;break;case"other":if(validOfOthersCondition)return true}const stringOfRules=_lodash.default.isEmpty(others)?"":`, ${others.map(each=>each.message).join(" | ")}`;if(result===false){throw new _exceptioner.default(9999,`7474423 type should be ${type} but get '${typeof type}' ${stringOfRules} `)}}getSliceArrayWithMutate(array,n){const slice=_lodash.default.remove(array,(each,index)=>index<n);return slice}getArrayOfInteraction(one,two){return one.filter(element=>!two.includes(element))}getArrayOfMoveToSpecificIndex(array,from,to){if(!Array.isArray(array)){throw new Error("First argument must be an array.")}const length=array.length;if(from<0||from>=length||to<0||to>=length){console.warn("Invalid 'from' or 'to' index for getArrayOfMoveToSpecificIndexOptimized.");return[...array]}if(from===to){return[...array]}const copy=[...array];const[item]=copy.splice(from,1);copy.splice(to,0,item);return copy}getArrayOfMoveItemToSpecificIndex(array,item,indexOfDestination){const indexOfItem=_lodash.default.indexOf(array,item);return this.getArrayOfMoveToSpecificIndex(array,indexOfItem,indexOfDestination)}getArrayOfMoveSpecificItemToAside(array,item,toTail=true){const indexOfItem=_lodash.default.indexOf(array,item);return this.getArrayOfMoveSpecificIndexToAside(array,indexOfItem,toTail)}getArrayOfMoveSpecificIndexToAside(array,index,toTail=true){const indexOfLast=_lodash.default.size(array)-1;return this.getArrayOfMoveToSpecificIndex(array,index,toTail?indexOfLast:0)}getECPayCheckMacValue(data,hashKey="5294y06JbISpM5x9",hashIV="v77hoKGq4kWxNNIS"){const clone=_lodash.default.cloneDeep(data);delete clone.CheckMacValue;const keys=Object.keys(clone).sort((l,r)=>l>r?1:-1);let checkValue="";for(const key of keys){checkValue+=`${key}=${clone[key]}&`}checkValue=`HashKey=${hashKey}&${checkValue}HashIV=${hashIV}`;checkValue=encodeURIComponent(checkValue).toLowerCase();checkValue=checkValue.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,"+");return _lodash.default.toUpper(_cryptoJs.default.SHA256(checkValue).toString(_cryptoJs.default.enc.Hex))}getStringOfHandledHtml(htmlString,predicate=document=>{console.log(document)}){const document=(0,_nodeHtmlParser.parse)(htmlString);predicate(document);return document.toString()}getSpecifyObjectBy(array,predicate){for(const item of array){if(predicate(item))return item}}validatePayloadObjectValid(content,rules=[],idOfError=this.getRandomHash(10)){if(this.isUndefinedNullEmpty(content)){throw new _exceptioner.default(9999,`${idOfError} content(pay-load) is undefined || empty`)}for(const rule of rules){if(_lodash.default.isString(rule)){if(this.isUndefinedNullEmpty(content[rule])){throw new _exceptioner.default(9999,`${idOfError} ATTRIBUTE:'${rule}' is not Exist`)}}else if(_lodash.default.isObject(rule)){const key=this.getObjectKey(rule);const predicate=this.getObjectValue(rule);if(!predicate(content[key])){throw new _exceptioner.default(9999,`${idOfError} ATTRIBUTE:'${key}' is not valid of custom rule`)}}}return true}getArrayOfSummarizeBy(array,keyOfId,keyOfSum){const obj={};for(const item of array){const key=item[keyOfId];if(obj[key]!==undefined){obj[key]=obj[key]+item[keyOfSum]}else{obj[key]=item[keyOfSum]}}const items=[];for(const key in obj){const _obj={};_obj[keyOfId]=key;_obj[keyOfSum]=obj[key];items.push(_obj)}return items}getHeadStringSplitBy(string,sign=this.getSeparatorOfUnique()){return _lodash.default.split(string,sign).shift()}getTailStringSplitBy(string,sign=this.getSeparatorOfUnique()){return _lodash.default.split(string,sign).pop()}getSlicesByIndexes(array=[],indexes=[]){const slices=[];_lodash.default.each(indexes,(each,index,arrayOfIndexes)=>{if(_lodash.default.isEqual(index,indexes.length-1))return false;const slice=_lodash.default.slice(array,each,indexes[index+1]);slices.push(slice)});return slices}findIndexes(array,predicate){const indexes=[];let hasIndex=true;let indexOfLatest=0;while(hasIndex){indexOfLatest=_lodash.default.findIndex(array,predicate,indexOfLatest+1);if(indexOfLatest>-1){indexes.push(indexOfLatest)}else{hasIndex=false}}return indexes}isOverSpecificAge(birthDate,target=18){const age=(0,_momentTimezone.default)().diff((0,_momentTimezone.default)(birthDate,"YYYY-MM-DD"),"years");return age>=target}isValidEmail(email){const emailRegex=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return emailRegex.test(email)}isValidTaiwaneseID(idNumber){const idRegex=/^[A-Z][1-2]\d{8}$/;if(!idRegex.test(idNumber)){return false}const weight=[1,9,8,7,6,5,4,3,2,1];const firstChar=idNumber.charCodeAt(0)-65;let sum=firstChar*10+parseInt(idNumber.slice(1));for(let i=0;i<weight.length;i++){sum+=parseInt(idNumber.charAt(i+1))*weight[i]}return sum%10===0}validatePersonalInfoInput(name,email,idNumber,phoneNumber,birthday,ageOfQualify=12){if(name.length<2){return{valid:false,message:"\u59D3\u540D\u81F3\u5C11\u8981\u5169\u500B\u5B57"}}const emailRegex=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;if(!emailRegex.test(email)){return{valid:false,message:"\u96FB\u5B50\u90F5\u4EF6\u683C\u5F0F\u4E0D\u6B63\u78BA"}}const idRegex=/^[A-Z][1-2]\d{8}$/;if(!idRegex.test(idNumber)){return{valid:false,message:"\u8EAB\u5206\u8B49\u865F\u78BC\u683C\u5F0F\u4E0D\u6B63\u78BA"}}const phoneRegex=/^09\d{8}$/;if(!phoneRegex.test(phoneNumber)){return{valid:false,message:"\u624B\u6A5F\u865F\u78BC\u683C\u5F0F\u4E0D\u6B63\u78BA"}}if(this.isUndefinedNullEmpty(birthday))return{valid:false,message:`出生日期格式不正確`};const now=(0,_momentTimezone.default)();const age=now.diff(birthday,"years");if(age<ageOfQualify){return{valid:false,message:`年齡不得小於 ${ageOfQualify} 歲`}}return{valid:true,message:"\u683C\u5F0F\u6AA2\u67E5\u901A\u904E"}}getStringOfFormatTimestampRange(startTimestamp,endTimestamp){const startDate=(0,_momentTimezone.default)(startTimestamp);const endDate=(0,_momentTimezone.default)(endTimestamp);const formatDate=date=>date.format("YY/MM/DD");const startYear=startDate.year();const endYear=endDate.year();if(startYear===endYear){return`${formatDate(startDate)} - ${endDate.format("MM/DD")}`}else{return`${formatDate(startDate)} - ${formatDate(endDate)}`}}getStringOfCalculateClassTime(startTimestamp,endTimestamp,weeklyMinutes){const startDate=(0,_momentTimezone.default)(startTimestamp);const endDate=(0,_momentTimezone.default)(endTimestamp);const totalDays=endDate.diff(startDate,"days")+1;const totalWeeks=Math.ceil(totalDays/7);const totalMinutes=totalWeeks*weeklyMinutes;const hours=Math.floor(totalMinutes/60);const minutes=totalMinutes%60;if(minutes===0){return`${hours}小時`}else{return`${hours}小時${minutes}分鐘`}}getNumberOfPeriodMinute(startTimestamp,endTimestamp){const startTime=(0,_momentTimezone.default)(startTimestamp).format("HH:mm");const endTime=(0,_momentTimezone.default)(endTimestamp).format("HH:mm");const startDate=(0,_momentTimezone.default)(startTime,"HH:mm");const endDate=(0,_momentTimezone.default)(endTime,"HH:mm");const durationInMinutes=_momentTimezone.default.duration(endDate.diff(startDate)).asMinutes();return durationInMinutes}getStringOfWeekTime(day,startTimestamp,endTimestamp){const daysOfWeek={1:"\u9031\u4E00",2:"\u9031\u4E8C",3:"\u9031\u4E09",4:"\u9031\u56DB",5:"\u9031\u4E94",6:"\u9031\u516D",7:"\u9031\u65E5"};if(day<1||day>7){throw new Error("day \u5FC5\u9808\u5728 1 \u5230 7 \u4E4B\u9593")}const startTime=(0,_momentTimezone.default)(startTimestamp).format("HH:mm");const endTime=(0,_momentTimezone.default)(endTimestamp).format("HH:mm");return`${daysOfWeek[day]} ${startTime}-${endTime}`}extractNumber(str){if(this.isUndefinedNullEmpty(str))return-1;const match=str.match(/\d+/);return match?Number(match[0]):-1}async fetchElementAttribute(dom,attr="innerText",defaultValue=""){return await dom.evaluate(el=>el[attr])}async fetchElementAttributes(dom,stringOfTrait,defaultValue="",...attributes){const element=await dom.$(stringOfTrait);if(!this.isUndefinedNullEmpty(element)){try{return await element.evaluate((el,attributes)=>{if(attributes.length===1)return el[attributes.shift()];return{...attributes.map(attr=>el[attr])}},attributes)}catch(error){this.appendError(`1581532 ${stringOfTrait} fetch ${JSON.stringify(attributes)} fail, element is not found`);return defaultValue}}return defaultValue}async writeElementAttributes(dom,stringOfTrait,...attributes){const element=await dom.$(stringOfTrait);if(!this.isUndefinedNullEmpty(element)){await element.evaluate((element,attributes)=>{attributes.map(attr=>{const entries=Object.entries(attr);const key=entries[0][0];const value=entries[0][1];element[key]=value})},attributes)}else this.appendError(`1231232 ${stringOfTrait} fetch ${JSON.stringify(attributes)} fail, element is not found`)}getSliceArrayOfUnique(array){if(!Array.isArray(array)||array.length===0){return[]}const firstElement=array[0];if(_lodash.default.isObject(firstElement)&&key){const uniqueMap=new Map(array.map(item=>[item[key],item]));return Array.from(uniqueMap.values())}else if(_lodash.default.isObject(firstElement)){console.warn("getSliceArrayOfUniqueOptimized: No key provided for object array, using potentially slow deep comparison.");return _lodash.default.uniqWith(array,_lodash.default.isEqual)}else{return Array.from(new Set(array))}}getUniqueValuesBy(array,key="valueOfType"){return _lodash.default.uniq(array.map(item=>item[key]))}generateCombinations(...attributes){const keys=attributes.map(attr=>attr.key);const labelMap=_lodash.default.keyBy(attributes,"key");const optionArrays=attributes.map(attr=>attr.options.map(option=>({key:attr.key,value:option.value,label:option.label})));const cartesianProduct=_lodash.default.reduce(optionArrays,(acc,curr)=>_lodash.default.flatMap(acc,a=>curr.map(b=>[...a,b])),[[]]);const results=cartesianProduct.map(combination=>{const trait={};const idParts=[];const contentParts=[];for(const{key,value,label}of combination){trait[key]=value;idParts.push(`${key}_${value}`);contentParts.push(`${label}`)}return{trait,id:idParts.join("_"),content:contentParts.join("\uFF5C")}});return _lodash.default.sortBy(results,item=>keys.map(key=>item.trait[key]))}extractStaticSegments(path,rules=[":"]){return path.trim().replace(/^\.?\/*|\/*$/g,"").split("/").filter(segment=>segment&&!rules.some(rule=>segment.startsWith(rule)))}mutateRemoveKeys(array,keysToRemove){_lodash.default.forEach(array,(obj,index)=>{const filtered=Object.fromEntries(Object.entries(obj).filter(([key])=>!keysToRemove.includes(key)));Object.keys(obj).forEach(k=>delete obj[k]);Object.assign(obj,filtered)})}removeKeysFromArrayObjects(array,keysToRemove){return _lodash.default.map(array,obj=>Object.fromEntries(Object.entries(obj).filter(([key])=>!keysToRemove.includes(key))))}formatTextWithEllipsis(originalText,maxLength){const ellipsis="......";const ellipsisLength=ellipsis.length;if(_lodash.default.size(originalText)<=maxLength)return originalText;if(maxLength<=ellipsisLength)return"";const remainingLength=maxLength-ellipsisLength;const frontLength=Math.floor(remainingLength/2);const backLength=remainingLength-frontLength;const front=_lodash.default.truncate(originalText,{length:frontLength,omission:""});const back=_lodash.default.takeRight(originalText,backLength).join("");return`${front}${ellipsis}${back}`}getObjectBy(obj,predict=attr=>attr.checked!==true){return _lodash.default.fromPairs(_lodash.default.toPairs(obj).filter(([_,value])=>predict(value)))}mutateBy(array,predict=item=>item){const sorted=_lodash.default.sortBy(array,predict);array.splice(0,array.length,...sorted)}findUniqueStrings(...arrays){const allStrings=_lodash.default.flatten(arrays);const grouped=_lodash.default.countBy(allStrings);return _lodash.default.chain(grouped).pickBy(count=>count===1).keys().compact().value()}getObjectOfSpecifyKey(value,key){const object={};object[key]=value;return object}findUniqueNonReferenceStrings(...arrays){if(arrays.length===0)return[];const[reference,...rest]=arrays;const allExceptRef=_lodash.default.flatten(rest);const counted=_lodash.default.countBy(allExceptRef);return _lodash.default.chain(counted).pickBy((count,str)=>count===1&&!reference.includes(str)).keys().compact().value()}getArrayOfFillMissingValues(array){const charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";const generateRandomValue=()=>_lodash.default.times(8,()=>_lodash.default.sample(charset)).join("");const usedValues=new Set(array.map(item=>item.value).filter(Boolean));return array.map(item=>{if(_lodash.default.isEmpty(item.value)){let newValue;do{newValue=generateRandomValue()}while(usedValues.has(newValue));usedValues.add(newValue);return{...item,value:newValue}}return item})}isFirestoreAutoId(id){return _lodash.default.isString(id)&&id.length===20&&/^[A-Za-z0-9]{20}$/.test(id)}getAutoIdOfFirestore(){return this.getRandomHashV2(20)}getStringOfConvertTimeRange(input){const[datePart,timeRange]=input.split("\uFF5C");const dateStr=datePart.split("(")[0];const[start,end]=timeRange.split("-");const formatDate=time=>(0,_momentTimezone.default)(`${dateStr} ${time}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDHHmm");return`${formatDate(start)}-${formatDate(end)}`}getTSOfSpecificDate(dateStr,{end=false}={}){return Number((0,_lodash.default)(dateStr).thru(str=>(0,_momentTimezone.default)(str.split("(")[0],"YYYY/MM/DD")).thru(m=>end?m.endOf("day"):m.startOf("day")).value().format("YYYYMMDDHHmmss"))}isHttpsURL(url){if(!_lodash.default.isString(url))return false;try{const decoded=decodeURIComponent(url.trim());const parsed=new URL(decoded);return parsed.protocol==="https:"}catch(e){return false}}generateUniqueCodeMap(array,length=3){if(length<2){throw new Error("\u4EE3\u78BC\u9577\u5EA6\u6700\u5C11\u5FC5\u9808\u70BA 2\u3002")}const usedCodes=new Set;const usedKeys=new Set;const generateRandomCode=()=>{const letters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";const chars=letters+"0123456789";let code;do{code=letters[Math.floor(Math.random()*letters.length)];for(let i=1;i<length;i++){code+=chars[Math.floor(Math.random()*chars.length)]}}while(usedCodes.has(code));usedCodes.add(code);return code};return _lodash.default.transform(array,(result,key)=>{if(usedKeys.has(key)){throw new Error(`23125453 Duplicate key detected: "${key}"`)}usedKeys.add(key);result[key]=generateRandomCode()},{})}getPriceOfPercentageBehavior(price,percentage,discount=false){const decimal=this.toPercentageDecimal(percentage);return this.getNumberOfMultiplyCeil(price,discount?1-decimal:1+decimal)}getFeeOfDiscount(origin,percentage){return Math.round(_lodash.default.multiply(origin,this.toPercentageDecimal(percentage)))}mergeArrayByKey(array){if(!Array.isArray(array))return array;const resultMap={};for(const obj of array){if(!_lodash.default.isPlainObject(obj))continue;for(const[key,value]of Object.entries(obj)){if(!resultMap[key]){resultMap[key]=_lodash.default.cloneDeep(value)}else{_lodash.default.merge(resultMap[key],value)}}}array.length=0;Object.entries(resultMap).forEach(([key,value])=>{array.push({[key]:value})});return array}getObjectOfStartEndDateTime(input){if(!input||typeof input!=="string"){return{startDate:"",startTime:"",endDate:"",endTime:""}}const cleaned=input.replace(/|/g," ").replace(/-/g,"-").replace(/\s+/g," ").trim();const crossDatePattern=/(\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})/;const sameDatePattern=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/;let startDate,startTime,endDate,endTime;if(crossDatePattern.test(cleaned)){[,startDate,startTime,endDate,endTime]=cleaned.match(crossDatePattern)}else if(sameDatePattern.test(cleaned)){[,startDate,startTime,endTime]=cleaned.match(sameDatePattern);endDate=startDate}else{return{startDate:"",startTime:"",endDate:"",endTime:""}}const start=new Date(`${startDate} ${startTime}`);const end=new Date(`${endDate} ${endTime}`);if(end<start){throw new Error(`End time cannot be earlier than start time: ${input}`)}return{startDate,startTime,endDate,endTime}}getFilteredHeraPeriods(arr,idOfCurrentBooze){return _lodash.default.chain(arr).filter(item=>item.idOfBooze!==idOfCurrentBooze).uniqBy(item=>`${item.idOfBooze}_${item.idOfVariant}`).value()}checkPeriodConflict(newTask,existingTasks,resourceCount=1){const[datePart,timePart]=newTask.content.split("\uFF5C");const date=(0,_momentTimezone.default)(datePart.split(" ")[0],"YYYY/MM/DD");const[startTimeStr,endTimeStr]=timePart.split("-");const start=(0,_momentTimezone.default)(`${date.format("YYYY/MM/DD")} ${startTimeStr}`,"YYYY/MM/DD HH:mm");const end=(0,_momentTimezone.default)(`${date.format("YYYY/MM/DD")} ${endTimeStr}`,"YYYY/MM/DD HH:mm");const conflictItems=_lodash.default.filter(existingTasks,task=>{const[pStartStr,pEndStr]=task.period.split("-");const pStart=(0,_momentTimezone.default)(pStartStr,"YYYYMMDDHHmm");const pEnd=(0,_momentTimezone.default)(pEndStr,"YYYYMMDDHHmm");return start.isBefore(pEnd)&&end.isAfter(pStart)});const conflict=conflictItems.length>=resourceCount;return{conflict,items:conflictItems}}}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")),_lodash=_interopRequireDefault(require("lodash")),_cryptoJs=_interopRequireDefault(require("crypto-js")),_configerer=require("configerer"),_exceptioner=_interopRequireDefault(require("../exceptioner")),_momentTimezone=_interopRequireDefault(require("moment-timezone")),_uuid=require("uuid"),_nodeHtmlParser=require("node-html-parser");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{removeAttributeBy(e,t=e=>_lodash.default.isUndefined(e)){for(const r in e)t(e[r])&&delete e[r]}getNumberOfNormalize(e,t=0){if(_lodash.default.isNumber(e))return e;try{const r=_lodash.default.toNumber(e);return _lodash.default.isNumber(r)&&!isNaN(r)?r:t}catch(e){Util.appendError(`448561684561 ${e.message}`)}return t}getStringOfNormalize(e,t="",r=!1){if(_lodash.default.isString(e))return r?_lodash.default.trim(e):e;try{const a=_lodash.default.toString(e);return this.isOrEquals(a,"","undefined")?t:r?_lodash.default.trim(a):a}catch(e){Util.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=_lodash.default.toNumber(e);if(!_lodash.default.isNumber(t)||isNaN(t))return!1}return!0}getSeparatorOfUnique(){return"།།"}getStringOfVersionIncrement(e,t=1){const r=e.split(".").map(e=>_lodash.default.toNumber(e)),a=r.length-1;return r[a]=r[a]+t,r.join(".")}setLocaleOfMoment(e="en"){_momentTimezone.default.locale(e)}getUuidOfV4(){return(0,_uuid.v4)()}constructor(){(0,_defineProperty2.default)(this,"mapOfIdNTimeoutId",{}),(0,_defineProperty2.default)(this,"getEnvironment",()=>this.env),(0,_defineProperty2.default)(this,"isProductionEnvironment",()=>_lodash.default.isEqual(this.getEnvironment(),"prod")),(0,_defineProperty2.default)(this,"asyncUnitTaskFunction",(e=2e3,t="預設的param",r)=>async(a=this.getRandomHash(10))=>{const n=this.getRandomValue(e,1.2*e);try{const e=n;if(this.appendInfo(`before executed ===> i'm symbol of ${e}, ready to be executed, inner param = ${t}`),await this.syncDelay(n),_lodash.default.isFunction(r)&&r(a))throw Error("force to made error happen");return this.appendInfo(`after executed ===> i'm symbol of ${e}, the task cost ${n} million-seconds ${a?`i hav params ===> ${a}`:""}`),{randomValue:n,symbol:e,param:a}}catch(e){this.appendError(new Error(`asyncUnitTask() catch error ${e.message}`))}finally{this.appendInfo("wow.... finally got you")}}),(0,_defineProperty2.default)(this,"test",e=>async()=>(await Util.syncDelay(3e3),await Util.syncDelay(4e3),await Util.syncDelay(5e3),await Util.syncDelay(6e3),`3423809432804 ${e}`)),(0,_defineProperty2.default)(this,"findLowestValue",(e,t="price")=>{const r=_lodash.default.minBy(e,t)[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"findHighestValue",(e,t="price")=>{const r=_lodash.default.maxBy(e,t)[t];return Math.floor(r)}),(0,_defineProperty2.default)(this,"getStringOfValueRange",(e,t="price",r="$")=>{const a=_lodash.default.minBy(e,t)[t],n=_lodash.default.maxBy(e,t)[t];return n===a?`$${a}`:`${r}${a} - ${r}${n}`}),(0,_defineProperty2.default)(this,"getCallersName",()=>{let e;try{throw new Error}catch(t){let r,a=/(\w+)@|at (\w+) \(/g,n=t.stack;a.exec(n),r=a.exec(n),_lodash.default.isNull(r)||(e=r[1]||r[2])}return _lodash.default.startsWith("asyncGeneratorStep",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 a=Math.max(0,Math.min(t+1,e.length));e.splice(a,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,"convertDateToTimestamp",e=>(0,_momentTimezone.default)(e).valueOf()),(0,_defineProperty2.default)(this,"measureExecutionTime",async(e,...t)=>{const r=Date.now();await e(...t);const a=Date.now()-r,n=_momentTimezone.default.duration(a,"milliseconds"),i=Math.floor(n.asHours()),o=n.minutes(),s=n.seconds(),l=n.milliseconds(),u=(a/1e3).toFixed(3);this.appendInfo(`${i}小時 ${o}分 ${s}.${l.toString().padStart(3,"0")}秒 (合計 ${u} 秒)`)}),(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[];if(void 0===_lodash.default)return[];let a=e.trim(),n=[];r=Math.max(2,r),a.length>t&&(a=a.substring(0,t)),(a.match(/[a-zA-Z]+/g)||[]).forEach(e=>{if(e.length>=2){n.push(e.toUpperCase()),n.push(e.toLowerCase());const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase();n.push(t)}});const i=(a.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());n.push(...i);let o=a.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);n.push(r)}return _lodash.default.chain(n).filter(e=>e.length>=2).filter(e=>e.length>2||!/^[\u4e00-\u9fa5a-z0-9]$/.test(e)).uniq().sortBy().value()}),(0,_defineProperty2.default)(this,"mutateIndexOfArrayItem",(e,t,r=0)=>{if(!Array.isArray(e)||!_lodash.default.isObject(t))return e;const a=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(e,t));if(-1===a)return e;e.splice(a,1);const n=_lodash.default.clamp(r,0,e.length);return e.splice(n,0,t),e}),(0,_defineProperty2.default)(this,"getArrayOfModifyObject2Index",(e,t,r=0)=>{if(!Array.isArray(e)||!_lodash.default.isObject(t))return e;const a=_lodash.default.cloneDeep(e),n=_lodash.default.findIndex(a,e=>_lodash.default.isEqual(e,t));if(-1===n)return e;a.splice(n,1);const i=_lodash.default.clamp(r,0,a.length);return a.splice(i,0,t),a}),(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 _lodash.default.chain(t).uniq().map(t=>{const a=_lodash.default.find(e,{label:t});if(a)return{label:t,value:a.value};let n;do{n=_lodash.default.random(2,999999999)}while(r.has(n));return r.add(n),{label:t,value:n}}).value()}),(0,_defineProperty2.default)(this,"getItemsOfMarkMatching",(e=[],t=[],r="value",a="belong")=>{const n=new Set(t);return _lodash.default.map(e,e=>({...e,[a]:n.has(e[r])}))}),(0,_defineProperty2.default)(this,"generateVariants",(e,t="|",r="-")=>{const a=e.filter(e=>e.length>0);return 0===a.length?[]:1===a.length?a[0].map(e=>({label:e.label,value:e.value})):_lodash.default.reduce(a,(e,t)=>_lodash.default.flatMap(e,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=>_lodash.default.mapKeys(e,(e,t)=>r[t]||t))}),(0,_defineProperty2.default)(this,"getArrayOfMergeBySpecificId",(e,t,r="id")=>{if(!Array.isArray(t))return e;const a=_lodash.default.keyBy(t,e=>_lodash.default.get(e,r));return e.map(e=>{const t=_lodash.default.get(e,r),n=a[t];return n?_lodash.default.merge({},e,n):e})}),(0,_defineProperty2.default)(this,"toPercentageDecimal",e=>{if(_lodash.default.isNil(e))return 1;_lodash.default.isString(e)&&(e=e.replace(/%/g,"").trim());const t=_lodash.default.toNumber(e);return _lodash.default.isFinite(t)?_lodash.default.round(t/100,10):1}),(0,_defineProperty2.default)(this,"getNumberOfMultiplyCeil",(e,t,r=0)=>{const a=Math.pow(10,r);return Math.ceil(e*t*a)/a}),(0,_defineProperty2.default)(this,"generateGoogleCalendarLink",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:i,details:o})=>{const s=(0,_momentTimezone.default)(`${t} ${r}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDTHHmmss"),l=(0,_momentTimezone.default)(`${a} ${n}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDTHHmmss"),u=new URLSearchParams;return e&&u.append("text",e),s&&l&&u.append("dates",`${s}/${l}`),o&&u.append("details",o),i&&u.append("location",i),u.append("ctz","Asia/Taipei"),u.append("trp","true"),`https://calendar.google.com/calendar/r/eventedit?${u.toString()}`}),(0,_defineProperty2.default)(this,"generateTimeTreeLink",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:i,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),a&&s.append("end_date",a.replace(/\//g,"-")),n&&s.append("end_time",n),i&&s.append("location",i),o&&s.append("memo",o),`https://timetreeapp.com/plans/new?${s.toString()}`}),(0,_defineProperty2.default)(this,"generateIcsContent",({title:e,startDate:t,startTime:r,endDate:a,endTime:n,location:i,details:o})=>{const s=_momentTimezone.default.tz(`${t} ${r}`,"YYYY/MM/DD HH:mm","Asia/Taipei").format("YYYYMMDDTHHmmss"),l=_momentTimezone.default.tz(`${a} ${n}`,"YYYY/MM/DD HH:mm","Asia/Taipei").format("YYYYMMDDTHHmmss"),u=(0,_momentTimezone.default)().utc().format("YYYYMMDDTHHmmss")+"Z",d=e=>e.replace(/\\/g,"\\\\").replace(/,/g,"\\,").replace(/;/g,"\\;").replace(/\n/g,"\\n"),f=["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:${u}`];return s&&f.push(`DTSTART;TZID=Asia/Taipei:${s}`),l&&f.push(`DTEND;TZID=Asia/Taipei:${l}`),e&&f.push(`SUMMARY:${d(e)}`),i&&f.push(`LOCATION:${d(i)}`),o&&f.push(`DESCRIPTION:${d(o)}`),f.push("END:VEVENT","END:VCALENDAR"),f.join("\r\n")}),(0,_defineProperty2.default)(this,"generateAllCalendarLinks",e=>{const t=this.generateGoogleCalendarLink(e),r={...e,memo:e.details},a=this.generateTimeTreeLink(r),n=this.generateIcsContent(e);return{google:t,timeTree:a,ics:`data:text/calendar;charset=utf8,${encodeURIComponent(n)}`}}),(0,_defineProperty2.default)(this,"getArrayOfMappingRef",(e,t)=>_lodash.default.map(e,e=>{const r=_lodash.default.find(t,{value:e.value});return r?_lodash.default.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(!_lodash.default.every(e,e=>e[r]===t))return!1}return!0}),this.init(),this.env="dev"}performActionWithoutTimingIssue(e=()=>!0,t=10){this.syncDelay(t).then(()=>e())}executeTimeoutTask(e,t=1e3,r=this.getRandomHash(),...a){const n=this,i=this.mapOfIdNTimeoutId[r];i&&clearTimeout(i);const o=setTimeout(async(...t)=>{await e(),delete n.mapOfIdNTimeoutId[r]},t,...a);n.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()}appendError(...e){this.isProductionEnvironment()}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&&_lodash.default.isFunction(e)&&(r=e(r));return r}isOrEquals(e,...t){for(const r of t)if(_lodash.default.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 a=e.match(new RegExp(t,r));return this.isUndefinedNullEmpty(a)?void 0:a[0]}or(...e){for(const t of e)if(_lodash.default.isBoolean(t)&&t)return!0;return!1}and(...e){for(const t of e)if(!t)return!1;return!0}nth(e,t=-1){return _lodash.default.nth(e,t%_lodash.default.size(e))}getExistOne(...e){for(const t of e)if(t)return t}getStringOfDropHeadSign(e,t){return _lodash.default.dropWhile(Array.from(e),e=>_lodash.default.isEqual(e,t)).join("")}isAndWith(e,t,...r){for(const a of r)if(!t(e,a))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 _lodash.default.isArray(e)?r?_lodash.default.findIndex(e,e=>_lodash.default.isEqual(t,e))>-1:_lodash.default.indexOf(e,t)>-1:_lodash.default.isObject(t)?e[t]:!!_lodash.default.isString(e)&&e.indexOf(t)>-1}containsBy(e,t){return _lodash.default.findIndex(e,e=>_lodash.default.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="{",a="}"){return this.getStringOfHeadMatch(e,`(?<=\\${r})${t}+?(?=\\${a})`)}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,_lodash.default.size(t));const a=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),n=r?_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`):t;return _cryptoJs.default.AES.encrypt(e,n,{iv:a}).toString()}getEncryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY,r=!1){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const a=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue"),n=r?_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`):t;return _cryptoJs.default.AES.encrypt(JSON.stringify({content:e}),n,{iv:a}).toString()}getDecryptString(e,t=_configerer.configerer.ENCRYPT_KEY){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const r=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const a=_cryptoJs.default.AES.decrypt(e,t,{iv:r}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(a.trim()))return a}catch(e){}return _cryptoJs.default.AES.decrypt(e,_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`),{iv:r}).toString(_cryptoJs.default.enc.Utf8)}getDecryptStringV2(e,t=_configerer.configerer.ENCRYPT_KEY){if(t.length>22)throw new _exceptioner.default(8010,_lodash.default.size(t));const r=_cryptoJs.default.enc.Base64.parse("thisIsIVWeNeedToGenerateTheSameValue");try{const a=_cryptoJs.default.AES.decrypt(e,t,{iv:r}).toString(_cryptoJs.default.enc.Utf8);if(!_lodash.default.isEmpty(a.trim()))return JSON.parse(a).content}catch(e){}const a=_cryptoJs.default.AES.decrypt(e,_cryptoJs.default.enc.Base64.parse(`${t}${_lodash.default.range(0,22-t.length).join("")}`),{iv:r}).toString(_cryptoJs.default.enc.Utf8);return JSON.parse(a).content}getFirebaseFormattedString(e){return _lodash.default.replace(e,/[\.\#\$\[\]]/g,"-").trim()}formalizeNamesToArray(e){let t=e;for(t=t.split(_configerer.configerer.SEPARATE_TONE_SINGER)[0].trim(),t=_lodash.default.replace(t,/[,\/#!$%\^&\*;:{}=_`、~()()]/g,"_").trim(),t=this.getFirebaseFormattedString(t),t=_lodash.default.replace(t,/\_\_+/g,"_").trim();_lodash.default.endsWith(t,"_");)t=t.slice(0,-1).trim();const r=t.split("_");return _lodash.default.map(r,e=>_lodash.default.trim(e))}getShuffledArrayWithLimitCountHighPerformance(e,t){let r=new Array(t),a=e.length,n=new Array(a);for(t>a&&(t=a);t--;){let i=Math.floor(Math.random()*a);r[t]=e[i in n?n[i]:i],n[i]=--a in n?n[a]:a}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 _lodash.default.size(t)>1?t.pop():""}getFolderPathOfSpecificPath(e){const t=e.split("/");return t.pop(),t.join("/")}getFolderNameOfFilePath(e){if(this.isValidFilePath(e)){const t=e.split("/");return _lodash.default.nth(t,-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 _lodash.default.join(_lodash.default.initial(_lodash.default.split(e,"/")),"/")+(t?"/":"")}isPathEqualsFileType(e,t){const r=e.split(".").pop();return _lodash.default.isEqual(r,t)}isValidFilePath(e){const t=this.getExtensionFromPath(e);return _lodash.default.size(t)>0}getArrayOfSize(e,t=1){return _lodash.default.take(e,t)}getShuffledArrayWithLimitCount(e,t){return this.getShuffledArrayWithLimitCountHighPerformance(e,t)}getRandomItemOfArray(e,...t){if(!_lodash.default.isArray(e))throw new _exceptioner.default(9999,`why are you so stupid, typeof array should be array, not ==> ${e} `);const r=_lodash.default.without(e,...t),a=_lodash.default.size(r)>0?r:e,n=this.getShuffledArrayWithLimitCount(a,1);return n.length>0?n[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 a=new Map(t.map(e=>[e[r],e]));return e.map(e=>({...a.get(e[r])||{},...e}))}getShuffledItemFromArray(e){return _lodash.default.shuffle(e)[0]}getShuffledArray(e){return _lodash.default.shuffle(e)}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 _lodash.default.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 _lodash.default.isObject(e)?Object.keys(e)[0]:""}printf(){this.appendInfo("i can use in web || react.js")}isKeywordRule(e){if(_lodash.default.isUndefined(e)||_lodash.default.isEmpty(e))throw new Error("PARAMS CAN NOT BE EMPTY");if(!_lodash.default.isString(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(_lodash.default.startsWith(e,r))return!0;return!1}replaceAll(e,t,r){return _lodash.default.replace(e,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){e[_lodash.default.indexOf(e,t)]=r}deepFlat(e,t="_"){let r="";const a=[[e,""]];for(;a.length>0;){const[e,n]=a.pop();if(_lodash.default.isArray(e))for(let t=e.length-1;t>=0;t--)a.push([e[t],n]);else if(_lodash.default.isObject(e)){const r=Object.keys(e);for(let i=r.length-1;i>=0;i--){const o=r[i];a.push([e[o],n+o+t])}}else{const a=_lodash.default.trim(String(e));a.length>0?r+=(r.length>0?t:"")+n+a:n.length>0&&r.length>0?r+=t:n.length>0&&0===r.length&&(r+=n.endsWith(t)?n.slice(0,-t.length):n)}}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 a=[],n=[];for(const i of t){const o=Promise.resolve().then(()=>r(i,t));if(a.push(o),e<=t.length){const t=o.then(()=>n.splice(n.indexOf(t),1));n.push(t),n.length>=e&&await Promise.race(n)}}return Promise.all(a)}getAttrValueInSequence(e,...t){for(const r of t)if(!_lodash.default.isEmpty(e[r]))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 a=!0,n=0;for(;a;)n=_lodash.default.findIndex(e,t,n+1),n>-1?r.push(n):a=!1;return r}getSliceArrayOfSpecificIndexes(e,...t){const r=[],a=_lodash.default.size(e);for(const n of t){if(!_lodash.default.isNumber(n))throw new _exceptioner.default(9999,`59941278 index should be number => ${n}, ${e}`);if(n>a-1)throw new _exceptioner.default(9999,`5994123 index=>${n} is not valid, exceed than array size=${a}, ${e}`);r.push(_lodash.default.nth(e,n))}return r}indexesOf(e,t){const r=[];let a=-1;for(;-1!==(a=e.indexOf(t,a+1));)r.push(a);return r}getIndexOfContext(e,t){return _lodash.default.findIndex(e,e=>_lodash.default.isEqual(e.trim(),t))}toOneLineString(e){return _lodash.default.join(_lodash.default.split(e,"\n"),"")}toSpaceLessString(e){return _lodash.default.split(e,"").map(e=>_lodash.default.trim(e)).join("")}toNewLineLessString(e){return _lodash.default.split(e,"\n").map(e=>_lodash.default.trim(e)).join("")}exist(e){return!_lodash.default.isNull(e)&&!_lodash.default.isUndefined(e)}isUndefinedNullEmpty(e){const t=null==e,r=!!(_lodash.default.isString(e)||_lodash.default.isArray(e)||_lodash.default.isObject(e))&&_lodash.default.isEmpty(e);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 a=e.split(r);for(const e of a)t(e,_lodash.default.indexOf(a,e),a);return a.join(r)}getSegmentsOfEachLine(e){return e.split("\n")}getNormalizedStringEndWith(e,t){e=this.toCDB(e),t=this.toCDB(t);const r=_lodash.default.join(_lodash.default.dropRightWhile(e,e=>!_lodash.default.isEqual(e,t)),"");return _lodash.default.isEmpty(r)?e:r}getNormalizedStringNotStartWith(e,...t){e=this.toCDB(e);const r=_lodash.default.join(_lodash.default.dropWhile(e,e=>this.has(t,e)),"");return _lodash.default.isEmpty(r)?e:r}getNormalizedStringNotEndWith(e,...t){e=this.toCDB(e);const r=_lodash.default.join(_lodash.default.dropRightWhile(e,e=>this.has(t,e)),"");return _lodash.default.isEmpty(r)?e:r}getTodayTimeFormat(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD")}getCustomFormatOfDatePresent(e,t="YY/MM"){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format(t)}getSimpleDateYYMMDDFormat(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD")}getSimpleTimeYYMMDDHHmmFormat(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YY/MM/DD HH:mm")}getECPayCurrentTimeFormat(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatV2(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormatYMDHM(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm")}getCurrentTimeFormatYMDHMS(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YYYY/MM/DD HH:mm:ss")}getCurrentTimeFormat(e){return(0,_momentTimezone.default)(e||this.getCurrentTimeStamp()).format("YYYY-MM-DD-HH-mm-ss")}getCurrentMillionSecTimeFormat(e){return(0,_momentTimezone.default)(e||void 0).format("YYYY-MM-DD-HH-mm-ss-SSS")}isBetweenTimeStamp(e=this.getCurrentTimeStamp(),t,r){return(0,_momentTimezone.default)(e).isBetween(t,r)}isBeforeTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_momentTimezone.default)(e).isBefore(t)}isAfterTimeStamp(e=this.getCurrentTimeStamp(),t){return(0,_momentTimezone.default)(e).isAfter(t)}formatTimeByLocale(e,t="zh-TW",r="Asia/Taipei",a=!0){_momentTimezone.default.locale(t);const n=a?"YYYY/MM/DD HH:mm":"YYYY/MM/DD hh:mm A";return(0,_momentTimezone.default)(e).tz(r).format(n)}getTimeStampWithConditions(e={days:0,months:0,years:0,minutes:0,seconds:0,hours:0},t=this.getCurrentTimeStamp()){let r=(0,_momentTimezone.default)(t);for(const t in e){const a=e[t],n=t;a>0&&(r=r.add(a,n)),a<0&&(r=r.subtract(Math.abs(a),n))}return r.valueOf()}getTimeStampByStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss").valueOf()}getTimeStampFromSpecificFormat(e,t="YYYY/MM/DD HH:mm:ss"){return(0,_momentTimezone.default)(e,t).valueOf()}getTimeStampFromECPayStringFormat(e){return this.getTimeStampFromSpecificFormat(e,"YYYY/MM/DD HH:mm:ss").valueOf()}getTimeFormatOfDurationToMillionSecond(e){return _momentTimezone.default.utc(e).format("HH小時mm分鐘ss秒SSS")}getTimeFormatOfDurationToSecond(e){return _momentTimezone.default.utc(e).format("HH小時mm分鐘ss秒")}getTimeFormatOfDurationToDay(e){return _momentTimezone.default.utc(e).format("DD天HH小時mm分鐘ss秒")}getChineseTimeFormat(e){return _momentTimezone.default.locale("zh-TW"),(0,_momentTimezone.default)(e).format("LLLL")}getMinuteFormatOfDuration(e){return _momentTimezone.default.duration(e).asMinutes()}getSecondFormatOfDuration(e){return _momentTimezone.default.duration(e).asSeconds()}getDayFormatOfDuration(e){return _momentTimezone.default.duration(e).asDays()}getDurationOfMillionSec(e){const t=this.getCurrentTimeStamp(),r=(0,_momentTimezone.default)(e).valueOf(),a=_lodash.default.sortBy([{ts:t},{ts:r}],e=>e.ts).map(e=>e.ts);let n=(0,_momentTimezone.default)(a.pop()),i=(0,_momentTimezone.default)(a.shift());return _momentTimezone.default.duration(n.diff(i)).asMilliseconds()}getCurrentTimeStamp(){return(0,_momentTimezone.default)().valueOf()}isStringContainInLines(e,t){for(let r of _lodash.default.split(e,"\n"))if(this.has(r,t))return!0;return!1}camel(...e){return _lodash.default.camelCase(e.join("_"))}upperCamel(...e){return _lodash.default.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 a of e){const e=t(a),n=r[e];n&&_lodash.default.isArray(n)?n.push(a):r[e]=[a]}return r}isEmptyString(e){return _lodash.default.isEqual(_lodash.default.trim(e),"")}mergeObject(...e){return _lodash.default.merge(...e)}syncSetTimeout(e,t,r=()=>{}){!function a(n){n?r():setTimeout(function(){e(),a(!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 _lodash.default.dropWhile(e,(e,r)=>_lodash.default.isEqual(e,t[r])).join("")}dropItemsByIndex(e,t,r){_lodash.default.remove(e,(e,a,n)=>r>=a&&a>=t)}isEven(e){return e%2==0}isOdd(e){return 1===Math.abs(e%2)}enrichZhTw(){_momentTimezone.default.locale("zh-tw",{months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),longDateFormat:{LT:"Ah點mm分",LTS:"Ah點m分s秒",L:"YYYY-MM-DD",LL:"YYYY年MMMD日",LLL:"YYYY年MMMD日Ah點mm分",LLLL:"YYYY年MMMD日ddddAh點mm分",l:"YYYY-MM-DD",ll:"YYYY年MMMD日",lll:"YYYY年MMMD日Ah點mm分",llll:"YYYY年MMMD日ddddAh點mm分"},meridiemParse:/凌晨|早上|上午|中午|下午|晚上/,meridiemHour:function(e,t){let r=e;return 12===r&&(r=0),"凌晨"===t||"早上"===t||"上午"===t?r:"下午"===t||"晚上"===t?r+12:r>=11?r:r+12},meridiem:function(e,t,r){const a=100*e+t;return a<600?"凌晨":a<900?"早上":a<1130?"上午":a<1230?"中午":a<1800?"下午":"晚上"},calendar:{sameDay:function(){return 0===this.minutes()?"[今天]Ah[點整]":"[今天]LT"},nextDay:function(){return 0===this.minutes()?"[明天]Ah[點整]":"[明天]LT"},lastDay:function(){return 0===this.minutes()?"[昨天]Ah[點整]":"[昨天]LT"},nextWeek:function(){let e,t;return e=(0,_momentTimezone.default)().startOf("week"),t=this.diff(e,"days")>=7?"[下]":"[本]",0===this.minutes()?t+"dddA點整":t+"dddAh點mm"},lastWeek:function(){let e,t;return e=(0,_momentTimezone.default)().startOf("week"),t=this.unix()<e.unix()?"[上]":"[本]",0===this.minutes()?t+"dddAh點整":t+"dddAh點mm"},sameElse:"LL"},ordinalParse:/\d{1,2}(日|月|周)/,ordinal:function(e,t){switch(t){case"d":case"D":case"DDD":return e+"日";case"M":return e+"月";case"w":case"W":return e+"周";default:return e}},relativeTime:{future:"%s内",past:"%s前",s:"幾秒",m:"1 分鐘",mm:"%d 分鐘",h:"1 小時",hh:"%d 小時",d:"1 天",dd:"%d 天",M:"1 個月",MM:"%d 个月",y:"1 年",yy:"%d 年"},week:{dow:1,doy:4}})}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=_lodash.default.toUpper(e)){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 a of e){const e={};for(const r of t){const t=r.func?r.func:e=>e;e[r.to]=this.isUndefinedNullEmpty(r.from)||!_lodash.default.isObject(a)?t(a):t(a[r.from])}r.push(e)}return r}exeAll(e,...t){if(_lodash.default.isArray(e))for(const r of e)for(const e of t)e(r);else{if(!_lodash.default.isObject(e))throw new _exceptioner.default(9999,"7841212 type can't be array or object");for(const r in e)for(const a of t)e[r]=a(e[r])}return e}getObjectWhile(e,t,r=e=>!0){const a={};for(const n in e)r(e,t,n)&&(a[n]=e[n]);return a}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 a in e)if(void 0===t[a]||t[a]!==e[a]){r=!1;break}return r}getStringOfPop(e,t){if(!_lodash.default.isString(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(!_lodash.default.isString(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 a of e){const e=a[t];if(this.isUndefinedNullEmpty(e))throw new _exceptioner.default(9999,`48157232 pk can't be empty => '${e}'`);r[e]=a}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 a=!1;const n=!!_lodash.default.isEmpty(r)||this.and(...r.map(e=>e.logic));switch(t){case"array":_lodash.default.isArray(e)&&n&&(a=!0);break;case"object":_lodash.default.isObject(e)&&n&&(a=!0);break;case"string":_lodash.default.isString(e)&&n&&(a=!0);break;case"number":_lodash.default.isNumber(e)&&n&&(a=!0);break;case"other":if(n)return!0}const i=_lodash.default.isEmpty(r)?"":`, ${r.map(e=>e.message).join(" | ")}`;if(!1===a)throw new _exceptioner.default(9999,`7474423 type should be ${t} but get '${typeof t}' ${i} `)}getSliceArrayWithMutate(e,t){return _lodash.default.remove(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 a=e.length;if(t<0||t>=a||r<0||r>=a)return[...e];if(t===r)return[...e];const n=[...e],[i]=n.splice(t,1);return n.splice(r,0,i),n}getArrayOfMoveItemToSpecificIndex(e,t,r){const a=_lodash.default.indexOf(e,t);return this.getArrayOfMoveToSpecificIndex(e,a,r)}getArrayOfMoveSpecificItemToAside(e,t,r=!0){const a=_lodash.default.indexOf(e,t);return this.getArrayOfMoveSpecificIndexToAside(e,a,r)}getArrayOfMoveSpecificIndexToAside(e,t,r=!0){const a=_lodash.default.size(e)-1;return this.getArrayOfMoveToSpecificIndex(e,t,r?a:0)}getECPayCheckMacValue(e,t="5294y06JbISpM5x9",r="v77hoKGq4kWxNNIS"){const a=_lodash.default.cloneDeep(e);delete a.CheckMacValue;const n=Object.keys(a).sort((e,t)=>e>t?1:-1);let i="";for(const e of n)i+=`${e}=${a[e]}&`;return i=`HashKey=${t}&${i}HashIV=${r}`,i=encodeURIComponent(i).toLowerCase(),i=i.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,"+"),_lodash.default.toUpper(_cryptoJs.default.SHA256(i).toString(_cryptoJs.default.enc.Hex))}getStringOfHandledHtml(e,t=e=>{}){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 a of t)if(_lodash.default.isString(a)){if(this.isUndefinedNullEmpty(e[a]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${a}' is not Exist`)}else if(_lodash.default.isObject(a)){const t=this.getObjectKey(a);if(!this.getObjectValue(a)(e[t]))throw new _exceptioner.default(9999,`${r} ATTRIBUTE:'${t}' is not valid of custom rule`)}return!0}getArrayOfSummarizeBy(e,t,r){const a={};for(const n of e){const e=n[t];void 0!==a[e]?a[e]=a[e]+n[r]:a[e]=n[r]}const n=[];for(const e in a){const i={};i[t]=e,i[r]=a[e],n.push(i)}return n}getHeadStringSplitBy(e,t=this.getSeparatorOfUnique()){return _lodash.default.split(e,t).shift()}getTailStringSplitBy(e,t=this.getSeparatorOfUnique()){return _lodash.default.split(e,t).pop()}getSlicesByIndexes(e=[],t=[]){const r=[];return _lodash.default.each(t,(a,n,i)=>{if(_lodash.default.isEqual(n,t.length-1))return!1;const o=_lodash.default.slice(e,a,t[n+1]);r.push(o)}),r}findIndexes(e,t){const r=[];let a=!0,n=0;for(;a;)n=_lodash.default.findIndex(e,t,n+1),n>-1?r.push(n):a=!1;return r}isOverSpecificAge(e,t=18){return(0,_momentTimezone.default)().diff((0,_momentTimezone.default)(e,"YYYY-MM-DD"),"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 a=0;a<t.length;a++)r+=parseInt(e.charAt(a+1))*t[a];return r%10==0}validatePersonalInfoInput(e,t,r,a,n,i=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(a)?this.isUndefinedNullEmpty(n)?{valid:!1,message:"出生日期格式不正確"}:(0,_momentTimezone.default)().diff(n,"years")<i?{valid:!1,message:`年齡不得小於 ${i} 歲`}:{valid:!0,message:"格式檢查通過"}:{valid:!1,message:"手機號碼格式不正確"}:{valid:!1,message:"身分證號碼格式不正確"}:{valid:!1,message:"電子郵件格式不正確"}}getStringOfFormatTimestampRange(e,t){const r=(0,_momentTimezone.default)(e),a=(0,_momentTimezone.default)(t),n=e=>e.format("YY/MM/DD");return r.year()===a.year()?`${n(r)} - ${a.format("MM/DD")}`:`${n(r)} - ${n(a)}`}getStringOfCalculateClassTime(e,t,r){const a=(0,_momentTimezone.default)(e),n=(0,_momentTimezone.default)(t).diff(a,"days")+1,i=Math.ceil(n/7)*r,o=Math.floor(i/60),s=i%60;return 0===s?`${o}小時`:`${o}小時${s}分鐘`}getNumberOfPeriodMinute(e,t){const r=(0,_momentTimezone.default)(e).format("HH:mm"),a=(0,_momentTimezone.default)(t).format("HH:mm"),n=(0,_momentTimezone.default)(r,"HH:mm"),i=(0,_momentTimezone.default)(a,"HH:mm");return _momentTimezone.default.duration(i.diff(n)).asMinutes()}getStringOfWeekTime(e,t,r){if(e<1||e>7)throw new Error("day 必須在 1 到 7 之間");const a=(0,_momentTimezone.default)(t).format("HH:mm"),n=(0,_momentTimezone.default)(r).format("HH:mm");return`${{1:"週一",2:"週二",3:"週三",4:"週四",5:"週五",6:"週六",7:"週日"}[e]} ${a}-${n}`}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="",...a){const n=await e.$(t);if(!this.isUndefinedNullEmpty(n))try{return await n.evaluate((e,t)=>1===t.length?e[t.shift()]:{...t.map(t=>e[t])},a)}catch(e){return this.appendError(`1581532 ${t} fetch ${JSON.stringify(a)} fail, element is not found`),r}return r}async writeElementAttributes(e,t,...r){const a=await e.$(t);this.isUndefinedNullEmpty(a)?this.appendError(`1231232 ${t} fetch ${JSON.stringify(r)} fail, element is not found`):await a.evaluate((e,t)=>{t.map(t=>{const r=Object.entries(t),a=r[0][0],n=r[0][1];e[a]=n})},r)}getSliceArrayOfUnique(e){if(!Array.isArray(e)||0===e.length)return[];const t=e[0];if(_lodash.default.isObject(t)&&key){const t=new Map(e.map(e=>[e[key],e]));return Array.from(t.values())}return _lodash.default.isObject(t)?_lodash.default.uniqWith(e,_lodash.default.isEqual):Array.from(new Set(e))}getUniqueValuesBy(e,t="valueOfType"){return _lodash.default.uniq(e.map(e=>e[t]))}generateCombinations(...e){const t=e.map(e=>e.key),r=(_lodash.default.keyBy(e,"key"),e.map(e=>e.options.map(t=>({key:e.key,value:t.value,label:t.label})))),a=_lodash.default.reduce(r,(e,t)=>_lodash.default.flatMap(e,e=>t.map(t=>[...e,t])),[[]]).map(e=>{const t={},r=[],a=[];for(const{key:n,value:i,label:o}of e)t[n]=i,r.push(`${n}_${i}`),a.push(`${o}`);return{trait:t,id:r.join("_"),content:a.join("|")}});return _lodash.default.sortBy(a,e=>t.map(t=>e.trait[t]))}extractStaticSegments(e,t=[":"]){return e.trim().replace(/^\.?\/*|\/*$/g,"").split("/").filter(e=>e&&!t.some(t=>e.startsWith(t)))}mutateRemoveKeys(e,t){_lodash.default.forEach(e,(e,r)=>{const a=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)));Object.keys(e).forEach(t=>delete e[t]),Object.assign(e,a)})}removeKeysFromArrayObjects(e,t){return _lodash.default.map(e,e=>Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))))}formatTextWithEllipsis(e,t){if(_lodash.default.size(e)<=t)return e;if(t<=6)return"";const r=t-6,a=Math.floor(r/2),n=r-a;return`${_lodash.default.truncate(e,{length:a,omission:""})}......${_lodash.default.takeRight(e,n).join("")}`}getObjectBy(e,t=e=>!0!==e.checked){return _lodash.default.fromPairs(_lodash.default.toPairs(e).filter(([e,r])=>t(r)))}mutateBy(e,t=e=>e){const r=_lodash.default.sortBy(e,t);e.splice(0,e.length,...r)}findUniqueStrings(...e){const t=_lodash.default.flatten(e),r=_lodash.default.countBy(t);return _lodash.default.chain(r).pickBy(e=>1===e).keys().compact().value()}getObjectOfSpecifyKey(e,t){const r={};return r[t]=e,r}findUniqueNonReferenceStrings(...e){if(0===e.length)return[];const[t,...r]=e,a=_lodash.default.flatten(r),n=_lodash.default.countBy(a);return _lodash.default.chain(n).pickBy((e,r)=>1===e&&!t.includes(r)).keys().compact().value()}getArrayOfFillMissingValues(e){const t=()=>_lodash.default.times(8,()=>_lodash.default.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")).join(""),r=new Set(e.map(e=>e.value).filter(Boolean));return e.map(e=>{if(_lodash.default.isEmpty(e.value)){let a;do{a=t()}while(r.has(a));return r.add(a),{...e,value:a}}return e})}isFirestoreAutoId(e){return _lodash.default.isString(e)&&20===e.length&&/^[A-Za-z0-9]{20}$/.test(e)}getAutoIdOfFirestore(){return this.getRandomHashV2(20)}getStringOfConvertTimeRange(e){const[t,r]=e.split("|"),a=t.split("(")[0],[n,i]=r.split("-"),o=e=>(0,_momentTimezone.default)(`${a} ${e}`,"YYYY/MM/DD HH:mm").format("YYYYMMDDHHmm");return`${o(n)}-${o(i)}`}getTSOfSpecificDate(e,{end:t=!1}={}){return Number((0,_lodash.default)(e).thru(e=>(0,_momentTimezone.default)(e.split("(")[0],"YYYY/MM/DD")).thru(e=>t?e.endOf("day"):e.startOf("day")).value().format("YYYYMMDDHHmmss"))}isHttpsURL(e){if(!_lodash.default.isString(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,a=new Set;return _lodash.default.transform(e,(e,n)=>{if(a.has(n))throw new Error(`23125453 Duplicate key detected: "${n}"`);a.add(n),e[n]=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",a=e+"0123456789";let n;do{n=e[Math.floor(52*Math.random())];for(let e=1;e<t;e++)n+=a[Math.floor(62*Math.random())]}while(r.has(n));return r.add(n),n})()},{})}getPriceOfPercentageBehavior(e,t,r=!1){const a=this.toPercentageDecimal(t);return this.getNumberOfMultiplyCeil(e,r?1-a:1+a)}getFeeOfDiscount(e,t){return Math.round(_lodash.default.multiply(e,this.toPercentageDecimal(t)))}mergeArrayByKey(e){if(!Array.isArray(e))return e;const t={};for(const r of e)if(_lodash.default.isPlainObject(r))for(const[e,a]of Object.entries(r))t[e]?_lodash.default.merge(t[e],a):t[e]=_lodash.default.cloneDeep(a);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})/,a=/(\d{4}\/\d{1,2}\/\d{1,2})(?:\s*\([^)]*\))?\s*(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/;let n,i,o,s;if(r.test(t))[,n,i,o,s]=t.match(r);else{if(!a.test(t))return{startDate:"",startTime:"",endDate:"",endTime:""};[,n,i,s]=t.match(a),o=n}const l=new Date(`${n} ${i}`);if(new Date(`${o} ${s}`)<l)throw new Error(`End time cannot be earlier than start time: ${e}`);return{startDate:n,startTime:i,endDate:o,endTime:s}}getFilteredHeraPeriods(e,t){return _lodash.default.chain(e).filter(e=>e.idOfBooze!==t).uniqBy(e=>`${e.idOfBooze}_${e.idOfVariant}`).value()}checkPeriodConflict(e,t,r=1){const[a,n]=e.content.split("|"),i=(0,_momentTimezone.default)(a.split(" ")[0],"YYYY/MM/DD"),[o,s]=n.split("-"),l=(0,_momentTimezone.default)(`${i.format("YYYY/MM/DD")} ${o}`,"YYYY/MM/DD HH:mm"),u=(0,_momentTimezone.default)(`${i.format("YYYY/MM/DD")} ${s}`,"YYYY/MM/DD HH:mm"),d=_lodash.default.filter(t,e=>{const[t,r]=e.period.split("-"),a=(0,_momentTimezone.default)(t,"YYYYMMDDHHmm"),n=(0,_momentTimezone.default)(r,"YYYYMMDDHHmm");return l.isBefore(n)&&u.isAfter(a)});return{conflict:d.length>=r,items:d}}}var _default=exports.default=Utiller;
|
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _path2=_interopRequireDefault(require("path"));var _fs=_interopRequireDefault(require("fs"));var _promises=_interopRequireDefault(require("fs/promises"));var _lodash=_interopRequireDefault(require("lodash"));var _child_process=_interopRequireDefault(require("child_process"));var _configerer=require("configerer");var _index=_interopRequireDefault(require("./index"));var _index2=_interopRequireDefault(require("../exceptioner/index"));var _pdfParse=_interopRequireDefault(require("pdf-parse"));var _del=_interopRequireDefault(require("del"));var _fsExtra=_interopRequireDefault(require("fs-extra"));var _prompt=_interopRequireDefault(require("prompt"));class NodeUtiller extends _index.default{constructor(...args){super(...args);(0,_defineProperty2.default)(this,"isPersistIntoLogFile",true);(0,_defineProperty2.default)(this,"findFilePathByExtension",(rootpath,_extension=[],...exclude)=>{const reg=new RegExp(`^[^\.].+.(${_lodash.default.join(_extension,"|")})$`);return this.findFilePathBy(rootpath,item=>{return reg.test(item.fileNameExtension)},...exclude)});(0,_defineProperty2.default)(this,"executeCommandLine",async command=>{const self=this;this.appendInfo(`執行腳本 ${command}`);return new Promise(function(resolve,reject){_child_process.default.exec(command,(error,stdout,stderr)=>{self.appendInfo(`${stdout}`);self.appendInfo(`${stderr}`);if(error){self.appendError(`執行錯誤: ${error}`);reject(error);return}resolve(stdout.trim())})})});(0,_defineProperty2.default)(this,"getPathAfterSpecificFolder",(fullPath,folder="src")=>{const parts=fullPath.split(_path2.default.sep);for(let i=parts.length-1;i>=0;i--){if(parts[i]===folder){return"/"+parts.slice(i+1).join("/")}}return""});(0,_defineProperty2.default)(this,"getPathAfterSrc",fullPath=>{return this.getPathAfterSpecificFolder(fullPath)})}findSpecificFolderByPath(path,folderName){const absolute=_path2.default.resolve(path);const parts=absolute.split(_path2.default.sep);while(parts.length){const joined=_path2.default.join(...parts,folderName);if(_fs.default.existsSync(joined))return joined;parts.pop()}return null}async getPDFText(path){let dataBuffer=_fs.default.readFileSync(path);return(0,_pdfParse.default)(dataBuffer).then(data=>{return data})}printf(){this.appendInfo("i can use in node.js only yo yo")}findFilePathBy(path,predicate=()=>true,...excludes){if(!_fs.default.existsSync(path))return[];const result=[];const entries=_fs.default.readdirSync(path,{withFileTypes:true});for(const entry of entries){if(excludes.includes(entry.name))continue;const fullPath=_path2.default.join(path,entry.name);if(entry.isDirectory()){result.push(...this.findFilePathBy(fullPath,predicate,...excludes))}else if(entry.isFile()){const info=this.getPathInfo(fullPath);if(predicate(info))result.push(info)}}return result}isPathExist(path){return _fs.default.existsSync(path)}renameFile(path,newName="fileName"){if(!this.isFile(path)||!newName){this.appendError(`renameFile 錯誤, path: ${path}, newName: ${newName}`);return}const dir=_path2.default.dirname(path);const ext=_path2.default.extname(path);const newPath=_path2.default.join(dir,`${newName}${ext}`);_fs.default.renameSync(path,newPath)}getPathInfo(path){const absolute=_path2.default.resolve(path);const obj={path,absolute,isFile:false,isDirectory:true,dirName:undefined,folderName:undefined,dirPath:undefined,folderPath:undefined,extension:undefined,fileName:undefined,fileNameExtension:undefined,lastModifiedTime:undefined,name:undefined};if(this.isFile(absolute)){obj["extension"]=absolute.split(".").pop();const fileNameStrings=absolute.split("/").pop().split(".");fileNameStrings.pop();obj["fileName"]=fileNameStrings.join(".");obj["name"]=fileNameStrings.join(".");obj["dirName"]=_lodash.default.nth(absolute.split("/"),-2);obj["folderName"]=_lodash.default.nth(absolute.split("/"),-2);obj["isFile"]=true;obj["dirPath"]=this.getFolderPathOfSpecificPath(absolute);obj["folderPath"]=this.getFolderPathOfSpecificPath(absolute);obj["isDirectory"]=false;obj["fileNameExtension"]=`${obj.fileName}.${obj.extension}`;obj["lastModifiedTime"]=this.getFileLastModifiedTime(absolute)}if(this.isDirectory(absolute)){obj["dirName"]=absolute.split("/").pop()}return obj}syncExecuteCommandLine(command){const self=this;this.appendInfo(`執行腳本 ${command}`);_child_process.default.exec(`${command}`,(error,stdout,stderr)=>{self.appendInfo(`${stdout}`);self.appendInfo(`${stderr}`);if(error!==null){self.appendError(`exec error: ${error}`)}})}persistByPath(targetPath){const isAbsolute=_path2.default.isAbsolute(targetPath);const parts=targetPath.split("/").filter(Boolean);const lastPart=parts[parts.length-1];const isFile=_path2.default.extname(lastPart)!=="";let current=isAbsolute?_path2.default.sep:"";for(let i=0;i<parts.length;i++){current=_path2.default.join(current,parts[i]);if(!_fs.default.existsSync(current)){if(i===parts.length-1&&isFile){_fs.default.writeFileSync(current,"")}else{_fs.default.mkdirSync(current,{recursive:false})}}}return _path2.default.resolve(targetPath)}async copyFromFolderToDestFolder(from,dest,override=true,preserveTimestamps=false,filter=()=>true){if(!_fs.default.existsSync(from)||!_fs.default.existsSync(from))throw new _index2.default(8009,`${from} or ${dest} is not exist!`);this.appendInfo(`正在複製ing ${from}/* => ${dest}/* succeed`);_fsExtra.default.copySync(from,dest,{preserveTimestamps,override,filter});this.appendInfo(`複製成功 ${from}/* => ${dest}/* succeed`)}cleanAllFiles(dir){if(this.isDirectory(dir)){this.appendInfo(`準備清除底下的所有 ${dir}`);_fsExtra.default.emptyDirSync(dir);this.appendInfo(`成功清除底下的所有 ${dir}`)}}async deleteSelfByPath(path,force){if(_fs.default.existsSync(path)){this.appendInfo(`準備刪掉 ${path},{force:${force}}`);await(0,_del.default)(path,{force});this.appendInfo(`成功刪掉了 ${path}`)}}async deleteFileOrFolder(path){this.appendInfo(`刪掉了 ${path}`);await(0,_del.default)(path)}async deleteChildByPath(path,force=false){const pathes=this.getChildPathByPath(path);for(const path of pathes){await this.deleteSelfByPath(path.absolute,force)}}getFileCountsOfFolder(path){if(this.isDirectory(path)){return _fs.default.readdirSync(path).length}return-1}async reinstallNodeModules(path="../",...exclude){const ex=[...exclude,"node_modules","utiller","configerer"];const paths=this.findFilePathBy(path,each=>_lodash.default.isEqual(each.fileNameExtension,"package.json"),...ex);for(const _json of paths){const path_module_root=this.getFileDirPath(_json.absolute);const path_gen_node_module=`${path_module_root}node_modules`;const path_lock_json=`${path_module_root}package-lock.json`;await(0,_del.default)(path_lock_json);this.appendInfo(`刪掉了 ${path_lock_json}`);await(0,_del.default)(path_gen_node_module);this.appendInfo(`刪掉了 ${path_gen_node_module}`)}for(const _json of paths){const path_module_root=this.getFileDirPath(_json.absolute);const path_gen_node_module=`${path_module_root}node_modules`;if(!_fs.default.existsSync(path_gen_node_module)){await this.executeCommandLine(`cd ${path_module_root} && npm install`)}}}getNamesOfFolderChild(path){return this.getChildPathByPath(path).filter(p=>p.isDirectory).map(p=>p.dirName)}getChildPathByPath(_path){try{const files=_fs.default.readdirSync(_path);return files.map(file=>this.getPathInfo(_path2.default.join(_path,file)))}catch(error){throw new _index2.default(8002,error)}}copySingleFile(from,dest,fileName,force=false){const destination=fileName&&fileName.trim()?_path2.default.join(dest,fileName):dest;if(_fs.default.existsSync(destination)&&!force){throw new _index2.default(8006,destination)}_fs.default.copyFileSync(from,destination)}ensureFolderExists(folderPath){const resolved=_path2.default.resolve(folderPath);if(_fs.default.existsSync(resolved))return;_fs.default.mkdirSync(resolved,{recursive:true})}getNodeEnvVariable(key,defaultValue=undefined){const value=process.env[key];return value===undefined?defaultValue:value}isDirectory(path){if(!this.isPathExist(path))return false;return _fs.default.lstatSync(path).isDirectory()}isFile(path){if(!this.isPathExist(path))return false;return _fs.default.lstatSync(path).isFile()}isImageFile(file){return["svg","png","jpg","jpeg"].includes(file.extension)}async cleanChildFiles(path,predicate=()=>true,...exclude){if(!_fs.default.existsSync(path))return false;const files=this.findFilePathBy(path,predicate,...exclude);const nonImages=files.filter(file=>!this.isImageFile(file));await Promise.allSettled(nonImages.map(file=>{this.cleanFileContent(file.absolute);this.appendInfo(`成功 cleanChildFiles() -> '${file.path}'`);return Promise.resolve()}));return files}cleanFileContent(path){this.syncDeleteFile(path)}async syncWithExistPackage(path="../"){const paths=this.findFilePathBy(path,each=>_lodash.default.isEqual(each.fileNameExtension,"package.json"),"node_modules");for(let path of paths){try{if(!_lodash.default.isEqual(path.dirName,".."))this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${path.dirName}`,`cd ${this.getFolderPathOfSpecificPath(path.absolute)}`)}catch(error){this.appendInfo(error.message)}}}async packageTemplatify(path,packageName){const existFolders=this.getChildPathByPath(path).map(each=>each.absolute.split("/").pop());if(this.has(existFolders,packageName)){throw new _index2.default(8004,` packageName ===> '${packageName}'`)}const dirPath=`${path}/${packageName}`;_fs.default.mkdirSync(dirPath);_fs.default.copyFileSync("./template/sample.babel.config.js",`${dirPath}/babel.config.js`);const packagejson=this.getJsonObjByFilePath("./template/sample.package.json");packagejson["name"]=packageName;this.writeFileInJSON(`${dirPath}/package.json`,packagejson);this.persistByPath(`${dirPath}/src`);const classBase=String.format(this.getFileContextInRaw(`./template/sample.src.index.js`),packageName,"\u660E\u6085",new Date);_fs.default.writeFileSync(`${dirPath}/src/index.js`,classBase);const ideaWorkspacePath=`${this.findSpecificFolderByPath(dirPath,".idea")}/workspace.xml`;this.insertShellCommand(_configerer.configerer.BASE_SHELL_SCRIPT,`cd_${packageName}`,`cd ${_path2.default.resolve(dirPath)}`);if(_fs.default.existsSync(ideaWorkspacePath)){const workspace=this.getFileContextInRaw(ideaWorkspacePath);const splited=workspace.split("\n");const indexOfRunManager=_lodash.default.findIndex(splited,line=>this.has(line,"name=\"RunManager"));this.insertToArray(splited,indexOfRunManager,`<configuration name="${packageName}"
|
|
2
|
-
|
|
3
|
-
path-to-node="$USER_HOME$/.nvm/versions/node/v18.19.1/bin/node"
|
|
4
|
-
node-parameters="--require @babel/register"
|
|
5
|
-
path-to-js-file="${_path2.default.resolve(dirPath)}/src/index.js"
|
|
6
|
-
working-dir="${_path2.default.resolve(dirPath)}" >`,` <envs>`,` <env name="self_debug" value="true" />`,` <env name="is_node" value="true" />`,` </envs>`,` <method v="2" />`,`</configuration>`);const indexOfList=_lodash.default.findIndex(splited,line=>_lodash.default.isEqual(_lodash.default.trim(line),`<list>`),indexOfRunManager);this.insertToArray(splited,indexOfList,` <item itemvalue="Node.js.${packageName}" />`);_fs.default.writeFileSync(ideaWorkspacePath,splited.join("\n"))}else{this.appendError(`${ideaWorkspacePath} not exist`)}await this.executeCommandLine(`cd ${_path2.default.resolve(dirPath)} && npm install`);this.appendInfo(`build ${packageName} succeed!`)}appendInfo(...messages){return this.appendLog(_configerer.configerer.PATH_INFO_LOG,messages,false)}appendError(...messages){return this.appendLog(_configerer.configerer.PATH_ERROR_LOG,messages,true)}appendLog(path,messages,isError=false){const msg=`${this.getCurrentTimeFormat()} ${isError?"ERROR":"LOG"} : ${messages.map(this.stringifyLog).join(" ,")}`;if(!this.isProductionEnvironment()){isError?console.error(...messages):console.log(...messages)}if(this.isPersistIntoLogFile){this.appendFile(path,msg)}}stringifyLog(data){return typeof data==="object"?JSON.stringify(data):String(data)}appendFile(filePath,data,newline=true,forceDelete=false){try{const resolvedPath=_path2.default.resolve(filePath);if(forceDelete&&_fs.default.existsSync(resolvedPath))_fs.default.unlinkSync(resolvedPath);if(!_fs.default.existsSync(resolvedPath))this.persistByPath(resolvedPath);const content=`${newline?"\n":""}${data}`;_fs.default.appendFileSync(resolvedPath,content)}catch(err){throw new _index2.default(8001,err)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=false}getLogString(datas){return datas.map(data=>this.isJson(data)||_lodash.default.isObject(data)||_lodash.default.isArray(data)?this.deepFlat(data):data).join(" ,")}async persistJsonFilePrettier(path,object,ignoreP=false){path=_path2.default.resolve(path);this.appendFile(path,JSON.stringify(object),true,true);if(!ignoreP)await this.prettier(path,120)}printCollectionToFile(collection){const fileName=`./logs/__temp_${this.getCurrentTimeFormat()}.txt`;this.persistByPath(`./logs/`);this.appendFile(fileName,this.deepFlat(collection,` \n\n, `));this.appendInfo(`collectionToFile succeed, file name ==> ${fileName}`)}async readFileContentByPath(path,cache={}){return cache[path]??(cache[path]=await _promises.default.readFile(path,"utf-8"))}singleFileTemplatify(path="./"){const all=this.findFilePathByExtension(path,["js"],"node_modules");for(const file of all){const content=this.getFileContextInRaw(file.absolute).trim();if(_lodash.default.isEmpty(content)){this.appendInfo(file.fileName,file.absolute);const className=_lodash.default.isEqual(file.fileName,"index")?file.dirName:file.fileName;_fs.default.writeFileSync(file.absolute,String.format(this.getFileContextInRaw(`.
|
|
7
|
-
/template/s
|
|
8
|
-
ample.src.index.js`),className,"\u660E\u6085",new Date))}}}isFileEmpty(path){const content=this.getFileContextInRaw(path);return!content||!content.trim()}copySingleFileConservative(destPath,latestFile){const{absolute,lastModifiedTime}=latestFile;if(!this.isPathExist(absolute)||this.isFileEmpty(absolute)){this.appendInfo(`${absolute} is empty file, ignore copy behavior`);return}const destExists=_fs.default.existsSync(destPath);if(destExists&&this.getFileLastModifiedTime(destPath)>lastModifiedTime){this.appendInfo(`${destPath} is the latest, ignore this run`);return}if(!destExists){this.appendInfo(`${destPath} does not exist, safe to copy.`)}this.ensureFolderExists(_path2.default.dirname(destPath));this.copySingleFile(absolute,destPath,undefined,true)}syncDeleteFile(path){if(_fs.default.existsSync(path))_fs.default.unlinkSync(path)}getFileContextInJSON(path){try{if(_fs.default.existsSync(path)){return JSON.parse(_fs.default.readFileSync(path,"utf-8"))}}catch(error){throw new _index2.default(9999,error.message)}return{}}getFileContextInRaw(path){if(!_fs.default.existsSync(path))return"";return _fs.default.readFileSync(path,"utf-8")}writeFileInJSON(path,param){let data=JSON.stringify(param,null,2);_fs.default.writeFileSync(path,data)}async generatePackage(path="./",deployToNPMServer=false,forceInstallNodeModule=true,...exclude){let packagejsons=this.findFilePathByExtension(path,["json"],"node_modules","release");packagejsons=_lodash.default.filter(packagejsons,each=>_lodash.default.isEqual(each.fileName,"package"));packagejsons=packagejsons.map(each=>this.getFolderPathOfSpecificPath(each.absolute));for(const path of packagejsons){if(this.isAndEquals(...exclude.map(projectName=>()=>!this.has(path,projectName)))){const tempFolderPath=await this.generateTempFolderWithCleanSrc(path);const release=this.persistByPath(_path2.default.join(path,"release"));await this.executeCommandLine(`cd ${path} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const pathOfPackageJson=_path2.default.join(path,"package.json");try{const indexFileName="sample.npm.module.index.js";this.copySingleFile(`/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/${indexFileName}`,release,"index.js",true);const templatePath=_path2.default.join(path,"template");if(this.isPathExist(templatePath)){await this.copyFromFolderToDestFolder(templatePath,this.persistByPath(_path2.default.join(release,"template")))}if(deployToNPMServer){const{moduleName,version}=await this.upgradePackageJsonVersion(pathOfPackageJson);await this.updateVersionOfTemplate(moduleName,version)}this.copySingleFile(pathOfPackageJson,_path2.default.join(release,"package.json"),undefined,true);if(forceInstallNodeModule||!this.isPathExist(_path2.default.join(release,"node_module"))){await this.executeCommandLine(`cd ${release} && yarn install --production`)}else{this.appendInfo(`ignore node-module install behavior`)}this.appendInfo(`build ${path} succeed`);if(deployToNPMServer){await this.executeCommandLine(`cd ${release} && npm publish`)}}catch(error){await this.deleteSelfByPath(release,true);throw new _index2.default(9999,`generatePackage 報錯, ${error.message}`)}finally{await this.deleteSelfByPath(tempFolderPath,true)}}}}async updateVersionOfTemplate(dependency,newVersion){const paths=["/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/package.json"];for(const path of paths){if(this.isPathExist(path)){let succeedOfPersistFile=false;const json=this.getJsonObjByFilePath(path);if(json&&json.dependencies&&json.dependencies[dependency]){json.dependencies[dependency]=`^${newVersion}`;try{await this.writeJsonThanPrettier(path,json);succeedOfPersistFile=true}catch(error){succeedOfPersistFile=true}}if(!succeedOfPersistFile){await this.updateFileOfSpecificLine(path,line=>` "${dependency}":"^${newVersion}"${_lodash.default.endsWith(_lodash.default.trim(line),",")?",":""}`,each=>_lodash.default.startsWith(_lodash.default.trim(each),`"${dependency}"`))}}}await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/high/idea-inventer/newp/template/",true,true)}async updateFileOfSpecificLine(pathOfFile,contentOfUpdated=line=>"updated",predicate=line=>true){const context=this.getFileContextInRaw(pathOfFile);const lines=context.split("\n");const index=lines.findIndex(predicate);if(index===-1)return;lines[index]=contentOfUpdated(lines[index]);this.appendFile(pathOfFile,lines.join("\n"),true,true);await this.prettier(pathOfFile)}async writeJsonThanPrettier(path,json){this.writeFileInJSON(path,json);await this.prettier(path)}async enrichEachPackageJson(rootPath){const validNames=new Set(["package","admin.package","web.package","functions.package"]);const jsonFiles=this.findFilePathByExtension(rootPath,["json"],"gen","node_modules","release");const packageFiles=jsonFiles.filter(file=>validNames.has(file.fileName));if(packageFiles.length===0)return;for(const{absolute}of packageFiles){const json=this.getJsonObjByFilePath(absolute);json.scripts||={};json.scripts.updateConfigerer="npm update configerer --save";await this.writeJsonThanPrettier(absolute,json)}}insertShellCommand(shellPath=_configerer.configerer.BASE_SHELL_SCRIPT,alias,command){if(this.isStringContainInLines(this.getFileContextInRaw(shellPath),alias)){throw new _index2.default(8007,`alias ${alias} is exist`)}else{const line=`alias ${alias}='${command}'`;this.appendFile(shellPath,line)}}getAdminCredential(){return this.getJsonObjByFilePath("/Users/davidtu/cross-achieve/mimi/idea-inventer/firebaser/key/mimi19up-firebase-adminsdk.json")}isEmptyFile(path){return!this.isPathExist(path)||_lodash.default.isEmpty(this.getFileContextInRaw(path).trim())}isEmptyFolder(path){return _fs.default.readdirSync(path).length===0}async prettier(path,width=200){await this.executeCommandLine(`cd ${_path2.default.resolve(".")} && npx prettier --write ${_path2.default.resolve(path)} --print-width ${width}`)}getFileLastModifiedTime(path){return _fs.default.statSync(path).mtimeMs}getJsonObjByFilePath(path){this.appendInfo(`ready to json path:${path}`);return JSON.parse(this.getFileContextInRaw(path))}async upgradePackageJsonVersion(path){if(_lodash.default.isEqual("json",this.getPathInfo(path).extension)){const json=this.getJsonObjByFilePath(path);json.version=this.getStringOfVersionIncrement(json.version);await this.writeJsonThanPrettier(path,json);return{version:json.version,moduleName:json.name}}else{throw new _index2.default(8020,`path is not package.json, which is ${path}`)}}async reWriteJsonAttribute(filePath,...attrs){const{extension}=this.getPathInfo(filePath);if(extension!=="json"){throw new _index2.default(9999,`reWriteJsonAttribute() => path is not package.json, which is ${filePath}`)}const invalidAttr=attrs.find(attr=>typeof attr!=="object"||attr===null);if(invalidAttr){throw new _index2.default(9999,`84451515 attr is not object, which is 'type=${typeof invalidAttr} => ${invalidAttr}'`)}const json=this.getJsonObjByFilePath(filePath);for(const attr of attrs){json[this.getObjectKey(attr)]=this.getObjectValue(attr)}await this.writeJsonThanPrettier(filePath,json);return{version:json.version,moduleName:json.name}}getVersionOfPackageJson(path){return this.getAttributeValueOfJson(path,"version","1.0.0")}getAttributeValueOfJson(path,key,defaultValue=undefined){if(_lodash.default.isEqual("json",this.getPathInfo(path).extension)){const json=this.getJsonObjByFilePath(path);return json[key]??defaultValue}else{throw new _index2.default(8020,`path is not package.json, which is ${path}`)}}getVersionOfJsFile(path){return this.getAttributeValueOfJsFile(path,"version","project without version notice")}getAttributeValueOfJsFile(path,key,defaultValue=undefined){if(_lodash.default.isEqual(this.getExtensionFromPath(path),"js")){const source=require(_path2.default.resolve(path)).default;return source[key]??defaultValue}else{throw new _index2.default(8020,`path is not js file, which is ${path}`)}}async rewriteAttributeOfSourceJs(path,...attrs){if(!this.isPathExist(path)){throw new _index2.default(9999,`4849813 ${path} is not exist`)}for(const attr of attrs){if(!_lodash.default.isObject(attr)){throw new _index2.default(9999,`4984651 attr is not object, which is 'type=${typeof attr} => ${attr}'`)}const key=this.getObjectKey(attr);const value=this.getObjectValue(attr);const contents=this.getFileContextInRaw(path).split(`\n`);const index=_lodash.default.findIndex(contents,each=>_lodash.default.startsWith(_lodash.default.trim(each),`${key}`));contents[index]=` ${key}: '${value}',`;this.appendFile(path,contents.join(`\n`),true,true)}return attrs}async getAnswerFromPromptQ(configs=[{name:"name",require:true,description:"type the name"}]){_prompt.default.start();return await _prompt.default.get(configs)}async getObjectFromPromptQ(...configs){_prompt.default.start();return await _prompt.default.get(configs)}async generateTempFolderWithCleanSrc(basePath){this.appendInfo("generateTempFolderWithCleanSrc",basePath);const sourceFile=_path2.default.join(basePath,"src");const tempFolderPath=_path2.default.join(basePath,"temp");if(!_fs.default.existsSync(sourceFile))return tempFolderPath;this.appendInfo("generateTempFolderWithCleanSrc","source",sourceFile);this.persistByPath(tempFolderPath);await this.copyFromFolderToDestFolder(sourceFile,tempFolderPath);const filePaths=this.findFilePathBy(tempFolderPath);for(const{absolute:tempFilePath}of filePaths){const rawLines=this.getFileContextInRaw(tempFilePath).split("\n");const trimmedLines=rawLines.map(line=>line.trim());const start=trimmedLines.findIndex(line=>line.startsWith("if (configerer.DEBUG_MODE)"));const end=trimmedLines.lastIndexOf("}");if(start>=0&&end>start){rawLines.splice(start,end-start+1);const updatedContent=rawLines.join("\n");this.appendFile(tempFilePath,updatedContent,true,true);await this.executeCommandLine(`cd ${_path2.default.dirname(tempFilePath)} && npx prettier --write "${tempFilePath}"`)}}return tempFolderPath}rewriteFile2File(from,to){const content=this.getFileContextInRaw(from);if(!content.trim())throw new _index2.default(9999,`${from} 為空,避免覆蓋`);this.appendFile(to,content,true,true);this.appendInfo(`rewrite from:${from} => to:${to} 成功`)}getStringOfHeadOfFile(path){if(this.isPathExist(path)){const context=this.getFileContextInRaw(path);return _lodash.default.head(context.split("\n"))}return""}isFileEditSucceed(filePath){if(!this.isPathExist(filePath))return false;const file=this.getPathInfo(filePath);const context=this.getFileContextInRaw(filePath).trim();if(context===""){this.appendInfo(`74985465 path ${file.path} is empty file, file would not persist`);return false}try{const firstLine=context.split("\n")[0];const match=firstLine.match(/const\s+([a-zA-Z_]\w*)\s*=\s*(true|false)\s*;?/);if(!match||_lodash.default.size(match)<3)return false;const editValue=match[2]==="true";if(editValue===true){return true}}catch(error){this.appendError(`66445411 ${error.message}`);return false}return false}joinRespectingDot(...args){const shouldHaveDotSlash=args[0]?.startsWith("./");const cleanArgs=args[0]?.startsWith("./")?[args[0].slice(2),...args.slice(1)]:args;const joined=_path2.default.join(...cleanArgs);return shouldHaveDotSlash&&!_path2.default.isAbsolute(joined)?`./${joined}`:joined}}var _default=exports.default=NodeUtiller;
|
|
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")),_lodash=_interopRequireDefault(require("lodash")),_child_process=_interopRequireDefault(require("child_process")),_configerer=require("configerer"),_index=_interopRequireDefault(require("./index")),_index2=_interopRequireDefault(require("../exceptioner/index")),_pdfParse=_interopRequireDefault(require("pdf-parse")),_del=_interopRequireDefault(require("del")),_fsExtra=_interopRequireDefault(require("fs-extra")),_prompt=_interopRequireDefault(require("prompt"));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(`^[^.].+.(${_lodash.default.join(t,"|")})$`);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,a,n)=>{if(t.appendInfo(`${a}`),t.appendInfo(`${n}`),e)return t.appendError(`執行錯誤: ${e}`),void s(e);i(a.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
|
+
// 例如: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,"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}async getPDFText(e){let t=_fs.default.readFileSync(e);return(0,_pdfParse.default)(t).then(e=>e)}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=[],a=_fs.default.readdirSync(e,{withFileTypes:!0});for(const n of a){if(i.includes(n.name))continue;const a=_path2.default.join(e,n.name);if(n.isDirectory())s.push(...this.findFilePathBy(a,t,...i));else if(n.isFile()){const e=this.getPathInfo(a);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),a=_path2.default.join(i,`${t}${s}`);_fs.default.renameSync(e,a)}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=_lodash.default.nth(t.split("/"),-2),i.folderName=_lodash.default.nth(t.split("/"),-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],a=""!==_path2.default.extname(s);let n=t?_path2.default.sep:"";for(let e=0;e<i.length;e++)n=_path2.default.join(n,i[e]),_fs.default.existsSync(n)||(e===i.length-1&&a?_fs.default.writeFileSync(n,""):_fs.default.mkdirSync(n,{recursive:!1}));return _path2.default.resolve(e)}async copyFromFolderToDestFolder(e,t,i=!0,s=!1,a=()=>!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:a}),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=>_lodash.default.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 a=i&&i.trim()?_path2.default.join(t,i):t;if(_fs.default.existsSync(a)&&!s)throw new _index2.default(8006,a);_fs.default.copyFileSync(e,a)}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),a=s.filter(e=>!this.isImageFile(e));return await Promise.allSettled(a.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=>_lodash.default.isEqual(e.fileNameExtension,"package.json"),"node_modules");for(let e of t)try{_lodash.default.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 a=this.getJsonObjByFilePath("./template/sample.package.json");a.name=t,this.writeFileInJSON(`${s}/package.json`,a),this.persistByPath(`${s}/src`);const n=String.format(this.getFileContextInRaw("./template/sample.src.index.js"),t,"明悅",new Date);_fs.default.writeFileSync(`${s}/src/index.js`,n);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=_lodash.default.findIndex(e,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/v18.19.1/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 a=_lodash.default.findIndex(e,e=>_lodash.default.isEqual(_lodash.default.trim(e),"<list>"),i);this.insertToArray(e,a,` <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(),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 a=_path2.default.resolve(e);s&&_fs.default.existsSync(a)&&_fs.default.unlinkSync(a),_fs.default.existsSync(a)||this.persistByPath(a);const n=`${i?"\n":""}${t}`;_fs.default.appendFileSync(a,n)}catch(e){throw new _index2.default(8001,e)}}disableLogMessagePersistent(){this.isPersistIntoLogFile=!1}getLogString(e){return e.map(e=>this.isJson(e)||_lodash.default.isObject(e)||_lodash.default.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(_lodash.default.isEmpty(t)){this.appendInfo(e.fileName,e.absolute);const t=_lodash.default.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 a=_fs.default.existsSync(e);a&&this.getFileLastModifiedTime(e)>s?this.appendInfo(`${e} is the latest, ignore this run`):(a||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 a=this.findFilePathByExtension(e,["json"],"node_modules","release");a=_lodash.default.filter(a,e=>_lodash.default.isEqual(e.fileName,"package")),a=a.map(e=>this.getFolderPathOfSpecificPath(e.absolute));for(const e of a)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 a=this.persistByPath(_path2.default.join(e,"release"));await this.executeCommandLine(`cd ${e} && babel ./temp --out-dir ./release/lib --config-file ./babel.config.js`);const n=require(_path2.default.join(e,"./terser.config.js")),r=this.getStringOfTerserCommandLine(n);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/high/idea-inventer/utiller/template/${s}`,a,"index.js",!0);const n=`${e}/release/index.js`;await this.executeCommandLine(`terser ${n} -o ${n} ${r}`);const l=_path2.default.join(e,"template");if(this.isPathExist(l)&&await this.copyFromFolderToDestFolder(l,this.persistByPath(_path2.default.join(a,"template"))),t){const{moduleName:e,version:t}=await this.upgradePackageJsonVersion(o);await this.updateVersionOfTemplate(e,t)}this.copySingleFile(o,_path2.default.join(a,"package.json"),void 0,!0),i||!this.isPathExist(_path2.default.join(a,"node_module"))?await this.executeCommandLine(`cd ${a} && yarn install --production`):this.appendInfo("ignore node-module install behavior"),this.appendInfo(`build ${e} succeed`),t&&await this.executeCommandLine(`cd ${a} && npm publish`)}catch(e){throw await this.deleteSelfByPath(a,!0),new _index2.default(9999,`generatePackage 報錯, ${e.message}`)}finally{await this.deleteSelfByPath(s,!0)}}}async updateVersionOfTemplate(e,t){const i=["/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/admin.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/web.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/template/functions.package.json.mustache","/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/sample.package.json","/Users/davidtu/cross-achieve/high/idea-inventer/free_marker/package.json"];for(const s of i)if(this.isPathExist(s)){let i=!1;const a=this.getJsonObjByFilePath(s);if(a&&a.dependencies&&a.dependencies[e]){a.dependencies[e]=`^${t}`;try{await this.writeJsonThanPrettier(s,a),i=!0}catch(e){i=!0}}i||await this.updateFileOfSpecificLine(s,i=>` "${e}":"^${t}"${_lodash.default.endsWith(_lodash.default.trim(i),",")?",":""}`,t=>_lodash.default.startsWith(_lodash.default.trim(t),`"${e}"`))}await this.copyFromFolderToDestFolder("/Users/davidtu/cross-achieve/high/idea-inventer/utiller/template/","/Users/davidtu/cross-achieve/high/idea-inventer/newp/template/",!0,!0)}async updateFileOfSpecificLine(e,t=e=>"updated",i=e=>!0){const s=this.getFileContextInRaw(e).split("\n"),a=s.findIndex(i);-1!==a&&(s[a]=t(s[a]),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){return!this.isPathExist(e)||_lodash.default.isEmpty(this.getFileContextInRaw(e).trim())}isEmptyFolder(e){return 0===_fs.default.readdirSync(e).length}async prettier(e,t=200){await this.executeCommandLine(`cd ${_path2.default.resolve(".")} && npx prettier --write ${_path2.default.resolve(e)} --print-width ${t}`)}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(_lodash.default.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 a=this.getJsonObjByFilePath(e);for(const e of t)a[this.getObjectKey(e)]=this.getObjectValue(e);return await this.writeJsonThanPrettier(e,a),{version:a.version,moduleName:a.name}}getVersionOfPackageJson(e){return this.getAttributeValueOfJson(e,"version","1.0.0")}getAttributeValueOfJson(e,t,i=void 0){if(_lodash.default.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(_lodash.default.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(!_lodash.default.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),a=this.getFileContextInRaw(e).split("\n");a[_lodash.default.findIndex(a,e=>_lodash.default.startsWith(_lodash.default.trim(e),`${t}`))]=` ${t}: '${s}',`,this.appendFile(e,a.join("\n"),!0,!0)}return t}async getAnswerFromPromptQ(e=[{name:"name",require:!0,description:"type the name"}]){return _prompt.default.start(),await _prompt.default.get(e)}async getObjectFromPromptQ(...e){return _prompt.default.start(),await _prompt.default.get(e)}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)")),a=i.lastIndexOf("}");if(s>=0&&a>s){t.splice(s,a-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){if(this.isPathExist(e)){const t=this.getFileContextInRaw(e);return _lodash.default.head(t.split("\n"))}return""}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||_lodash.default.size(e)<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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "utiller",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.413",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -29,7 +29,6 @@
|
|
|
29
29
|
"uuid": "^8.3.2"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@babel/runtime": "^7.24.8",
|
|
33
32
|
"@babel/cli": "^7.24.8",
|
|
34
33
|
"@babel/core": "^7.24.9",
|
|
35
34
|
"@babel/plugin-proposal-decorators": "^7.24.1",
|
|
@@ -37,6 +36,8 @@
|
|
|
37
36
|
"@babel/plugin-transform-runtime": "^7.24.3",
|
|
38
37
|
"@babel/preset-env": "^7.24.4",
|
|
39
38
|
"@babel/preset-react": "^7.24.1",
|
|
40
|
-
"@babel/register": "^7.23.7"
|
|
39
|
+
"@babel/register": "^7.23.7",
|
|
40
|
+
"@babel/runtime": "^7.24.8",
|
|
41
|
+
"terser": "^5.44.1"
|
|
41
42
|
}
|
|
42
43
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
compress: {
|
|
3
|
+
drop_console: true, // 移除所有 console
|
|
4
|
+
drop_debugger: true, // 移除所有 debugger
|
|
5
|
+
passes: 2, // 壓縮兩次(更徹底)
|
|
6
|
+
|
|
7
|
+
// 額外的壓縮選項
|
|
8
|
+
dead_code: true, // 移除永遠不會執行的代碼
|
|
9
|
+
unused: true, // 移除未使用的變數和函數
|
|
10
|
+
warnings: false, // 不顯示警告
|
|
11
|
+
unsafe: false, // 不使用不安全的優化
|
|
12
|
+
unsafe_comps: false, // 不使用不安全的比較優化
|
|
13
|
+
unsafe_math: false, // 不使用不安全的數學優化
|
|
14
|
+
unsafe_proto: false, // 不優化 prototype
|
|
15
|
+
|
|
16
|
+
// 內聯選項
|
|
17
|
+
inline: true, // 內聯簡單的函數
|
|
18
|
+
join_vars: true, // 合併連續的 var 聲明
|
|
19
|
+
reduce_vars: true, // 優化變數賦值
|
|
20
|
+
collapse_vars: true, // 合併變數
|
|
21
|
+
|
|
22
|
+
// 移除特定的函數調用
|
|
23
|
+
pure_funcs: [], // 可以添加要移除的純函數,如 ['console.log']
|
|
24
|
+
},
|
|
25
|
+
mangle: true, // ✅ 混淆所有變數名(a, b, c...)
|
|
26
|
+
// 可以選擇性保留某些名稱不被混淆
|
|
27
|
+
// mangle: {
|
|
28
|
+
// reserved: ['$', 'exports', 'require'], // 保留這些名稱
|
|
29
|
+
// keep_fnames: false, // 不保留函數名
|
|
30
|
+
// keep_classnames: false // 不保留類名
|
|
31
|
+
// },
|
|
32
|
+
|
|
33
|
+
format: {
|
|
34
|
+
beautify: false, // ✅ 不美化,壓縮成一行
|
|
35
|
+
comments: false, // ✅ 移除所有註解
|
|
36
|
+
|
|
37
|
+
// 如果需要保留特定註解(如 license),可以用正則
|
|
38
|
+
// comments: /^!|@preserve|@license|@cc_on/i,
|
|
39
|
+
|
|
40
|
+
ascii_only: false, // 支持 Unicode 字符
|
|
41
|
+
quote_style: 3, // 保持原有的引號風格
|
|
42
|
+
wrap_iife: false, // 不包裹立即執行函數
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
sourceMap: false // 不生成 source map
|
|
46
|
+
};
|
package/lib/words/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.count=count;exports.generate=generate;exports.wordList=void 0;var _seedrandom=_interopRequireDefault(require("seedrandom"));const wordList=exports.wordList=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];const shortestWordSize=wordList.reduce((shortestWord,currentWord)=>currentWord.length<shortestWord.length?currentWord:shortestWord).length;const longestWordSize=wordList.reduce((longestWord,currentWord)=>currentWord.length>longestWord.length?currentWord:longestWord).length;function generate(options){const random=options?.seed?new _seedrandom.default(options.seed):null;const{minLength,maxLength,...rest}=options||{};function word(){let min=typeof minLength!=="number"?shortestWordSize:limitWordSize(minLength);const max=typeof maxLength!=="number"?longestWordSize:limitWordSize(maxLength);if(min>max)min=max;let rightSize=false;let wordUsed;while(!rightSize){wordUsed=generateRandomWord();rightSize=wordUsed.length<=max&&wordUsed.length>=min}return wordUsed}function generateRandomWord(){return wordList[randInt(wordList.length)]}function limitWordSize(wordSize){if(wordSize<shortestWordSize)wordSize=shortestWordSize;if(wordSize>longestWordSize)wordSize=longestWordSize;return wordSize}function randInt(lessThan){const r=random?random():Math.random();return Math.floor(r*lessThan)}if(options===undefined){return word()}if(typeof options==="number"){options={exactly:options}}else if(Object.keys(rest).length===0){return word()}if(options.exactly){options.min=options.exactly;options.max=options.exactly}if(typeof options.wordsPerString!=="number"){options.wordsPerString=1}if(typeof options.formatter!=="function"){options.formatter=word=>word}if(typeof options.separator!=="string"){options.separator=" "}const total=options.min+randInt(options.max+1-options.min);let results=[];let token="";let relativeIndex=0;for(let i=0;i<total*options.wordsPerString;i++){if(relativeIndex===options.wordsPerString-1){token+=options.formatter(word(),relativeIndex)}else{token+=options.formatter(word(),relativeIndex)+options.separator}relativeIndex++;if((i+1)%options.wordsPerString===0){results.push(token);token="";relativeIndex=0}}if(typeof options.join==="string"){results=results.join(options.join)}return results}function count(options){let{minLength,maxLength}=options||{};if(typeof minLength!=="number"){minLength=shortestWordSize}if(typeof maxLength!=="number"){maxLength=longestWordSize}return wordList.filter(word=>word.length>=minLength&&word.length<=maxLength).length}
|