UNPKG

@cmtlyt/base

Version:
34 lines (31 loc) 38.4 kB
"use strict";const array=require("./shared/base.BHKgYhd5.cjs"),fp_functor_index=require("./shared/base.BUXCkErk.cjs"),fp_utils_index=require("./shared/base.BrNI005F.cjs");require("ms");const noop=()=>{};function tryCall(t,e){const s=n=>{if(e){e(n);return}throw n};try{const n=t();return fp_functor_index.isPromise(n)&&n.catch(s),n}catch(n){s(n)}}function completion(t,...e){try{return t(...e)}catch(s){return s}}function iife(t,e){return t(...e||[])}function tryOrError(t){try{return[null,t()]}catch(e){return[e,null]}}async function tryOrErrorAsync(t){try{return[null,await t()]}catch(e){return[e,null]}}async function resultOrError(t){try{return[null,await t]}catch(e){return[e,null]}}const sleep=t=>new Promise(e=>setTimeout(e,t));function sleepSync(t){const e=getNow();for(;getNow()-e<t;);}function debounceAsync(t,e=1e3,s=!1){if(e<=0)return t;let n=null,o=null;const p=()=>{n=null,o=null};return array.cacheByReturn(()=>s?(...x)=>(o||=array.withResolvers(),n?clearTimeout(n):tryCall(()=>{const w=t(...x);fp_functor_index.isPromise(w)?w.then(o.resolve,o.reject):o.resolve(w)},o.reject),n=setTimeout(p,e),o.promise):(...x)=>{o||=array.withResolvers();const w=o;return n&&clearTimeout(n),n=setTimeout(()=>{tryCall(()=>{const B=t(...x);fp_functor_index.isPromise(B)?B.then(S=>{w.resolve(S),p()},w.reject):(w.resolve(B),p())},w.reject)},e),o.promise})}function debounce(t,e=1e3,s=!1){if(e<=0)return t;const n=debounceAsync(t,e,s);return(...o)=>{n(...o)}}function throttle(t,e=100,s=!0){if(e<=0)return t;let n=null;return array.cacheByReturn(()=>s?(...o)=>{n||(t(...o),n=setTimeout(()=>{n=null},e))}:(...o)=>{n||(n=setTimeout(()=>{t(...o),n=null},e))})}const y$1=array.cacheByReturn(()=>globalThis.requestIdleCallback?(t,e,s,n)=>{requestIdleCallback(o=>{if(o.timeRemaining()>0)try{const p=t(...e);s(p)}catch(p){n(p)}else y$1(t,e,s,n)})}:globalThis.requestAnimationFrame?(t,e,s,n)=>{const o=getNow();requestAnimationFrame(()=>{if(getNow()-o<16.6)try{const p=t(...e);s(p)}catch(p){n(p)}else y$1(t,e,s,n)})}:(t,e,s,n)=>{setTimeout(()=>{try{const o=t(...e);s(o)}catch(o){n(o)}},0)});function chunkTask(t){return e=>{const s=[];return new Promise((n,o)=>{const p=async x=>new Promise(y$1.bind(null,t,x)).then(w=>s.push(w),o);(async()=>{if(typeof e=="number")for(let x=0;x<e;++x)await p([x]);else if(Array.isArray(e))for(const x in e){const w=e[x];await p(w)}n(s)})()})}}function reverseArgs(t){return(...e)=>t(...e.reverse())}function tryCallFunc(t,e){return(...s)=>tryCall(()=>t(...s),e)}function tryOrErrorFunc(t){return function(...e){return tryOrError(()=>t.call(this,...e))}}function tryOrErrorAsyncFunc(t){return function(...e){return tryOrErrorAsync(()=>t.call(this,...e))}}const getNow=array.cacheByReturn(()=>typeof performance<"u"?()=>performance.now():()=>Date.now());function caniuseCSSFeature(t){return array.isWeb()?typeof window>"u"?!1:window?.CSS?.supports?.(t)||!1:(array.warning("caniuse \u53EA\u80FD\u5728\u6D4F\u89C8\u5668\u73AF\u5883\u4E2D\u4F7F\u7528"),!1)}function caniuse(t){return array.isWeb()?typeof window>"u"?!1:typeof window[t]<"u":(array.warning("caniuse \u53EA\u80FD\u5728\u6D4F\u89C8\u5668\u73AF\u5883\u4E2D\u4F7F\u7528"),!1)}function isFunc(t){return typeof t=="function"}function isAsyncFunc(t){return array.warning("\u8BE5\u65B9\u6CD5\u5B58\u5728\u751F\u4EA7\u73AF\u5883\u548C\u5F00\u53D1\u73AF\u5883\u7ED3\u679C\u4E0D\u4E00\u81F4\u98CE\u9669, \u8BF7\u8C28\u614E\u4F7F\u7528, \u4F8B\u5982\u4F7F\u7528 babel \u8F6C\u6362\u540E async \u51FD\u6570\u4F1A\u53D8\u6210\u666E\u901A\u51FD\u6570"),array.getType(t)==="asyncfunction"}function isConstructor(t){return t instanceof Object?typeof Object.getPrototypeOf(t).constructor=="function":!1}function deepClone(t,e=new WeakMap){if(t===null||typeof t!="object"||array.STATIC_TYPE.includes(array.getType(t)))return t;if(e.has(t))return e.get(t);const s=Array.isArray(t)?[]:{};e.set(t,s);for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(s[n]=deepClone(t[n],e));return s}function u$2(t,e){const s=array.getType(t);if(array.STATIC_TYPE.includes(s))return t;if(s!==array.getType(e))return array.STATIC_TYPE.includes(array.getType(e))?e:(array.warning("\u4F20\u5165\u7684\u4E24\u4E2A\u53C2\u6570\u7C7B\u578B\u4E0D\u540C,\u65E0\u6CD5\u5408\u5E76"),t);if(s==="string"||s==="number")return t+e;if(Array.isArray(t))return t.concat(e);if(s==="object")for(const n in e){const o=e[n];let p=t[n]??o;!array.STATIC_TYPE.includes(array.getType(p))&&typeof o=="object"&&o!==null&&(p=t[n]||(Array.isArray(o)?[]:{}),p=u$2(p,o)),t[n]=p}return t||e}function merge(t,...e){return e.reduce((s,n)=>u$2(s,n),t)}function cloneMerge(t,...e){return t=deepClone(t),merge(t,...e)}const fromEntries=array.cacheByReturn(()=>typeof Object.fromEntries=="function"?t=>Object.fromEntries(t):typeof Array.from=="function"&&typeof Object.assign=="function"?t=>{const e={};return Array.from(t,([s,n])=>e[s]=n),e}:t=>{const e={};return tryCall(()=>{for(const[s,n]of t)e[s]=n},()=>{const s=t[Symbol.iterator]();let n=s.next();for(;!n.done;){const[o,p]=n.value;e[o]=p,n=s.next()}}),e}),objectForEach=array.cacheByReturn(()=>typeof Object.entries=="function"?(t,e)=>{array.isNull(t)||Object.entries(t).forEach(([s,n])=>e(n,s))}:(t,e)=>{Object.keys(t).forEach(s=>{e(t[s],s)})}),objectMap=array.cacheByReturn(()=>typeof Object.entries=="function"?(t,e)=>fromEntries(Object.entries(t).map(([s,n])=>[s,e(n,s)])):(t,e)=>{const s={};return Object.keys(t).forEach(n=>{s[n]=e(t[n],n)}),s}),objectFilter=array.cacheByReturn(()=>typeof Object.entries=="function"?(t,e)=>fromEntries(Object.entries(t).filter(([s,n])=>e(n,s))):(t,e)=>{const s={};return Object.keys(t).forEach(n=>{e(t[n],n)&&(s[n]=t[n])}),s}),objectReduce=array.cacheByReturn(()=>typeof Object.entries=="function"?(t,e,s)=>Object.entries(t).reduce((n,[o,p])=>e(n,p,o,t),s):(t,e,s)=>Object.keys(t).reduce((n,o)=>e(n,t[o],o,t),s)),objectSome=array.cacheByReturn(()=>typeof Object.entries=="function"?(t,e)=>Object.entries(t).some(([s,n])=>e(n,s)):(t,e)=>Object.keys(t).some(s=>e(t[s],s))),objectEvery=array.cacheByReturn(()=>typeof Object.entries=="function"?(t,e)=>Object.entries(t).every(([s,n])=>e(n,s)):(t,e)=>Object.keys(t).every(s=>e(t[s],s))),objectFind=array.cacheByReturn(()=>typeof Object.entries=="function"?(t,e)=>Object.entries(t).find(([s,n])=>e(n,s))?.[1]:(t,e)=>{const s=Object.keys(t).find(n=>e(t[n],n));return s?t[s]:void 0});function a(t,e,s){return new Promise((n,o)=>{e=new RegExp(e);const p=t.match(e);if(!p){n(t);return}(async()=>{try{const x=await s(...Array.from(p)).catch(o);n(t.replace(e,x))}catch(x){o(x)}})()})}async function asyncReplace(t,e,s){if(typeof s=="string")return t.replace(e,s);if(typeof s!="function")throw new TypeError("replacer \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u51FD\u6570");return typeof e=="string"?a(t,e,s):e instanceof RegExp?e.global?new Promise((n,o)=>{let p,x=0;const w=[];for(p=e.exec(t);p!==null;){const S=s(...Array.from(p)),D=t.slice(x,p.index);x=p.index+p[0].length,w.push(D,S),p=e.exec(t)}const B=t.slice(x);w.push(B),(async()=>{const S=await Promise.all(w).catch(o);S&&n(S.join(""))})()}):a(t,e,s):t}async function streamToString(t){const e=t.getReader(),s=[];let n="";for(;;){const{done:p,value:x}=await e.read();if(p)break;s.push(x)}const o=new TextDecoder("utf-8");for(const p of s)n+=o.decode(p);return n+=o.decode(),n}async function streamToArrayBuffer(t){const e=t.getReader(),s=[];let n=0;for(;;){const{done:x,value:w}=await e.read();if(x)break;s.push(w),n+=w.byteLength}const o=new ArrayBuffer(n);let p=0;for(const x of s){const w=new Uint8Array(x);new Uint8Array(o,p,w.length).set(w),p+=w.length}return o}function arrayBufferToBase64String(t){const e=new Uint8Array(t).reduce((s,n)=>s+String.fromCharCode(n),"");return btoa(e)}const arrayBufferToChunkBase64String=arrayBufferToBase64String;function base64StringToUint8Array(t){const e=atob(t),s=e.length,n=new Uint8Array(s);for(let o=0;o<s;o++)n[o]=e.charCodeAt(o);return n}function chunkBase64StringToBlob(t){array.warning("\u5F53\u524D\u5B57\u7B26\u4E32\u4F7F\u7528 chunk \u65B9\u5F0F\u751F\u6210, \u8BF7\u4F7F\u7528 base64StringToBlob \u4EE3\u66FF, \u540E\u7EED chunkBase64StringToBlob \u65B9\u6CD5\u5C06\u4F1A\u79FB\u9664");const e=t.split("|");return new Blob(e.map(s=>base64StringToUint8Array(s)))}function base64StringToBlob(t){return t.includes("|")?chunkBase64StringToBlob(t):new Blob([base64StringToUint8Array(t)])}const chunkBase64StringToArrayBuffer=base64StringToArrayBuffer;async function base64StringToArrayBuffer(t){return base64StringToBlob(t).arrayBuffer()}function stringToStream(t){const e=new TextEncoder;return new ReadableStream({start(s){s.enqueue(e.encode(t)),s.close()}})}function stringToBinary(t){return new TextEncoder().encode(t)}function binaryToString(t){return new TextDecoder().decode(t)}async function streamToBase64String(t){const e=await streamToArrayBuffer(t);return arrayBufferToBase64String(e)}const streamToChunkBase64String=streamToBase64String,chunkBase64StringToStream=base64StringToStream;function base64StringToStream(t){return base64StringToBlob(t).stream()}function arrayBufferToStream(t){return new ReadableStream({start(e){e.enqueue(t),e.close()}})}const blobToChunkBase64String=blobToBase64String;async function blobToBase64String(t){const e=await t.arrayBuffer();return arrayBufferToBase64String(e)}function parseUrl(t,e){if(!t&&!array.safeGetGlobal().location)throw new TypeError("\u5F53\u524D\u73AF\u5883\u4E0D\u5B58\u5728 location, \u65E0\u6CD5\u4F7F\u7528\u9ED8\u8BA4\u503C, \u8BF7\u4F20\u9012 path \u53C2\u6570");if(array.isWeb()&&!caniuse("URL")||array.isNode()&&!array.safeGetGlobal().URL)throw new TypeError("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301 URL, \u65E0\u6CD5\u4F7F\u7528 parseUrl \u65B9\u6CD5");const{hashQueryToSearchParams:s}=e||{};let n=t||=array.safeGetGlobal().location.href;if(s&&(array.isHttpUrlString(n)||array.isHttpsUrlString(n))){const[o,p]=n.split("#"),[x,w]=(p||"").split("?"),[B,S]=o.split("?"),D=`${S||""}${S?w?`&${w}`:"":w||""}`;n=`${B}${D?`?${D}`:""}${x?`#${x}`:""}`}return new URL(n)}function parseSearch(t){if(array.isWeb()&&!caniuse("URLSearchParams")||array.isNode()&&!array.safeGetGlobal().URLSearchParams)throw new TypeError("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301 URL, \u65E0\u6CD5\u4F7F\u7528 parseSearch \u65B9\u6CD5");return new URLSearchParams(t)}function parseSearchObject(t){return typeof t=="string"?tryCall(()=>fromEntries(parseSearch(t).entries()),()=>fromEntries(t.replace(/^\?/,"").split("&").map(e=>e.split("=")))):fromEntries(t.entries())}function toString(t,e){const{singleQuotes:s=!1}=e||{};switch(typeof t){case"string":return s?`'${t}'`:`"${t}"`;case"number":case"boolean":case"bigint":return t.toString();case"symbol":return t.toString().replace(/^Symbol\((.*)\)$/,`Symbol(${s?"'$1'":'"$1"'})`);case"function":{const n=t.toString();return n.startsWith("(")||n.startsWith("function ")?n:`function ${n}`}case"object":return objectToString(t,e);default:return JSON.stringify(t)}}function objectToString(t,e){const s=array.getType(t);if(s==="regexp")return t.toString();if(s==="null")return"null";if(s==="date")return`new Date(${t.getTime()})`;const{wrap:n=!1,indentChar:o=" ",indent:p=n?2:0}=e||{},x=array.getChar(o,p),w=Array.isArray(t),B=[];return objectForEach(t,(S,D)=>{const P=iife(()=>w?`${n?x:""}${toString(S,e)}`:typeof S=="object"?`${n?x:""}${D}: ${objectToString(S,{...e,indent:p+2})}`:`${n?x:""}${D}: ${toString(S,e)}`);B.push(P)}),w?`[${n?` `:""}${B.join(n?`, `:", ")}${n?` `:""}]`:`{${n?` `:""}${B.join(n?`, `:", ")}${n?` `:""}}`}function formatDate(t=new Date,e){return array.warning("\u672A\u6765\u4F1A\u5B9E\u73B0~"),e?t.toLocaleString():`${t.valueOf()}`}class Calculator{#t;#e;static group(e,s=0){if(typeof e!="function")throw new TypeError("func \u5FC5\u987B\u662F\u4E00\u4E2A\u51FD\u6570");const n=new Calculator(s);return e(n)??n}constructor(e=0){this.#t=e,this.#e=0}#r(e){if(e instanceof Calculator)return e.getCurrValue();if(array.isNumber(e))return e;throw new TypeError("value \u5FC5\u987B\u662F\u4E00\u4E2A\u6570\u5B57\u6216 Calculator")}add(e){return e=this.#r(e),this.#e=this.#e+this.#t,this.#t=e,this}sub(e){return e=this.#r(e),this.#e=this.#e+this.#t,this.#t=-e,this}mut(e){return e=this.#r(e),this.#t*=e,this}div(e){return e=this.#r(e),this.#t/=e,this}getCurrValue(){return this.#e+this.#t}valueOf(){return this.#t=this.getCurrValue(),this.#e=0,this.#t}}const d$1=array.onceFunc(()=>typeof array.safeGetGlobal().document?.execCommand=="function"),c$1=array.onceFunc(()=>array.safeGetGlobal().document?.queryCommandSupported?.("copy")&&d$1()),u$1=array.onceFunc(()=>array.safeGetGlobal().document?.queryCommandSupported?.("paste")&&d$1()),i=array.onceFunc(()=>array.isHttpsUrlString(array.safeGetGlobal().location?.href)&&!!navigator.clipboard?.writeText||!1),l$1=array.onceFunc(()=>i()||c$1()||!1),m$1=array.onceFunc(()=>array.isHttpsUrlString(array.safeGetGlobal().location?.href)&&!!navigator.clipboard?.readText||!1),b$1=array.onceFunc(()=>m$1()||u$1()||!1),C$1=i,y=l$1,f$1=array.cacheByReturn(()=>{if(i())return t=>{navigator.clipboard.writeText(t)};if(c$1()){const t=array.safeGetGlobal().document;return e=>{const s=t.createElement("input");s.setAttribute("value",e),t.body.appendChild(s),s.select(),t.execCommand("copy"),t.body.removeChild(s)}}return t=>{array.warning("copy not supported:> ",t)}}),v$1=array.cacheByReturn(()=>{if(m$1())return()=>navigator.clipboard.readText();if(u$1()){const t=array.safeGetGlobal().document;return()=>{const e=t.createElement("input");t.body.appendChild(e),e.select();try{t.execCommand("paste")}catch{return Promise.reject(new Error("paste not supported"))}const s=e.value;return t.body.removeChild(e),Promise.resolve(s)}}return()=>(array.warning("paste not supported"),Promise.reject(new Error("paste not supported")))}),h$1=array.cacheByReturn(()=>{if(C$1())return()=>{navigator.clipboard.writeText("")};if(c$1()){const t=array.safeGetGlobal().document;return()=>{const e=t.createElement("input");t.body.appendChild(e),e.select(),t.execCommand("copy"),t.body.removeChild(e)}}return()=>{array.warning("clear not supported")}}),clipboard={copy:f$1,paste:v$1,clear:h$1,get isCopyable(){return l$1()},get isPasteable(){return b$1()},get isClearable(){return y()}};function l(t){return{maxConcurrent:3,autoRun:!0,...t}}let r$1=class Q{static instanceMap={};#t;#e=[];#r=0;#s=[];#c=!1;#n=null;get#i(){return this.#n&&this.#n.promise}set#i(e){if(e==="finished"&&this.#n){this.#n.resolve(),this.#n=null,this.status="finished";return}this.status=this.#t.autoRun?"running":this.status;const{promise:s,resolve:n}=array.withResolvers();this.#n={promise:s,resolve:n}}get finished(){return this.#o(),this.#i||Promise.resolve()}status="stopped";id;get#f(){if(this.status==="stopped"||this.#r>=this.#t.maxConcurrent)return;let e;do if(e=this.#e.shift(),!e)return;while(e.status!=="waiting");return this.#s.push(e),e}constructor(e,s){const n=l(s);this.id=e,this.#t=n}#o(){if(this.#c)throw new Error("queue has been disposed")}#p(){const{maxConcurrent:e}=this.#t;for(let s=this.#r;s<e;++s){const n=this.#f;if(!n){this.#r===0&&this.status==="running"&&(this.#i="finished");break}this.#r++,n.task(n).then(n.resolve.bind(null,n),n.reject)}}#u(e){const{promise:s,resolve:n,reject:o}=array.withResolvers();return{id:array.getRandomString(),promise:s,oriTask:e,task:p=>(p.status="running",e()),status:"waiting",resolve:(p,x)=>{const{id:w,status:B}=p;if(this.#s=this.#s.filter(S=>S.id!==w),this.#r--,n(x),this.#p(),B==="remove")throw new Error(`task ${p.id} Abnormal termination`)},reject:o,changeStatus:(p,x)=>{p.status=x}}}add(e,s={return:"promise"}){this.#o(),this.#i||(this.#i="init");const n=this.#u(e);this.#e.push(n),this.#t.autoRun&&this.#p();let{return:o="promise"}=s;return["id","promise"].includes(o)||(o="promise"),n[o]}#a(e,s){const n=s?[...this.#e,...this.#s]:this.#e;return typeof e=="string"?n.find(o=>o.id===e):n.find(o=>o.oriTask===e)}remove(e){this.#o();const s=this.#a(e,!1);return!s||s?.id==="running"?!1:(s.changeStatus(s,"remove"),!0)}clear(){this.#o(),this.#e=[]}getTaskInfo(e){this.#o();const s=this.#a(e,!0);if(s)return{id:s.id,status:s.status,promise:s.promise,task:s.oriTask}}run(){this.#o(),this.status!=="running"&&(this.status="running",this.#p())}stop(){this.#o(),this.status="stopped"}dispose(){this.#o(),this.stop(),this.clear(),this.status="disposed",this.#c=!0,delete Q.instanceMap[this.id]}get remainingCount(){return this.#o(),this.#e.length}};function getAllQueueIds(){return Object.keys(r$1.instanceMap)}function getConcurrentQueue(t,e="default"){return r$1.instanceMap[e]||=new r$1(e,t)}const cookie={get(t){return array.safeGetGlobal().document?.cookie.split("; ").find(e=>e.startsWith(`${t}=`))?.split("=")[1]||""},set(t,e,s={}){const n=array.safeGetGlobal().document;n?.cookie&&(n.cookie=`${t}=${e};${array.generateCookieInfo(s)}`)},remove(t){const e=array.safeGetGlobal().document;e?.cookie&&(e.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`)}},u={};class r{static getPool(e="",s=5,n){const o=n||(()=>array.INTERNAL_EMPTY);return e?u[e]??=new r(s,o,e):new r(s,o,e)}#t;#e;#r;#s;usableCount;isClose;constructor(e=5,s=()=>array.INTERNAL_EMPTY,n=Symbol("")){this.#t=n,this.#e=Array.from({length:e},(o,p)=>this.#c(s(p))),this.#r=[],this.usableCount=this.#e.reduce((o,p)=>(p.data!==array.INTERNAL_EMPTY&&o++,o),0),this.isClose=!1,this.#s=()=>{}}#c(e){return{data:e,__id:array.getRandomString(32)}}#n(e,s=null){if(this.isClose)throw this.#s(e),new Error("\u6C60\u5B50\u5DF2\u5173\u95ED");if(typeof s=="number"){const n=this.#e[s];n.data=e,n.__id=array.getRandomString(32)}else{const n=this.#e.findIndex(o=>o.data===array.INTERNAL_EMPTY);if(!~n)throw new Error("\u6C60\u5B50\u5DF2\u6EE1");this.#e[n]=this.#c(e)}++this.usableCount}async#i(e){if(this.isClose)throw new Error("\u6C60\u5B50\u5DF2\u5173\u95ED");const s=this.#e[e];if(!s||s.data===array.INTERNAL_EMPTY)return new Promise((D,P)=>{this.#r.push({resolve:D,reject:P})});const{data:n,__id:o}=s,p=()=>{if(this.isClose)throw this.#n(n,e),new Error("\u6C60\u5B50\u5DF2\u5173\u95ED");if(o!==s.__id)throw new Error("\u6570\u636E\u5DF2\u88AB\u8FD4\u8FD8")},x=()=>{this.#n(n,e)};--this.usableCount;const w=function(){if(this===S)return p(),n},B=function(){if(this===S)return p(),x()},S={data(){return w.call(this)},unUse(){return B.call(this)}};return Promise.resolve(S)}put(e){if(this.#n(e),this.#r.length){const{resolve:s}=this.#r.shift();this.get().then(n=>{s(n)})}}async get(){const e=this.#e.findIndex(s=>s.data!==array.INTERNAL_EMPTY);return this.#i(e)}close(e){this.#e.forEach(({data:s})=>e(s)),this.#e=[],this.#r=[],this.usableCount=0,this.isClose=!0,this.#s=e,delete u[this.#t]}}function createPool(t,e=5,s){return r.getPool(s,e,t)}function getPool(t=""){return r.getPool(t)}function C(t,e=[],s=!1){return` ${e.length?`importScripts("${e.join('", "')}");`:""} const func = ${t}; const { postMessage } = (()=>{ const postMessage = (data) => { self.postMessage({ __clUserCall: true, data }) }; return { postMessage: (data) => postMessage(data) }; })(); self.onmessage = async (e) => { const { callId, data: args } = e.data try { const result = await func.apply(null, ${s?"[postMessage, ...args]":"args"}); self.postMessage({ __clSysCall: true, type: 'success', result, callId }); } catch (e) { self.postMessage({ __clSysCall: true, callId, type: 'error', error: e }) } } self.onerror = (e) => { self.postMessage({ __clSysCall: true, type: 'error', error: e }) }`}function k(t){return new Worker(t)}function F$1(){const t=[],e=n=>{t.push(n)},s=n=>{t.splice(t.indexOf(n),1)};return{on:e,remove:s,clearOn:()=>{t.length=0},onOnce:n=>{const o=(...p)=>{n(...p),s(o)};e(o)},emit:n=>{for(const o of t)o(n)}}}function v({emit:t,type:e,result:s,error:n,resolve:o=()=>{},reject:p=()=>{},isSysCall:x,eventData:w}){if(x)e==="success"?o(s):p(n);else{const{__clUserCall:B,data:S}=w;t(B?S:w)}}function b(t){const e=k(t);let s=!1,n={};const{emit:o,...p}=F$1();return e.onmessage=x=>{const{type:w,result:B,error:S,callId:D,__clSysCall:P}=x.data,{resolve:_,reject:W}=n[D]||{};P&&delete n[D],v({emit:o,type:w,result:B,error:S,resolve:_,reject:W,isSysCall:P,eventData:x.data})},{run:async(...x)=>{if(s)throw new Error("worker\u8D44\u6E90\u5DF2\u91CA\u653E");const w=array.getRandomString(16);return new Promise((B,S)=>{n[w]={resolve:B,reject:S},e.postMessage({callId:w,data:x})})},dispose:()=>{e.terminate(),n=null,s=!0,URL.revokeObjectURL(t)},...p}}function E(t){let e=!1;const{emit:s,...n}=F$1();return{run:async(...o)=>{if(e)throw new Error("worker\u8D44\u6E90\u5DF2\u91CA\u653E");const p=k(t);return new Promise((x,w)=>{p.onmessage=B=>{const{type:S,result:D,error:P,__clSysCall:_}=B.data;_&&p.terminate(),v({emit:s,type:S,result:D,error:P,resolve:x,reject:w,isSysCall:_,eventData:B.data})},p.postMessage({data:o})})},dispose:()=>{e=!0,URL.revokeObjectURL(t)},...n}}function M(t){const e=[],s=[];return t.forEach(n=>{typeof n=="string"?s.push(n):typeof n=="function"&&e.push(n)}),s.push(array.createLinkByString(e.map(n=>`function ${n.name}(...args) { return (${n})(...args); }`).join(` `))),s}function createWorkerFunc(t,e=[],s={}){if(!caniuse("Worker"))return array.warning("\u4E0D\u652F\u6301 web worker \u5DF2\u964D\u7EA7"),{run:async(...w)=>await t(...w),dispose:()=>{},...F$1()};const{reuse:n=!0,needPost:o=!1}=s||{},p=C(t,M(e),o),x=array.createLinkByString(p);return n?b(x):E(x)}const G=["FormData","binary"],J=["json","string"],X=["POST","PUT"],Z=["chunk","file"];function d(t,e,s,n,o){return(Array.isArray(e)?!e.includes(array.getType(s)):array.getType(s)!==e)||o&&!o.includes(s)?(array.warning(`options.${t} \u5FC5\u987B\u662F${e}\uFF0C\u5DF2\u4F7F\u7528\u9ED8\u8BA4\u503C ${n} \u4EE3\u66FF`),n):s}function V(t){if(!t)throw new TypeError("options \u4E0D\u80FD\u4E3A\u7A7A");if(typeof t!="object")throw new TypeError("options \u5FC5\u987B\u662F\u5BF9\u8C61");if(!t.url&&t.url!=="string")throw new TypeError("options.url \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");const{url:e,maxConcurrent:s,concurrentNode:n,chunkSize:o,dataType:p,dataKey:x,responseType:w,retryCount:B,requestMethod:S,headers:D,headersHandler:P,bodyHandler:_,requestOptions:W}=t,L=d("dataType","string",p,"FormData",G);return{url:e,maxConcurrent:d("maxConcurrent","number",s,3),concurrentNode:d("concurrentNode","string",n,"chunk",Z),chunkSize:d("chunkSize","number",o,1024*512),dataType:L,dataKey:d("dataKey","string",x,"file"),responseType:d("responseType","string",w,"json",J),retryCount:d("retryCount","number",B,0),requestMethod:d("requestMethod","string",S,"POST",X),headers:d("headers","object",D,{"Content-Type":L==="FormData"?"multipart/form-data":"application/octet-stream"}),headersHandler:d("headersHandler",["function","asyncfunction"],P,()=>{}),bodyHandler:d("bodyHandler",["function","asyncfunction"],_,()=>{}),requestOptions:d("requestOptions","object",W,{})}}const ee=async({uploadInfo:t,fileUrl:e,chunkIdxInfo:s,chunkSize:n,serverPath:o,dataKey:p,responseType:x,requestMethod:w,headers:B,chunkIdxs:S,retryCount:D,dataType:P,requestOptions:_})=>{const W=[],L=await fetch(e).then(j=>j.blob()),[H,se]=s,q=S.length>0?S:Array.from({length:se-H},(j,I)=>H+I),z=j=>{if(n<=0)return L.slice();const I=j*n,$=Math.min(L.size,I+n);return L.slice(I,$)},ne=async j=>x==="json"?await j.json():x==="string"?await j.text():"none",oe=async(j,I)=>{const $=await ne(I),N={chunkIdx:j,status:"loading",response:$};I.status===200?N.status="success":(N.status="fail",W.push(j)),self.postMessage(N)},ie=(j,I)=>{W.push(j),self.postMessage({chunkIdx:j,status:"error",message:I,uploadInfo:t})},ue=userHeadersHandler||(()=>{}),ae=userBodyHandler||(()=>{}),ce=async j=>{const I=z(j),$=new FormData;$.append(p,I),$.append("chunkIdx",`${j}`);const N=await ae({chunk:I,chunkIdx:j,customOption:t.customOption});return typeof N=="object"&&Object.keys(N).forEach(K=>{$.append(K,N[K])}),$},pe=async j=>z(j),le=async j=>{if(P==="FormData")return ce(j);if(P==="binary")return pe(j)},he=async j=>{const I=await ue({chunkIdx:j,currentHeanders:B,customOption:t.customOption});return{...B,...I}},Y=async j=>{for(const I of j){const $=await le(I),N=await he(I);console.log("run",N),await fetch(o,{..._,method:w,body:$,headers:N}).then(oe.bind(null,I)).catch(ie.bind(null,I))}};await Y(q);for(let j=0;j<D&&W.length!==0;++j){const I=[...W];W.length=0,await Y(I)}return{status:"finished",message:"\u4E0A\u4F20\u7ED3\u675F",chunks:q,errorChunks:W}},U={waiting:"waiting",uploading:"uploading",closed:"closed"};async function te(t){if(fp_functor_index.isFile(t)||fp_functor_index.isBlob(t))return Promise.resolve(t);if(array.isUrl(t))return await fetch(t).then(e=>e.blob())}function F(t){return t?t.includes("=>")||t.startsWith("function")||t.startsWith("async function")?t:t.startsWith("async")?t.replace("async","async function "):`function ${t}`:""}function re({bodyHandler:t,headersHandler:e}){const s=F(t?.toString()),n=F(e?.toString());return array.createLinkByString(` ${t?`const userBodyHandler = ${s};`:""} ${e?`const userHeadersHandler = ${n};`:""} `)}const R={};class O{static getInstance(e,s=!1){const{url:n}=e;return s?R[n]=new O(e):R[n]??=new O(e)}#t;#e;#r;#s;#c;#n;#i;#f;#o;#p;#u;#a;#h;#l;constructor(e){const s=e;this.#t=e.url,this.#e=s.maxConcurrent,this.#r=s.concurrentNode,this.#s=s.chunkSize,this.#c=s.dataType,this.#n=s.dataKey,this.#i=s.responseType,this.#f=s.retryCount,this.#o=s.requestMethod;const{bodyHandler:n,headersHandler:o}=s;this.#p=s,this.#u=[],this.#a=U.waiting,this.#h={};const p=re({bodyHandler:n,headersHandler:o});this.#l=createPool(()=>createWorkerFunc(ee,[p],{reuse:!1}),this.#e,Symbol("uploader"))}#x(e,s){e(s)}#m(e){return e.some(s=>s.data?.errorChunks?.length)?"error":"success"}#b(e){return e.reduce((s,n)=>s.concat(n.data?.errorChunks||[]),[])}async#T(e,s,n){const{id:o,workerTotal:p}=s,x=this.#h[o];x.push({data:n}),x.length>=p&&(e({taskInfo:x,taskStatus:this.#m(x),errorChunks:this.#b(x),customOption:s.customOption}),delete this.#h[o],Object.keys(this.#h)||(this.#a=U.waiting))}async#d({uploadInfo:e,fileUrl:s,start:n,end:o,onProgress:p,worker:x,resolve:w,reject:B,chunkIdxs:S=[]}){const D={uploadInfo:e,chunkIdxs:S,fileUrl:s,chunkIdxInfo:[n,o],chunkSize:this.#s,serverPath:this.#t,dataKey:this.#n,responseType:this.#i,requestMethod:this.#o,headers:this.#p.headers,retryCount:this.#f,dataType:this.#c},P=this.#x.bind(this,p);return x.on(P),x.run(D).then(this.#T.bind(this,w,e),B).finally(()=>{x.remove(P),this.#y()})}async#w({runWorkerBaseData:e,retryChunksMap:s,taskChunkSize:n,chunkTotal:o}){if(s.length){for(const p in s){const x=await this.#l.get();this.#d({chunkIdxs:s[p],start:0,end:0,worker:x.data(),...e})}return}if(this.#r==="chunk"){for(let p=0;p<this.#e;++p){const x=await this.#l.get(),w=p*n,B=Math.min(o,w+n);this.#d({start:w,end:B,worker:x.data(),...e})}return}if(this.#r==="file"){e.workerTotal=1;const p=await this.#l.get();this.#d({start:0,end:o,worker:p.data(),...e})}}#A(e){return e.length?e.length:this.#r==="chunk"?this.#e:this.#r==="file"?1:0}async#y(){if(this.#a===U.closed||this.#u.length===0||this.#l.usableCount===0)return;this.#a=U.uploading;const{file:e,resolve:s,reject:n,chunkIdxs:o=[],onProgress:p=()=>{},customOption:x={}}=this.#u.shift(),w=await te(e),B=URL.createObjectURL(w),S=this.#s<=0?1:Math.ceil(w.size/this.#s),D=Math.ceil(S/this.#e),P=array.getArraySlice(o,this.#e),_={id:array.getRandomString(32),workerTotal:this.#A(P),customOption:x};this.#h[_.id]=[];const W={uploadInfo:_,fileUrl:B,onProgress:p,resolve:s,reject:n};this.#w({runWorkerBaseData:W,retryChunksMap:P,taskChunkSize:D,chunkTotal:S})}async#g(e,{onProgress:s=()=>{},chunkIdxs:n=[],customOption:o}){return new Promise((p,x)=>{this.#u.push({file:e,onProgress:s,chunkIdxs:n,resolve:p,reject:x,customOption:o}),this.#y()})}retry(e,s,n){return this.#g(e,{...n,chunkIdxs:s})}upload(e,s){if(this.#a!==U.closed)return this.#g(e,{...s||{},chunkIdxs:[]})}abort(e){return!!this.#u.splice(this.#u.findIndex(s=>s.file===e),1)?.length}clear(){this.#u=[]}close(){this.#a=U.closed,this.#l.close(e=>e.dispose())}}function createUploader(t,e=!1){const s=V(t);return O.getInstance(s,e)}function c(t){return t.join("|")}function A(t,e){const{types:s,match:n,base:o}=t;if(n&&n.matchFunc(e,s))return n.callback(...e);if(!o)throw new TypeError("\u6CA1\u6709\u627E\u5230\u5339\u914D\u7684\u51FD\u6570");return o.callback(...e)}function T(t){return fp_functor_index.isPromise(t)?"promise<any>":Array.isArray(t)?`${T(t[0])}[]`:typeof t}function h(t){return t.map(T)}function f(t,e){return t.startsWith("promise")?e.toLowerCase().startsWith("promise"):t===e}function typesMatch(t,e){const s=c(t).includes("..."),n=t.length-(s?1:0);if(n>e.length||!s&&n!==e.length)return!1;for(let o=0,p=0,x=t[o],w=e[p];p<e.length;x=t[o],w=e[++p]){if(x==="any"){++o;continue}if(x.startsWith("...")){const[,B]=x.split("...");if(!f(B,w))return!1;continue}if(!f(x,w))return!1;++o}return!0}function m(t,e,s){if(s){const o=h(s);return objectFind(t,({types:p})=>typesMatch(p,o))}if(!e)return;const n=c(e);return t[n]}function g(t){return{register(e,...s){if(typeof e!="function")throw new TypeError("\u7B2C\u4E00\u4E2A\u53C2\u6570\u5FC5\u987B\u4E3A function \u7C7B\u578B");const[n,...o]=s,p=typeof n=="function";if(p||o.unshift(n),o.some(_=>typeof _!="string"))throw new TypeError("\u5269\u4F59\u53C2\u6570\u5FC5\u987B\u4E3A string \u7C7B\u578B");const x=o.map(_=>_==="void"?"undefined":_==="unknown"?"any":_),w={callback:e,matchFunc:p?n:void 0},B=p?"match":"base",S=x.pop(),D=m(t,x);if(D?.[B])throw new TypeError(`\u5F53\u524D\u591A\u6001\u5DF2\u5B9E\u73B0, \u7C7B\u578B: ${D.types}`);const P={types:x,returnType:S,[B]:w};return t[c(x)]=Object.assign({},t[c(x)],P),this}}}function createOverloadFunc(){const t={},e=g(t);return new Proxy((...s)=>{const n=m(t,void 0,s);if(!n)throw new TypeError("\u6CA1\u6709\u627E\u5230\u5339\u914D\u7684\u51FD\u6570");return A(n,s)},{get(s,n,o){return n in e?e[n].bind(o):Reflect.get(s,n,o)}})}exports.EMPTY=array.EMPTY,exports.adjust=array.adjust,exports.adjust_=array.adjust_,exports.aperture=array.aperture,exports.aperture_=array.aperture_,exports.append=array.append,exports.append_=array.append_,exports.apply=array.apply,exports.applyTo=array.applyTo,exports.applyTo_=array.applyTo_,exports.apply_=array.apply_,exports.argNumLimit=array.argNumLimit,exports.argNumLimit_=array.argNumLimit_,exports.asyncFilter=array.asyncFilter,exports.cacheByReturn=array.cacheByReturn,exports.cacheReturnValue=array.cacheReturnValue,exports.collectBy=array.collectBy,exports.collectBy_=array.collectBy_,exports.createLinkByString=array.createLinkByString,exports.curry=array.curry,exports.every=array.every,exports.every_=array.every_,exports.filter=array.filter,exports.filter_=array.filter_,exports.find=array.find,exports.findIndex=array.findIndex,exports.findIndex_=array.findIndex_,exports.find_=array.find_,exports.gc=array.gc,exports.generateClassName=array.generateClassName,exports.generateCookieInfo=array.generateCookieInfo,exports.getAliAppEnv=array.getAliAppEnv,exports.getArray=array.getArray,exports.getArraySlice=array.getArraySlice,exports.getChar=array.getChar,exports.getDeviceInfo=array.getDeviceInfo,exports.getOsType=array.getOsType,exports.getRandomString=array.getRandomString,exports.getSpace=array.getSpace,exports.getType=array.getType,exports.getUserAgent=array.getUserAgent,exports.groupBy=array.groupBy,exports.groupBy_=array.groupBy_,exports.groupWith=array.groupWith,exports.groupWith_=array.groupWith_,exports.includes=array.includes,exports.includes_=array.includes_,exports.isAliApp=array.isAliApp,exports.isAliAppMiniApp=array.isAliAppMiniApp,exports.isAliAppWeb=array.isAliAppWeb,exports.isAliMiniApp=array.isAliMiniApp,exports.isAliMiniappPlatform=array.isAliMiniappPlatform,exports.isAliPay=array.isAliPay,exports.isAliPayWeb=array.isAliPayWeb,exports.isAliUa=array.isAliUa,exports.isAliWebInMiniApp=array.isAliWebInMiniApp,exports.isAlipayApp=array.isAlipayApp,exports.isAlipayMiniWeb=array.isAlipayMiniWeb,exports.isAlipayMiniapp=array.isAlipayMiniapp,exports.isAndroid=array.isAndroid,exports.isArray=array.isArray,exports.isArrayLike=array.isArrayLike,exports.isBaiduSmartProgram=array.isBaiduSmartProgram,exports.isBlobUrlString=array.isBlobUrlString,exports.isByteDanceMicroApp=array.isByteDanceMicroApp,exports.isCaiNiao=array.isCaiNiao,exports.isCaiNiaoApp=array.isCaiNiaoApp,exports.isCaiNiaoBusiness=array.isCaiNiaoBusiness,exports.isChrome=array.isChrome,exports.isDataUrlString=array.isDataUrlString,exports.isDingTalk=array.isDingTalk,exports.isDingdingMiniapp=array.isDingdingMiniapp,exports.isEdge=array.isEdge,exports.isEmpty=array.isEmpty,exports.isFalse=array.isFalse,exports.isFirefox=array.isFirefox,exports.isHmApp=array.isHmApp,exports.isHttpUrlString=array.isHttpUrlString,exports.isHttpsUrlString=array.isHttpsUrlString,exports.isIOS=array.isIOS,exports.isIOSNotchScreen=array.isIOSNotchScreen,exports.isIPhone14PM=array.isIPhone14PM,exports.isIPhoneX=array.isIPhoneX,exports.isIPhoneXR=array.isIPhoneXR,exports.isIPhoneXSMax=array.isIPhoneXSMax,exports.isInIframe=array.isInIframe,exports.isKraken=array.isKraken,exports.isKuaiShouMiniProgram=array.isKuaiShouMiniProgram,exports.isLBMiniWeb=array.isLBMiniWeb,exports.isLST=array.isLST,exports.isLT=array.isLT,exports.isLTMiniWeb=array.isLTMiniWeb,exports.isLTMiniapp=array.isLTMiniapp,exports.isLTNode=array.isLTNode,exports.isLTWeb=array.isLTWeb,exports.isLXB=array.isLXB,exports.isMMCMiniapp=array.isMMCMiniapp,exports.isMiniApp=array.isMiniApp,exports.isNaN=array.isNaN,exports.isNewEdge=array.isNewEdge,exports.isNode=array.isNode,exports.isNull=array.isNull,exports.isNumber=array.isNumber,exports.isOldEdge=array.isOldEdge,exports.isOpenHarmony=array.isOpenHarmony,exports.isQuickApp=array.isQuickApp,exports.isSafari=array.isSafari,exports.isString=array.isString,exports.isTB=array.isTB,exports.isTBMiniWeb=array.isTBMiniWeb,exports.isTBMiniapp=array.isTBMiniapp,exports.isTBNode=array.isTBNode,exports.isTBWeb=array.isTBWeb,exports.isTaobaoMiniapp=array.isTaobaoMiniapp,exports.isTbLive=array.isTbLive,exports.isTbWebEnv=array.isTbWebEnv,exports.isTmall=array.isTmall,exports.isTrue=array.isTrue,exports.isTuan=array.isTuan,exports.isTuanWebview=array.isTuanWebview,exports.isUndef=array.isUndef,exports.isUrl=array.isUrl,exports.isWeChatMiniProgram=array.isWeChatMiniProgram,exports.isWeb=array.isWeb,exports.isWebInDingding=array.isWebInDingding,exports.isWebInMiniApp=array.isWebInMiniApp,exports.isWechat=array.isWechat,exports.isWechatH5=array.isWechatH5,exports.isWechatMiniWeb=array.isWechatMiniWeb,exports.isWechatNode=array.isWechatNode,exports.isWechatWeb=array.isWechatWeb,exports.isWeex=array.isWeex,exports.isXiNiaoapp=array.isXiNiaoapp,exports.isYouKu=array.isYouKu,exports.join=array.join,exports.join_=array.join_,exports.makeBy=array.makeBy,exports.makeBy_=array.makeBy_,exports.map=array.map,exports.map_=array.map_,exports.memoize=array.memoize,exports.nth=array.nth,exports.nth_=array.nth_,exports.onceFunc=array.onceFunc,exports.partition=array.partition,exports.partition_=array.partition_,exports.placeholderFunc=array.placeholderFunc,exports.reduce=array.reduce,exports.reduce_=array.reduce_,exports.replicate=array.replicate,exports.replicate_=array.replicate_,exports.safeGetGlobal=array.safeGetGlobal,exports.some=array.some,exports.some_=array.some_,exports.take=array.take,exports.take_=array.take_,exports.warning=array.warning,exports.withResolvers=array.withResolvers,exports.zip=array.zip,exports.zip_=array.zip_,exports.functor=fp_functor_index.index,exports.isBlob=fp_functor_index.isBlob,exports.isFile=fp_functor_index.isFile,exports.isObject=fp_functor_index.isObject,exports.isPlainObject=fp_functor_index.isPlainObject,exports.isPromise=fp_functor_index.isPromise,exports.compose=fp_utils_index.compose,exports.pipe=fp_utils_index.pipe,exports.utils=fp_utils_index.index,exports.Calculator=Calculator,exports.arrayBufferToBase64String=arrayBufferToBase64String,exports.arrayBufferToChunkBase64String=arrayBufferToChunkBase64String,exports.arrayBufferToStream=arrayBufferToStream,exports.asyncReplace=asyncReplace,exports.base64StringToArrayBuffer=base64StringToArrayBuffer,exports.base64StringToBlob=base64StringToBlob,exports.base64StringToStream=base64StringToStream,exports.base64StringToUint8Array=base64StringToUint8Array,exports.binaryToString=binaryToString,exports.blobToBase64String=blobToBase64String,exports.blobToChunkBase64String=blobToChunkBase64String,exports.caniuse=caniuse,exports.caniuseCSSFeature=caniuseCSSFeature,exports.chunkBase64StringToArrayBuffer=chunkBase64StringToArrayBuffer,exports.chunkBase64StringToBlob=chunkBase64StringToBlob,exports.chunkBase64StringToStream=chunkBase64StringToStream,exports.chunkTask=chunkTask,exports.clipboard=clipboard,exports.cloneMerge=cloneMerge,exports.completion=completion,exports.cookie=cookie,exports.createOverloadFunc=createOverloadFunc,exports.createPolymorphismFunc=createOverloadFunc,exports.createPool=createPool,exports.createUploader=createUploader,exports.createWorkerFunc=createWorkerFunc,exports.debounce=debounce,exports.debounceAsync=debounceAsync,exports.deepClone=deepClone,exports.formatDate=formatDate,exports.fromEntries=fromEntries,exports.getAllQueueIds=getAllQueueIds,exports.getConcurrentQueue=getConcurrentQueue,exports.getNow=getNow,exports.getPool=getPool,exports.iife=iife,exports.isAsyncFunc=isAsyncFunc,exports.isConstructor=isConstructor,exports.isFunc=isFunc,exports.merge=merge,exports.noop=noop,exports.objectEvery=objectEvery,exports.objectFilter=objectFilter,exports.objectFind=objectFind,exports.objectForEach=objectForEach,exports.objectMap=objectMap,exports.objectReduce=objectReduce,exports.objectSome=objectSome,exports.objectToString=objectToString,exports.parseSearch=parseSearch,exports.parseSearchObject=parseSearchObject,exports.parseUrl=parseUrl,exports.resultOrError=resultOrError,exports.reverseArgs=reverseArgs,exports.sleep=sleep,exports.sleepSync=sleepSync,exports.streamToArrayBuffer=streamToArrayBuffer,exports.streamToBase64String=streamToBase64String,exports.streamToChunkBase64String=streamToChunkBase64String,exports.streamToString=streamToString,exports.stringToBinary=stringToBinary,exports.stringToStream=stringToStream,exports.throttle=throttle,exports.toString=toString,exports.tryCall=tryCall,exports.tryCallFunc=tryCallFunc,exports.tryOrError=tryOrError,exports.tryOrErrorAsync=tryOrErrorAsync,exports.tryOrErrorAsyncFunc=tryOrErrorAsyncFunc,exports.tryOrErrorFunc=tryOrErrorFunc,exports.typesMatch=typesMatch;