UNPKG

pdd

Version:
5 lines (4 loc) 19.8 kB
class Exception extends Error{name="Error";message="Error message";code=500;constructor(t,e,s=500){super(e),this.name=t??"Error",this.message=e??"Error message",this.code=s??500}}const opt=Object.prototype.toString;function isArray(t){return"[object Array]"===opt.call(t)}function isNull(t){return"[object Null]"===opt.call(t)}function isBoolean(t){return"[object Boolean]"===opt.call(t)}function isObject(t){return"[object Object]"===opt.call(t)}const isPromise=t=>"[object Promise]"===opt.call(t);function isString(t){return"[object String]"===opt.call(t)}function isNumber(t){return"[object Number]"===opt.call(t)&&t==t}function isRegExp(t){return"[object RegExp]"===opt.call(t)}function isDate(t){return"[object Date]"===opt.call(t)}function isHex(t){return/^#[a-fA-F0-9]{3}$|#[a-fA-F0-9]{6}$/.test(t)}function isRgb(t){return/^rgb\((\s*\d+\s*,?){3}\)$/.test(t)}function isRgba(t){return/^rgba\((\s*\d+\s*,\s*){3}\s*\d(\.\d+)?\s*\)$/.test(t)}function isColor(t){return isHex(t)||isRgb(t)||isRgba(t)}function isUndefined(t){return void 0===t}function isFunction(t){return"function"==typeof t}function isClass(t){if("function"==typeof t){const e=t.toString();if(void 0!==t.prototype&&t.prototype.constructor===t){if("class "===e.slice(0,6))return!0;if(2<=Object.getOwnPropertyNames(t.prototype).length)return!0;/^function\s+\(|^function\s+anonymous\(/.test(e)}}return!1}function isEmptyObject(t){return isObject(t)&&0===Object.keys(t).length}function isEmpty(t){return!t&&0!==t||isEmptyObject(t)}function isExist(t){return t||0===t}function isWindow(t){return t===window}function isPhone(t){return!!isString(t)&&/^(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/.test(t)}function isEmail(t){return!!isString(t)&&/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(t)}class Container{static instance=null;instances=new Map;bindings={};aliases={};bind(t,e){if(!t)throw new Exception("Abstract Error","Abstract not null");if(Array.isArray(t))t.map(t=>{this.bind(t,e)});else{if(!isString(t))throw new Exception("Abstract Error","The abstract name is a string");isObject(e)||isClass(e)?this.bindings[t]=e:isFunction(e)&&!isClass(e)&&this.instances.set(t,e)}}make(t,e,s=!1){var r;if(t=this.getAlias(t),this.has(t))return isClass(r=this.instances.get(t)||this.bindings[t])?this.makeClass(t,r,e,s):isFunction(r)?this.makeFunc(t,r,e,s):r;throw new Exception("Container Error","The abstract does not exist")}makeClass(t,e,s,r=!1){var i=()=>new e(s);return r?(this.bind(t,i),this.instances.get(t)):i}makeFunc(t,e,s,r=!1){e=e(s);return r?(this.bind(t,e),this.instances.get(t)):e}has(t){return this.existence(t)}existence(t){return!this.bindings[t]||!this.instances.get(t)||!this.getAlias(t)}getAlias(t){return this.aliases[t]||t}get(t){if(this.has(t))return this.make(t);throw new Exception("Container Error","The abstract does not exist")}singleton(t,e){this.bind(t,e)}static getInstance(){let t=this.instance;return t=t&&t instanceof Container?t:this.instance=new Container}proxyInstance(){return new Proxy(this,{get:(t,e)=>t[e]})}}class Application extends Container{static VERSION="0.4.14";adapters=new WeakMap;providers=[];static lifecycle(){const t=(new Date).getTime();return{created:()=>{Application.registerProviders(Application.getProviders()),Application.registerProviders(Application.getConfig("APP_CONFIG").PROVIDERS)},mounted:()=>{},unmounted:()=>{console.log(` %c pdd %c ${Application.VERSION} ${(new Date).getTime()-t}ms `,"color: #fadfa3; background: #030307; padding:5px 0;border-radius:3px 0 0 3px;","color:#000000;background: #ebd29a; padding:5px 0;border-radius:0 3px 3px 0;")}}}getterProviders(){var t=this.providers;return Array.isArray(t)&&0<t.length?t:[]}static getProviders(){return Application.getInstance().getterProviders()}setterProviders(t){const e=this.providers;Array.isArray(e)&&(this.providers=e.filter(e=>{return!t.find(t=>e===t)}),this.providers=this.getterProviders().concat(t))}static setProviders(t){Application.getInstance().setterProviders(t)}static registerProvider(t){if(!isClass(t))throw new Exception("Provider Error","The first argument must be a class");new t(Application.getInstance())}static registerProviders(t){Array.isArray(t)&&t.map(t=>{Application.registerProvider(t)})}static setConfig(t,e){Application.getInstance().singleton(t,e)}static getConfig(t,e){if(Application.getInstance().has(t))return Application.getInstance().get(t);if(isEmpty(e))throw new Exception("Application Config Error","Configuration information does not exist");return e}static setAppConfig(t){Application.setConfig("APP_CONFIG",t)}static getAppConfig(t){return Application.getConfig("APP_CONFIG",{})[t]}static bindAdapter(t,e){if(!isClass(t))throw new Exception("Adapter Error","The first argument must be a class");e=isEmpty(e)?new t:new t(e);Application.getInstance().setterAdapter(t,e)}setterAdapter(t,e){if(!isClass(t))throw new Exception("Adapter Error","The first argument must be a class");Application.getAdapter(t)&&console.warn("Adapter Warn",`The adapter ${t.name||""} is already bound`),this.adapters.set(t,e)}static getAdapter(t){if(isClass(t))return Application.getInstance().getterAdapter(t);throw new Exception("Adapter Error","The argument must be a class")}getterAdapter(t){return this.adapters.get(t)}static getService(t){return Application.getInstance().get(t)}static getInstance(){let t=this.instance;return t=t&&t instanceof Application?t:Application.instance=new this}static run(t){const e=Application.lifecycle();e.created(),e.mounted(),e.unmounted(),isFunction(t)&&t()}}class Command{$payload;$helper;$http;constructor(...t){this.$payload=[...t],this.$helper=Application.getService("$helper"),this.$http=Application.getService("$helper").http}$transform=(t,e)=>Array.isArray(t)?t.map(t=>this.$transform(t,e)):e(t);$filterEmptyFields(e){return isEmpty(e)?{}:(Object.keys(e).map(t=>{isEmpty(e[t])&&delete e[t]}),e)}}class Transformer{data;payload;constructor(t,e){this.data=t,this.payload=e}transform(t,e){return t}create(s){return Array.isArray(this.data)?this.data.map((t,e)=>isFunction(s)?s(t,e):this.transform(t)):isFunction(s)?s(this.data,0):this.transform(this.data)}formatNumber(t,e=-1,s="",r="."){"number"!=typeof t&&(t=isString(t)?parseFloat(t):0);var i=(t=isNaN(t)?0:t).toString().split("."),i=(e=parseInt(e),e=isNaN(Math.abs(e))||-1===e?-1:Math.abs(e),i[1]&&-1===e?e=i[1].length:i[1]||-1!==e||(e=0),s="string"==typeof s?s:",",r=r||".",t<0?"-":"");let n;const a=parseInt(t=Math.abs(+t||0).toFixed(e),10).toString();return i+((n=3<(n=a.length)?n%3:0)?a.substr(0,n)+s:"")+a.substr(n).replace(/(\d{3})(?=\d)/g,"$1"+s)+(e?r+Math.abs(Number(t)-Number(a)).toFixed(e).slice(2):"")}formatDate(t=Date.now()){if(isString(t))return isNaN(Date.parse(t))?this.formatDate():this.formatDate(Date.parse(t));const e=new Date(t),s=e.getFullYear(),r=e.getMonth()+1<10?"0"+(e.getMonth()+1):e.getMonth()+1,i=e.getDate()<10?"0"+e.getDate():e.getDate(),n=e.getHours()<10?"0"+e.getHours():e.getHours(),a=e.getMinutes()<10?"0"+e.getMinutes():e.getMinutes(),o=e.getSeconds()<10?"0"+e.getSeconds():e.getSeconds();var t=e.getDay(),c=0<=e.getHours()&&n<12?"AM":"PM",p=0<=e.getHours()&&n<12?"上午":"下午";return{Y:s.toString(),M:r.toString(),D:i.toString(),h:n.toString(),m:a.toString(),s:o.toString(),week:["日","一","二","三","四","五","六"][t],ap:c,apCn:p}}}class Lib{static typeOf(t,e){return typeof t===e}static getTag(t){return Object.prototype.toString.call(t)}static isFunction(t){return Lib.typeOf(t,"function")&&"[object Function]"===Lib.getTag(t)}static isString(t){return Lib.typeOf(t,"string")||"[object String]"===Lib.getTag(t)}static isNumber(t){return"number"==typeof t}static isObject(t){return"[object Object]"===Lib.getTag(t)}static isUndefined(t){return void 0===t||"[object Undefined]"===Lib.getTag(t)}static isNull(t){return null===t||"[object Null]"===Lib.getTag(t)}static isEmpty(t){return!t&&0!==t||!(!Lib.isObject(t)&&!Array.isArray(t))&&("{}"===JSON.stringify(t)||"[]"===JSON.stringify(t))}static isClass(t){if(Lib.isFunction(t)){const e=t.toString();if(void 0!==t.prototype&&t.prototype.constructor===t){if("class "===e.slice(0,6))return!0;if(2<=Object.getOwnPropertyNames(t.prototype).length)return!0;/^function\s+\(|^function\s+anonymous\(/.test(e)}}return!1}static strTrim(t,e,s){return e?"L"===s?t.replace(new RegExp("^\\"+e+"+","g"),""):"R"===s?t.replace(new RegExp("\\"+e+"+$","g"),""):t.replace(new RegExp("^\\"+e+"+|\\"+e+"+$","g"),""):t.replace(/^\s+|\s+$/g,"")}}class HttpAdapterInterface{http;method="POST";url="";data={};headers={};extra={};constructor(t){if("function"!=typeof t)throw new Exception("HTTP Adapter Error","The first argument must be a function");this.http=t}setConfig({method:t,url:e,data:s,headers:r,extra:i}){this.method=t??this.method,this.url=e??this.url,this.data=s??this.data,this.headers=r??this.headers,this.extra=i??this.extra}request(){return new Promise((e,s)=>{this.http({method:this.method,url:this.url,data:this.data,headers:this.headers,extra:this.extra}).then(t=>{e(t)}).catch(t=>{s(t)})})}}class AxiosAdapter extends HttpAdapterInterface{request(){return new Promise((e,s)=>{this.http({method:this.method,url:this.url,data:this.data,headers:this.headers,...this.extra}).then(t=>{e(t)}).catch(t=>{s(t)})})}}class UniRequestAdapter extends HttpAdapterInterface{request(){return new Promise((e,s)=>{this.http({method:this.method,url:this.url,data:this.data,header:this.headers,...this.extra,success:t=>{e(t)},fail:t=>{s(t)}})})}}class ServiceProvider{app;constructor(t){this.app=t,this.register()}}class CommandProvider extends ServiceProvider{register(){this.app.singleton("$command",()=>{console.log("COMMAND_REGISTERED")})}}class WebStorage{type="localStorage";storage="localStorage"===this.type?localStorage:sessionStorage;constructor({type:t}){this.setConfig({type:t})}get(t){if(!t)return this.getAll();if(isString(t))return this.storage.getItem(t);throw new Exception("","The first parameter is a string")}set(t,e){if("length"===t)throw new Exception("WebStorage Error","The key of data must not be length");this.storage.setItem(t,JSON.stringify(e))}save(t,e){this.set(t,e)}delete(t){t?Array.isArray(t)?t.map(t=>{this.delete(t)}):this.storage.removeItem(t):this.clear()}remove(t){this.delete(t)}clear(){this.storage.clear()}keys(){var t=this.getAll();return Object.keys(t)}getAll(){const{length:t,...e}=this.storage;return e}setConfig({type:t}){this.type=t}}class Service{app;constructor(t){this.app=t}}class Helper extends Service{env(){return{}}webStorage(t,e,s){const r=new WebStorage({type:t});if(e&&!Lib.isString(e))throw new Exception("WebStorage Error","The first argument must be a string");return void 0!==e||Lib.isString(e)?void 0===s?r.get(e):void r.save(e,s):r.getAll()}storage(t,e){return this.webStorage("localStorage",t,e)}cookie(){}session(t,e){return this.webStorage("sessionStorage",t,e)}async http(t,e,s={},r={}){return Application.getService("$request").http(t,e,s,r)}async send(t,e,s,r,i=!0){if(!this.app.has("$request"))throw new Exception("RequestService Error","");let n=await Application.getService("$request").send(t,e,r,i);return Lib.isFunction(s)&&(n=s(n)),i?n:n.data}checkAuth(){}cookies(t,e){}request(t,e,s){}}class HelperProvider extends ServiceProvider{register(){this.app.singleton("$helper",()=>new Helper(this.app))}}class RESTful{isRESTful=!0;api;requestData;constructor(t,e,s){this.isRESTful=s??this.isRESTful,this.api=t,this.requestData=isObject(e)?e:{}}create(){return this.isRESTful?this.transformer():{api:this.api,data:this.requestData}}transformer(){const t=Object.keys(this.requestData),r={},i={},e=(t.map(t=>{var e=t.match(/^__/g),s=t.replace(/^__/g,"");e?r[s]=this.requestData[t]:i[s]=this.requestData[t]}),this.api.match(/<(.*?)>/g)),s={};if(e&&Array.isArray(e)){const n=e.map(t=>{const e=t.replace(/(^<)|(>$)/g,"");t=e.split("=");return 2===t.length?(s[t[0]]=t[1],t[0]):(s[e]=null,e)});return Object.assign(s,r),this.api=this.api.replace(/=(.*?)>/g,">"),n.map(t=>{this.api=this.api.replace(`<${t}>`,s[t])}),{api:this.api,data:i}}return{api:this.api,data:this.requestData}}}function queryStringify(t,e){const s=[];for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(isArray(t[r])||isObject(t[r])?e?s.push(queryStringify(t[r],`${e}[${r}]`)):s.push(queryStringify(t[r],r)):e?s.push(encodeURIComponent(`${e}[${r}]`)+"="+encodeURIComponent(t[r])):s.push(encodeURIComponent(r)+"="+encodeURIComponent(t[r])));return s.join("&")}function strTrim(t,e,s){return e?"L"===s?t.replace(new RegExp("^\\"+e+"+","g"),""):"R"===s?t.replace(new RegExp("\\"+e+"+$","g"),""):t.replace(new RegExp("^\\"+e+"+|\\"+e+"+$","g"),""):t.replace(/^\s+|\s+$/g,"")}class HttpService extends Service{_http=null;_api={};_headers={};_host="";_isRESTful=!0;_carryingData={};_mode="REQUEST_PAYLOAD";$helper=null;_requestMiddleware;_responseMiddleware;_context={request:{hairstyle:null,body:null},response:null};constructor(t,{HTTP_ADAPTER:e,HTTP_API:s,HTTP_HOST:r,IS_RESTFUL:i,CONTENT_TYPE:n,DATA_CARRYING:a,REQUEST_MIDDLEWARE:o,RESPONSE_MIDDLEWARE:c}){super(t),this._http=e??this._http,this._api=s??this._api,this._host=r??this._host,this._isRESTful=i??!0,this.setContentType(n),this.setDataCarry(a.REQUEST_HEADERS,a.REQUEST_DATA),this._requestMiddleware=isFunction(o)?o:t=>t,this._responseMiddleware=isFunction(c)?c:t=>t}setContentType(t){"REQUEST_PAYLOAD"===t||"JSON"===t?(this._mode=t,this.setHeader("Content-Type","application/json")):"FORM_DATA"===t&&(this._mode=t,this.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"))}getContentType(){return this._mode}setDataCarry(e,s){if(isObject(e)){const t=Object.keys(e);Array.isArray(t)&&t.map(t=>{this.carryingHandle(t,e[t],"REQUEST_HEADERS")})}if(isObject(s)){const r=Object.keys(s);Array.isArray(r)&&r.map(t=>{this.carryingHandle(t,s[t],"REQUEST_DATA")})}}carryingHandle(e,s,r="REQUEST_HEADERS"){if(e&&s)if(isFunction(s))try{"REQUEST_HEADERS"===r?this.setHeader(e,s()):"REQUEST_DATA"===r&&this.setData(e,s())}catch(t){console.warn("Application Error",t)}else if(isString(s)||isNumber(s))try{"REQUEST_HEADERS"===r?this.setHeader(e,s):"REQUEST_DATA"===r&&this.setData(e,s)}catch(t){console.warn("Application Error",t)}else{let t=null;"LOCAL"===s||"LOCAL_STORAGE"===s?t=Application.getService("$helper").storage(e):"SESSION"===s?t=Application.getService("$helper").session(e):"COOKIES"===s?t=Application.getService("$helper").cookies(e):"STORAGE"===s&&(t=Application.getService("$helper").storage(e)),"REQUEST_HEADERS"===r?this.setHeader(e,t):"REQUEST_DATA"===r&&this.setData(e,t)}}async http(t,e,s={},r={}){try{return this._context.request={...this._context.request,...this.getParameters(t,e)},this._context.request.headers={...this._context.request.headers,...s},this._context.request.extra=r,this._context=this._requestMiddleware(this._context),this._http.setConfig(this._context.request),await this.request(this._context.request.hairstyle[3])}catch(t){console.warn("Request config warn",t)}}async request(t){try{var e=await this._http.request();try{this._context.response=e;var s=await this._responseMiddleware(this._context);return t?s.response:s.response.data}catch(t){console.warn("Response middleware Error",t)}}catch(t){if(t&&t.response)switch(t.response.status){case 400:t.message="请求参数错误";break;case 401:t.message="未授权,请登录";break;case 403:t.message="跨域拒绝访问";break;case 404:t.message="请求地址出错: "+t.response.config.url;break;case 408:t.message="请求超时";break;case 500:t.message="服务器内部错误";break;case 501:t.message="服务未实现";break;case 502:t.message="网关错误";break;case 503:t.message="服务不可用";break;case 504:t.message="网关超时";break;case 505:t.message="HTTP版本不受支持"}throw this._context.response={...t.response,message:t.message},this._responseMiddleware(this._context),t}}async send(t,e,s={},r=!1){s.host&&(this._host=s.host),s.headers&&this.setHeaders(s.headers),s.mode&&this.setContentType(s.mode);const i=this.makeHairstyle(t);return r&&(i[3]=r),this.http(i,e,{})}makeHairstyle(t){let e;if(!(e="string"==typeof t?this._api[t]:t)&&!t)throw new Exception("The api route does not exist","ApiRouteError");t=e[0];let s=["POST",this.getContentType()];var r=e[2]??!0,i=e[3]??!1;return isArray(e[1])?s=[e[1][0].toUpperCase()||"POST",e[1][1]||this.getContentType()]:isString(e[1])&&(s=[e[1].toUpperCase(),this.getContentType()]),[t,s,r,i]}getParameters(t,e){var[t,s,r,i]=this.makeHairstyle(t);let n={};0<Object.keys(this._carryingData).length&&r&&(e={...this._carryingData,...e}),0<Object.keys(this._headers).length&&r&&(n=this._headers);const a=new RESTful(t,e,this._isRESTful).create();let o=strTrim(this._host,"/")+"/"+strTrim(a.api,"/");var c=s?.[0],p=s?.[1];return this.setContentType(p),"GET"===c&&isObject(a.data)&&(o=isEmpty(a.data)?o:o+"?"+queryStringify(a.data)),{api:a.api.trim(),url:o,method:c,data:a.data,auth:r,hairstyle:[t,s,r,i],body:e,payload:a.data,headers:n}}setHeaders(t={}){this._headers={...this._headers,...t}}setHeader(t,e){this._headers[t]=e}setData(t,e){this._carryingData[t]=e}}class HttpProvider extends ServiceProvider{register(){var t=Application.getAppConfig("HTTP_CONFIG").HTTP_ADAPTER,e=Application.getAppConfig("HTTP_CONFIG").HTTP_LIB;const s=Application.getAppConfig("HTTP_CONFIG").HTTP_API,r=Application.getAppConfig("HTTP_CONFIG").HTTP_HOST,i=Application.getAppConfig("HTTP_CONFIG").IS_RESTFUL,n=Application.getAppConfig("HTTP_CONFIG").CONTENT_TYPE,a=Application.getAppConfig("HTTP_CONFIG").DATA_CARRYING;if(!t||!e)throw new Exception("ADAPTER Error","Bind http adapter error");Application.bindAdapter(t,e);const o=Application.getAdapter(t),c=Application.getAppConfig("HTTP_CONFIG").REQUEST_MIDDLEWARE,p=Application.getAppConfig("HTTP_CONFIG").RESPONSE_MIDDLEWARE;this.app.singleton("$request",()=>new HttpService(this.app,{HTTP_ADAPTER:o,HTTP_API:s,HTTP_HOST:r,IS_RESTFUL:i,CONTENT_TYPE:n,DATA_CARRYING:a,REQUEST_MIDDLEWARE:c,RESPONSE_MIDDLEWARE:p}))}}async function $http(t,e,s={},r={}){return Application.getService("$request").http(t,e,s,r)}class EventBus{_events=new Map;static _instance;static getInstance(){return EventBus._instance&&EventBus._instance instanceof EventBus||(EventBus._instance=new EventBus),EventBus._instance}static getEvents(){return EventBus.getInstance()._events}static getEventsSize(){return EventBus.getInstance()._events.size}static getEvent(t){return EventBus.getInstance()._events.get(t)}static hasEvent(t){return EventBus.getInstance()._events.has(t)}static deleteEvent(t){return EventBus.getInstance()._events.delete(t),EventBus.hasEvent(t)}static setEvent(t,e){return EventBus.hasEvent(t),EventBus.getInstance()._events.set(t,e)}static on(t,e){return isFunction(e)||console.warn("The second argument to the on method must be a function"),EventBus.setEvent(t,e)}static emit(t,...e){if(isFunction(EventBus.getEvent(t)))return EventBus.getEvent(t)(...e);console.error(`You need to bind the ${t} event and method before emit`)}static once(t,...e){EventBus.emit(t,...e),EventBus.off(t)}static off(t){if(Array.isArray(t)){const e=t.map(t=>EventBus.off(t));return e.indexOf(!1)<0}return!!EventBus.hasEvent(t)&&EventBus.getInstance()._events.delete(t)}}function defineAppConfig(t){return t}function defineHttpConfig(t){return t}function defineHttpApis(t){return t}function defineHttpApiMap(t){return t}Application.setProviders([CommandProvider,HelperProvider,HttpProvider]);export{$http,AxiosAdapter,Command,Container,EventBus,Exception,Lib,ServiceProvider,Transformer,UniRequestAdapter,Application as default,defineAppConfig,defineHttpApiMap,defineHttpApis,defineHttpConfig,isArray,isBoolean,isClass,isColor,isDate,isEmail,isEmpty,isEmptyObject,isExist,isFunction,isNull,isNumber,isObject,isPhone,isPromise,isRegExp,isString,isUndefined,isWindow,queryStringify}; //# sourceMappingURL=pdd.js.map