@ezuikit/utils-tools 2.0.2 → 2.0.4

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/README.md CHANGED
@@ -1 +1 @@
1
- ## 工具
1
+ ## 工具
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
- * @ezuikit/utils-tools v2.0.2
2
+ * @ezuikit/utils-tools v2.0.4
3
3
  * tools utils
4
- * Copyright (c) 2026-01-05 Ezviz-OpenBiz
4
+ * Copyright (c) 2026-06-09 Ezviz-OpenBiz
5
5
  * Released under the MIT License.
6
6
  */
7
- "use strict";var getQuery=function(url){var query=url.split("?")[1],obj={};if(query)for(var vars=query.split("&"),i=0;i<vars.length;i++){var pair=vars[i].split("=");obj[pair[0]]=decodeURIComponent(pair[1])}return obj};function parseEzopenUrl(url){var obj={};if(/^ezopen:\/\//.test(url)){if(url.includes("@")){var endIndex=url.indexOf("@"),startIndex=url.indexOf("//");obj.validateCode=url.substring(startIndex+2,endIndex),url=url.replace(obj.validateCode+"@","")}obj.protocol=url.split("//")[0],obj.search=url.split("?")[1]?"?"+url.split("?")[1]:"",obj.hostname=url.split("/")[2],obj.origin=obj.protocol+"//"+obj.hostname,obj.pathname=url.split("?")[0].replace(obj.origin,""),obj.href=url;var pathnames=obj.pathname.split("/"),lastPath=pathnames[2].split(".");return obj.deviceSerial=pathnames[1],obj.channelNo=lastPath[0],obj.type=lastPath[lastPath.length-1],"live"===obj.type&&(obj.definition=lastPath.length>2?lastPath[1]:"sd"),"rec"===obj.type&&pathnames[2]&&(obj.recType=pathnames[2].includes(".cloud.")?"cloud":""),obj.searchParams=getQuery(url),obj}return{}}var codec={h264:1,h265:2,h266:4,vp8:8,vp9:16,av1:32};function _array_like_to_array(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _instanceof(left,right){return null!=right&&"undefined"!=typeof Symbol&&right[Symbol.hasInstance]?!!right[Symbol.hasInstance](left):left instanceof right}function _create_for_of_iterator_helper_loose(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o,minLen){if(o){if("string"==typeof o)return _array_like_to_array(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array(o,minLen):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var DateTime=function(){function DateTime(){}return DateTime.fillZero=function(num,len){return void 0===len&&(len=2),num.toString().padStart(len,"0")},DateTime.format=function(input,format){var date;if(_instanceof(input,Date))date=input;else{if("number"!=typeof input&&"string"!=typeof input)throw new Error("Invalid date input");date=DateTime.toDate(input+"")}for(var _step,result=format,_iterator=_create_for_of_iterator_helper_loose([[/(yyyy|YYYY)/g,function(){return DateTime.fillZero(date.getFullYear(),4)}],[/(yy|YY)/g,function(){return DateTime.fillZero(date.getFullYear()%100,2)}],[/(MM)/g,function(){return DateTime.fillZero(date.getMonth()+1,2)}],[/(M)/g,function(){return(date.getMonth()+1).toString()}],[/(dd|DD)/g,function(){return DateTime.fillZero(date.getDate(),2)}],[/(d|D)/g,function(){return date.getDate().toString()}],[/(HH|hh)/g,function(){return DateTime.fillZero(date.getHours(),2)}],[/(H|h)/g,function(){return date.getHours().toString()}],[/(mm)/g,function(){return DateTime.fillZero(date.getMinutes(),2)}],[/(m)/g,function(){return date.getMinutes().toString()}],[/(ss|SS)/g,function(){return DateTime.fillZero(date.getSeconds(),2)}],[/(s|S)/g,function(){return date.getSeconds().toString()}],[/(fff)/g,function(){return DateTime.fillZero(date.getMilliseconds(),3)}]]);!(_step=_iterator()).done;){var _step_value=_step.value,regexp=_step_value[0],fn=_step_value[1];result=result.replace(regexp,fn)}return result},DateTime.toDate=function(str){if(_instanceof(str,Date))return str;str=(str+"").trim().replace(/\/|\./gi,"-"),/^\d{4}$/.test(str)&&(str+="-01"),/^\d{4}-\d{2}$/.test(str)&&(str+="-01");try{return/^\d{4}-\d{2}-\d{2}$/.test(str)?new Date(+str.slice(0,4),+str.slice(5,7)-1,+str.slice(8,10),0,0,0):/^\d{8}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),0,0)):/^\d{14}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),+str.slice(8,10),+str.slice(10,12),+str.slice(12,14))):/^\d{13}$/.test(str)?new Date(Number(str)):/^\d{10}$/.test(str)?new Date(1e3*Number(str)):new Date(str)}catch(error){throw new Error("Invalid date string")}},DateTime.diff=function(date1,date2,type){void 0===type&&(type="second");var d1=DateTime.toDate(date1),d2=DateTime.toDate(date2);return"second"===type?Math.floor((d1.getTime()-d2.getTime())/1e3):"minute"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60):"hour"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60):"day"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60/24):Math.abs(d1.getTime()-d2.getTime())},DateTime}();exports.DateTime=DateTime,exports.addVc=function(url,codecs){void 0===codecs&&(codecs=["h264"]);var vc=(codecs||["h264"]).reduce(function(acc,key){return key=key.toLowerCase(),acc+(codec[key]||0)},0),host=url.split("?")[0],query=url.split("?")[1];return query=(query||"").split("&").filter(function(item){return!/^vc=\d?/.test(item)}).join("&"),host+"?"+(query+=(query?"&":"")+"vc="+vc)},exports.getQuery=getQuery,exports.getStaticPath=function(path,base){void 0===base&&(base="");var protocolReg=/^(https?:\/\/|^\/\/)/;if(""===path||void 0===path)return"";if(protocolReg.test(path))return path;path=path.replace(/\/+/g,"/"),base=protocolReg.test(base||"")?base:window.location.href;try{return new URL(path,base).href}catch(error){return path}},exports.isHttp=function(url){return/^http[s]?:\/\//.test(url)},exports.isMobile=function(agent){var _navigator,_navigator1,_navigator2,_window;return/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone|Opera Mini)/i.test(null!=agent?agent:null==(_navigator=navigator)?void 0:_navigator.userAgent)||/Macintosh/i.test(agent||(null==(_navigator1=navigator)?void 0:_navigator1.userAgent))&&(null==(_navigator2=navigator)?void 0:_navigator2.maxTouchPoints)>1||!!(null==(_window=window)?void 0:_window.__IS_MOBILE_SIMULATOR__)},exports.isRealMobile=function(agent){var _navigator,ua=(null!=agent?agent:null==(_navigator=navigator)?void 0:_navigator.userAgent).toLowerCase();if(/ipad|tablet|playbook|silk|android(?!.*mobile)/i.test(ua))return!1;var hasTouch="ontouchstart"in window||navigator.maxTouchPoints>0;return/android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(ua)&&hasTouch},exports.parseEzopenUrl=parseEzopenUrl,exports.pick=function(obj,keys){return Object.entries(obj).reduce(function(acc,param){var key=param[0],value=param[1];return keys.includes(key)&&(acc[key]=value),acc},{})},exports.switchEzopenUrl=function(url,options){var _ref=null!=options?options:{},type=_ref.type,recType=_ref.recType,search=_ref.search,definition=_ref.definition,channelNo=_ref.channelNo,deviceSerial=_ref.deviceSerial,validateCode=_ref.validateCode,obj=parseEzopenUrl(url);if(search){var ns=Object.assign({},obj.searchParams,getQuery("?"+search.replace("?","")));search=Object.entries(ns).reduce(function(acc,param){var key=param[0],value=param[1];return""===value?acc:acc+=key+"="+encodeURIComponent(value)+"&"},"?").replace(/&$/,"")}else search=obj.search;return type=type||obj.type,recType=null!=recType?recType:obj.recType,definition=null!=definition?definition:obj.definition,channelNo=channelNo||obj.channelNo,deviceSerial=deviceSerial||obj.deviceSerial,validateCode=null!=validateCode?validateCode:obj.validateCode,obj.protocol+"//"+(validateCode?validateCode+"@":"")+obj.hostname+"/"+deviceSerial+"/"+channelNo+("rec"===type&&recType?"."+recType:"")+("live"===type&&"hd"===definition?"."+definition:"")+"."+type+search};
7
+ "use strict";var getQuery=function(url){var query=url.split("?")[1],obj={};if(query)for(var vars=query.split("&"),i=0;i<vars.length;i++){var pair=vars[i].split("=");obj[pair[0]]=decodeURIComponent(pair[1])}return obj};function parseEzopenUrl(url){var obj={};if(/^ezopen:\/\//.test(url)){if(url.includes("@")){var endIndex=url.indexOf("@"),startIndex=url.indexOf("//");obj.validateCode=url.substring(startIndex+2,endIndex),url=url.replace(obj.validateCode+"@","")}obj.protocol=url.split("//")[0],obj.search=url.split("?")[1]?"?"+url.split("?")[1]:"",obj.hostname=url.split("/")[2],obj.origin=obj.protocol+"//"+obj.hostname,obj.pathname=url.split("?")[0].replace(obj.origin,""),obj.href=url;var pathnames=obj.pathname.split("/"),lastPath=pathnames[2].split(".");return obj.deviceSerial=pathnames[1],obj.channelNo=lastPath[0],obj.type=lastPath[lastPath.length-1],"live"===obj.type&&(obj.definition=lastPath.length>2?lastPath[1]:"sd"),"rec"===obj.type&&pathnames[2]&&(obj.recType=pathnames[2].includes(".cloud.")?"cloud":""),obj.searchParams=getQuery(url),obj}return{}}var codec={h264:1,h265:2,h266:4,vp8:8,vp9:16,av1:32};function _array_like_to_array(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _instanceof(left,right){return null!=right&&"undefined"!=typeof Symbol&&right[Symbol.hasInstance]?!!right[Symbol.hasInstance](left):left instanceof right}function _create_for_of_iterator_helper_loose(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o,minLen){if(o){if("string"==typeof o)return _array_like_to_array(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array(o,minLen):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var DateTime=function(){function DateTime(){}return DateTime.normalizeUnit=function(unit){return"year"===unit||"y"===unit||"年"===unit?"year":"month"===unit||"M"===unit||"月"===unit?"month":"day"===unit||"d"===unit||"日"===unit?"day":"hour"===unit||"h"===unit||"时"===unit?"hour":"minute"===unit||"m"===unit||"分"===unit?"minute":"second"},DateTime.daysInMonth=function(year,month){return new Date(year,month+1,0).getDate()},DateTime.shiftMonth=function(baseDate,months){var result=new Date(baseDate.getTime()),currentDate=result.getDate();result.setDate(1),result.setMonth(result.getMonth()+months);var maxDate=DateTime.daysInMonth(result.getFullYear(),result.getMonth());return result.setDate(Math.min(currentDate,maxDate)),result},DateTime.add=function(input,value,unit){if(void 0===unit&&(unit="day"),!Number.isFinite(value))throw new Error("Invalid value");var baseDate=DateTime.toDate(input),normalizedUnit=DateTime.normalizeUnit(unit);if("year"===normalizedUnit)return DateTime.shiftMonth(baseDate,12*value);if("month"===normalizedUnit)return DateTime.shiftMonth(baseDate,value);var result=new Date(baseDate.getTime());return result.setTime(result.getTime()+value*{day:864e5,hour:36e5,minute:6e4,second:1e3}[normalizedUnit]),result},DateTime.subtract=function(input,value,unit){return void 0===unit&&(unit="day"),DateTime.add(input,-value,unit)},DateTime.fillZero=function(num,len){return void 0===len&&(len=2),num.toString().padStart(len,"0")},DateTime.format=function(input,format){var date;if(_instanceof(input,Date))date=input;else{if("number"!=typeof input&&"string"!=typeof input)throw new Error("Invalid date input");date=DateTime.toDate(input+"")}for(var _step,result=format,_iterator=_create_for_of_iterator_helper_loose([[/(yyyy|YYYY)/g,function(){return DateTime.fillZero(date.getFullYear(),4)}],[/(yy|YY)/g,function(){return DateTime.fillZero(date.getFullYear()%100,2)}],[/(MM)/g,function(){return DateTime.fillZero(date.getMonth()+1,2)}],[/(M)/g,function(){return(date.getMonth()+1).toString()}],[/(dd|DD)/g,function(){return DateTime.fillZero(date.getDate(),2)}],[/(d|D)/g,function(){return date.getDate().toString()}],[/(HH|hh)/g,function(){return DateTime.fillZero(date.getHours(),2)}],[/(H|h)/g,function(){return date.getHours().toString()}],[/(mm)/g,function(){return DateTime.fillZero(date.getMinutes(),2)}],[/(m)/g,function(){return date.getMinutes().toString()}],[/(ss|SS)/g,function(){return DateTime.fillZero(date.getSeconds(),2)}],[/(s|S)/g,function(){return date.getSeconds().toString()}],[/(fff)/g,function(){return DateTime.fillZero(date.getMilliseconds(),3)}]]);!(_step=_iterator()).done;){var _step_value=_step.value,regexp=_step_value[0],fn=_step_value[1];result=result.replace(regexp,fn)}return result},DateTime.toDate=function(str){if(_instanceof(str,Date))return str;str=(str+"").trim().replace(/\/|\./gi,"-"),/^\d{4}$/.test(str)&&(str+="-01"),/^\d{4}-\d{2}$/.test(str)&&(str+="-01");try{return/^\d{4}-\d{2}-\d{2}$/.test(str)?new Date(+str.slice(0,4),+str.slice(5,7)-1,+str.slice(8,10),0,0,0):/^\d{8}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),0,0,0)):/^\d{14}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),+str.slice(8,10),+str.slice(10,12),+str.slice(12,14))):/^\d{13}$/.test(str)?new Date(Number(str)):/^\d{10}$/.test(str)?new Date(1e3*Number(str)):new Date(str)}catch(error){throw new Error("Invalid date string")}},DateTime.diff=function(date1,date2,type){void 0===type&&(type="second");var d1=DateTime.toDate(date1),d2=DateTime.toDate(date2);return"second"===type?Math.floor((d1.getTime()-d2.getTime())/1e3):"minute"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60):"hour"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60):"day"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60/24):Math.abs(d1.getTime()-d2.getTime())},DateTime}();exports.DateTime=DateTime,exports.addVc=function(url,codecs){void 0===codecs&&(codecs=["h264"]);var vc=(codecs||["h264"]).reduce((function(acc,key){return key=key.toLowerCase(),acc+(codec[key]||0)}),0),host=url.split("?")[0],query=url.split("?")[1];return query=(query||"").split("&").filter((function(item){return!/^vc=\d?/.test(item)})).join("&"),host+"?"+(query+=(query?"&":"")+"vc="+vc)},exports.getQuery=getQuery,exports.getStaticPath=function(path,base){void 0===base&&(base="");var protocolReg=/^(https?:\/\/|^\/\/)/;if(""===path||void 0===path)return"";if(protocolReg.test(path))return path;path=path.replace(/\/+/g,"/"),base=protocolReg.test(base||"")?base:window.location.href;try{return new URL(path,base).href}catch(error){return path}},exports.isHttp=function(url){return/^http[s]?:\/\//.test(url)},exports.isMobile=function(agent){var _navigator,_navigator1,_navigator2,_window;return/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone|Opera Mini)/i.test(null!=agent?agent:null==(_navigator=navigator)?void 0:_navigator.userAgent)||/Macintosh/i.test(agent||(null==(_navigator1=navigator)?void 0:_navigator1.userAgent))&&(null==(_navigator2=navigator)?void 0:_navigator2.maxTouchPoints)>1||!!(null==(_window=window)?void 0:_window.__IS_MOBILE_SIMULATOR__)},exports.parseEzopenUrl=parseEzopenUrl,exports.pick=function(obj,keys){return Object.entries(obj).reduce((function(acc,param){var key=param[0],value=param[1];return keys.includes(key)&&(acc[key]=value),acc}),{})},exports.switchEzopenUrl=function(url,options){var _ref=null!=options?options:{},type=_ref.type,recType=_ref.recType,search=_ref.search,definition=_ref.definition,channelNo=_ref.channelNo,deviceSerial=_ref.deviceSerial,validateCode=_ref.validateCode,obj=parseEzopenUrl(url);if(search){var ns=Object.assign({},obj.searchParams,getQuery("?"+search.replace("?","")));search=Object.entries(ns).reduce((function(acc,param){var key=param[0],value=param[1];return""===value?acc:acc+=key+"="+encodeURIComponent(value)+"&"}),"?").replace(/&$/,"")}else search=obj.search;return type=type||obj.type,recType=null!=recType?recType:obj.recType,definition=null!=definition?definition:obj.definition,channelNo=channelNo||obj.channelNo,deviceSerial=deviceSerial||obj.deviceSerial,validateCode=null!=validateCode?validateCode:obj.validateCode,obj.protocol+"//"+(validateCode?validateCode+"@":"")+obj.hostname+"/"+deviceSerial+"/"+channelNo+("rec"===type&&recType?"."+recType:"")+("live"===type&&"hd"===definition?"."+definition:"")+"."+type+search};
package/dist/index.umd.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
- * @ezuikit/utils-tools v2.0.2
2
+ * @ezuikit/utils-tools v2.0.4
3
3
  * tools utils
4
- * Copyright (c) 2026-01-05 Ezviz-OpenBiz
4
+ * Copyright (c) 2026-06-09 Ezviz-OpenBiz
5
5
  * Released under the MIT License.
6
6
  */
7
- !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Tools={})}(this,function(exports){"use strict";var getQuery=function(url){var query=url.split("?")[1],obj={};if(query)for(var vars=query.split("&"),i=0;i<vars.length;i++){var pair=vars[i].split("=");obj[pair[0]]=decodeURIComponent(pair[1])}return obj};function parseEzopenUrl(url){var obj={};if(/^ezopen:\/\//.test(url)){if(url.includes("@")){var endIndex=url.indexOf("@"),startIndex=url.indexOf("//");obj.validateCode=url.substring(startIndex+2,endIndex),url=url.replace(obj.validateCode+"@","")}obj.protocol=url.split("//")[0],obj.search=url.split("?")[1]?"?"+url.split("?")[1]:"",obj.hostname=url.split("/")[2],obj.origin=obj.protocol+"//"+obj.hostname,obj.pathname=url.split("?")[0].replace(obj.origin,""),obj.href=url;var pathnames=obj.pathname.split("/"),lastPath=pathnames[2].split(".");return obj.deviceSerial=pathnames[1],obj.channelNo=lastPath[0],obj.type=lastPath[lastPath.length-1],"live"===obj.type&&(obj.definition=lastPath.length>2?lastPath[1]:"sd"),"rec"===obj.type&&pathnames[2]&&(obj.recType=pathnames[2].includes(".cloud.")?"cloud":""),obj.searchParams=getQuery(url),obj}return{}}var codec={h264:1,h265:2,h266:4,vp8:8,vp9:16,av1:32};function _array_like_to_array(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _instanceof(left,right){return null!=right&&"undefined"!=typeof Symbol&&right[Symbol.hasInstance]?!!right[Symbol.hasInstance](left):left instanceof right}function _create_for_of_iterator_helper_loose(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o,minLen){if(o){if("string"==typeof o)return _array_like_to_array(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array(o,minLen):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var DateTime=function(){function DateTime(){}return DateTime.fillZero=function(num,len){return void 0===len&&(len=2),num.toString().padStart(len,"0")},DateTime.format=function(input,format){var date;if(_instanceof(input,Date))date=input;else{if("number"!=typeof input&&"string"!=typeof input)throw new Error("Invalid date input");date=DateTime.toDate(input+"")}for(var _step,result=format,_iterator=_create_for_of_iterator_helper_loose([[/(yyyy|YYYY)/g,function(){return DateTime.fillZero(date.getFullYear(),4)}],[/(yy|YY)/g,function(){return DateTime.fillZero(date.getFullYear()%100,2)}],[/(MM)/g,function(){return DateTime.fillZero(date.getMonth()+1,2)}],[/(M)/g,function(){return(date.getMonth()+1).toString()}],[/(dd|DD)/g,function(){return DateTime.fillZero(date.getDate(),2)}],[/(d|D)/g,function(){return date.getDate().toString()}],[/(HH|hh)/g,function(){return DateTime.fillZero(date.getHours(),2)}],[/(H|h)/g,function(){return date.getHours().toString()}],[/(mm)/g,function(){return DateTime.fillZero(date.getMinutes(),2)}],[/(m)/g,function(){return date.getMinutes().toString()}],[/(ss|SS)/g,function(){return DateTime.fillZero(date.getSeconds(),2)}],[/(s|S)/g,function(){return date.getSeconds().toString()}],[/(fff)/g,function(){return DateTime.fillZero(date.getMilliseconds(),3)}]]);!(_step=_iterator()).done;){var _step_value=_step.value,regexp=_step_value[0],fn=_step_value[1];result=result.replace(regexp,fn)}return result},DateTime.toDate=function(str){if(_instanceof(str,Date))return str;str=(str+"").trim().replace(/\/|\./gi,"-"),/^\d{4}$/.test(str)&&(str+="-01"),/^\d{4}-\d{2}$/.test(str)&&(str+="-01");try{return/^\d{4}-\d{2}-\d{2}$/.test(str)?new Date(+str.slice(0,4),+str.slice(5,7)-1,+str.slice(8,10),0,0,0):/^\d{8}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),0,0)):/^\d{14}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),+str.slice(8,10),+str.slice(10,12),+str.slice(12,14))):/^\d{13}$/.test(str)?new Date(Number(str)):/^\d{10}$/.test(str)?new Date(1e3*Number(str)):new Date(str)}catch(error){throw new Error("Invalid date string")}},DateTime.diff=function(date1,date2,type){void 0===type&&(type="second");var d1=DateTime.toDate(date1),d2=DateTime.toDate(date2);return"second"===type?Math.floor((d1.getTime()-d2.getTime())/1e3):"minute"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60):"hour"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60):"day"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60/24):Math.abs(d1.getTime()-d2.getTime())},DateTime}();exports.DateTime=DateTime,exports.addVc=function(url,codecs){void 0===codecs&&(codecs=["h264"]);var vc=(codecs||["h264"]).reduce(function(acc,key){return key=key.toLowerCase(),acc+(codec[key]||0)},0),host=url.split("?")[0],query=url.split("?")[1];return query=(query||"").split("&").filter(function(item){return!/^vc=\d?/.test(item)}).join("&"),host+"?"+(query+=(query?"&":"")+"vc="+vc)},exports.getQuery=getQuery,exports.getStaticPath=function(path,base){void 0===base&&(base="");var protocolReg=/^(https?:\/\/|^\/\/)/;if(""===path||void 0===path)return"";if(protocolReg.test(path))return path;path=path.replace(/\/+/g,"/"),base=protocolReg.test(base||"")?base:window.location.href;try{return new URL(path,base).href}catch(error){return path}},exports.isHttp=function(url){return/^http[s]?:\/\//.test(url)},exports.isMobile=function(agent){var _navigator,_navigator1,_navigator2,_window;return/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone|Opera Mini)/i.test(null!=agent?agent:null==(_navigator=navigator)?void 0:_navigator.userAgent)||/Macintosh/i.test(agent||(null==(_navigator1=navigator)?void 0:_navigator1.userAgent))&&(null==(_navigator2=navigator)?void 0:_navigator2.maxTouchPoints)>1||!!(null==(_window=window)?void 0:_window.__IS_MOBILE_SIMULATOR__)},exports.isRealMobile=function(agent){var _navigator,ua=(null!=agent?agent:null==(_navigator=navigator)?void 0:_navigator.userAgent).toLowerCase();if(/ipad|tablet|playbook|silk|android(?!.*mobile)/i.test(ua))return!1;var hasTouch="ontouchstart"in window||navigator.maxTouchPoints>0;return/android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(ua)&&hasTouch},exports.parseEzopenUrl=parseEzopenUrl,exports.pick=function(obj,keys){return Object.entries(obj).reduce(function(acc,param){var key=param[0],value=param[1];return keys.includes(key)&&(acc[key]=value),acc},{})},exports.switchEzopenUrl=function(url,options){var _ref=null!=options?options:{},type=_ref.type,recType=_ref.recType,search=_ref.search,definition=_ref.definition,channelNo=_ref.channelNo,deviceSerial=_ref.deviceSerial,validateCode=_ref.validateCode,obj=parseEzopenUrl(url);if(search){var ns=Object.assign({},obj.searchParams,getQuery("?"+search.replace("?","")));search=Object.entries(ns).reduce(function(acc,param){var key=param[0],value=param[1];return""===value?acc:acc+=key+"="+encodeURIComponent(value)+"&"},"?").replace(/&$/,"")}else search=obj.search;return type=type||obj.type,recType=null!=recType?recType:obj.recType,definition=null!=definition?definition:obj.definition,channelNo=channelNo||obj.channelNo,deviceSerial=deviceSerial||obj.deviceSerial,validateCode=null!=validateCode?validateCode:obj.validateCode,obj.protocol+"//"+(validateCode?validateCode+"@":"")+obj.hostname+"/"+deviceSerial+"/"+channelNo+("rec"===type&&recType?"."+recType:"")+("live"===type&&"hd"===definition?"."+definition:"")+"."+type+search}});
7
+ !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Tools={})}(this,(function(exports){"use strict";var getQuery=function(url){var query=url.split("?")[1],obj={};if(query)for(var vars=query.split("&"),i=0;i<vars.length;i++){var pair=vars[i].split("=");obj[pair[0]]=decodeURIComponent(pair[1])}return obj};function parseEzopenUrl(url){var obj={};if(/^ezopen:\/\//.test(url)){if(url.includes("@")){var endIndex=url.indexOf("@"),startIndex=url.indexOf("//");obj.validateCode=url.substring(startIndex+2,endIndex),url=url.replace(obj.validateCode+"@","")}obj.protocol=url.split("//")[0],obj.search=url.split("?")[1]?"?"+url.split("?")[1]:"",obj.hostname=url.split("/")[2],obj.origin=obj.protocol+"//"+obj.hostname,obj.pathname=url.split("?")[0].replace(obj.origin,""),obj.href=url;var pathnames=obj.pathname.split("/"),lastPath=pathnames[2].split(".");return obj.deviceSerial=pathnames[1],obj.channelNo=lastPath[0],obj.type=lastPath[lastPath.length-1],"live"===obj.type&&(obj.definition=lastPath.length>2?lastPath[1]:"sd"),"rec"===obj.type&&pathnames[2]&&(obj.recType=pathnames[2].includes(".cloud.")?"cloud":""),obj.searchParams=getQuery(url),obj}return{}}var codec={h264:1,h265:2,h266:4,vp8:8,vp9:16,av1:32};function _array_like_to_array(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _instanceof(left,right){return null!=right&&"undefined"!=typeof Symbol&&right[Symbol.hasInstance]?!!right[Symbol.hasInstance](left):left instanceof right}function _create_for_of_iterator_helper_loose(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(it)return(it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=function(o,minLen){if(o){if("string"==typeof o)return _array_like_to_array(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return"Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_array_like_to_array(o,minLen):void 0}}(o))||allowArrayLike){it&&(o=it);var i=0;return function(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var DateTime=function(){function DateTime(){}return DateTime.normalizeUnit=function(unit){return"year"===unit||"y"===unit||"年"===unit?"year":"month"===unit||"M"===unit||"月"===unit?"month":"day"===unit||"d"===unit||"日"===unit?"day":"hour"===unit||"h"===unit||"时"===unit?"hour":"minute"===unit||"m"===unit||"分"===unit?"minute":"second"},DateTime.daysInMonth=function(year,month){return new Date(year,month+1,0).getDate()},DateTime.shiftMonth=function(baseDate,months){var result=new Date(baseDate.getTime()),currentDate=result.getDate();result.setDate(1),result.setMonth(result.getMonth()+months);var maxDate=DateTime.daysInMonth(result.getFullYear(),result.getMonth());return result.setDate(Math.min(currentDate,maxDate)),result},DateTime.add=function(input,value,unit){if(void 0===unit&&(unit="day"),!Number.isFinite(value))throw new Error("Invalid value");var baseDate=DateTime.toDate(input),normalizedUnit=DateTime.normalizeUnit(unit);if("year"===normalizedUnit)return DateTime.shiftMonth(baseDate,12*value);if("month"===normalizedUnit)return DateTime.shiftMonth(baseDate,value);var result=new Date(baseDate.getTime());return result.setTime(result.getTime()+value*{day:864e5,hour:36e5,minute:6e4,second:1e3}[normalizedUnit]),result},DateTime.subtract=function(input,value,unit){return void 0===unit&&(unit="day"),DateTime.add(input,-value,unit)},DateTime.fillZero=function(num,len){return void 0===len&&(len=2),num.toString().padStart(len,"0")},DateTime.format=function(input,format){var date;if(_instanceof(input,Date))date=input;else{if("number"!=typeof input&&"string"!=typeof input)throw new Error("Invalid date input");date=DateTime.toDate(input+"")}for(var _step,result=format,_iterator=_create_for_of_iterator_helper_loose([[/(yyyy|YYYY)/g,function(){return DateTime.fillZero(date.getFullYear(),4)}],[/(yy|YY)/g,function(){return DateTime.fillZero(date.getFullYear()%100,2)}],[/(MM)/g,function(){return DateTime.fillZero(date.getMonth()+1,2)}],[/(M)/g,function(){return(date.getMonth()+1).toString()}],[/(dd|DD)/g,function(){return DateTime.fillZero(date.getDate(),2)}],[/(d|D)/g,function(){return date.getDate().toString()}],[/(HH|hh)/g,function(){return DateTime.fillZero(date.getHours(),2)}],[/(H|h)/g,function(){return date.getHours().toString()}],[/(mm)/g,function(){return DateTime.fillZero(date.getMinutes(),2)}],[/(m)/g,function(){return date.getMinutes().toString()}],[/(ss|SS)/g,function(){return DateTime.fillZero(date.getSeconds(),2)}],[/(s|S)/g,function(){return date.getSeconds().toString()}],[/(fff)/g,function(){return DateTime.fillZero(date.getMilliseconds(),3)}]]);!(_step=_iterator()).done;){var _step_value=_step.value,regexp=_step_value[0],fn=_step_value[1];result=result.replace(regexp,fn)}return result},DateTime.toDate=function(str){if(_instanceof(str,Date))return str;str=(str+"").trim().replace(/\/|\./gi,"-"),/^\d{4}$/.test(str)&&(str+="-01"),/^\d{4}-\d{2}$/.test(str)&&(str+="-01");try{return/^\d{4}-\d{2}-\d{2}$/.test(str)?new Date(+str.slice(0,4),+str.slice(5,7)-1,+str.slice(8,10),0,0,0):/^\d{8}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),0,0,0)):/^\d{14}$/.test(str)?(str+="",new Date(+str.slice(0,4),+str.slice(4,6)-1,+str.slice(6,8),+str.slice(8,10),+str.slice(10,12),+str.slice(12,14))):/^\d{13}$/.test(str)?new Date(Number(str)):/^\d{10}$/.test(str)?new Date(1e3*Number(str)):new Date(str)}catch(error){throw new Error("Invalid date string")}},DateTime.diff=function(date1,date2,type){void 0===type&&(type="second");var d1=DateTime.toDate(date1),d2=DateTime.toDate(date2);return"second"===type?Math.floor((d1.getTime()-d2.getTime())/1e3):"minute"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60):"hour"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60):"day"===type?Math.floor((d1.getTime()-d2.getTime())/1e3/60/60/24):Math.abs(d1.getTime()-d2.getTime())},DateTime}();exports.DateTime=DateTime,exports.addVc=function(url,codecs){void 0===codecs&&(codecs=["h264"]);var vc=(codecs||["h264"]).reduce((function(acc,key){return key=key.toLowerCase(),acc+(codec[key]||0)}),0),host=url.split("?")[0],query=url.split("?")[1];return query=(query||"").split("&").filter((function(item){return!/^vc=\d?/.test(item)})).join("&"),host+"?"+(query+=(query?"&":"")+"vc="+vc)},exports.getQuery=getQuery,exports.getStaticPath=function(path,base){void 0===base&&(base="");var protocolReg=/^(https?:\/\/|^\/\/)/;if(""===path||void 0===path)return"";if(protocolReg.test(path))return path;path=path.replace(/\/+/g,"/"),base=protocolReg.test(base||"")?base:window.location.href;try{return new URL(path,base).href}catch(error){return path}},exports.isHttp=function(url){return/^http[s]?:\/\//.test(url)},exports.isMobile=function(agent){var _navigator,_navigator1,_navigator2,_window;return/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone|Opera Mini)/i.test(null!=agent?agent:null==(_navigator=navigator)?void 0:_navigator.userAgent)||/Macintosh/i.test(agent||(null==(_navigator1=navigator)?void 0:_navigator1.userAgent))&&(null==(_navigator2=navigator)?void 0:_navigator2.maxTouchPoints)>1||!!(null==(_window=window)?void 0:_window.__IS_MOBILE_SIMULATOR__)},exports.parseEzopenUrl=parseEzopenUrl,exports.pick=function(obj,keys){return Object.entries(obj).reduce((function(acc,param){var key=param[0],value=param[1];return keys.includes(key)&&(acc[key]=value),acc}),{})},exports.switchEzopenUrl=function(url,options){var _ref=null!=options?options:{},type=_ref.type,recType=_ref.recType,search=_ref.search,definition=_ref.definition,channelNo=_ref.channelNo,deviceSerial=_ref.deviceSerial,validateCode=_ref.validateCode,obj=parseEzopenUrl(url);if(search){var ns=Object.assign({},obj.searchParams,getQuery("?"+search.replace("?","")));search=Object.entries(ns).reduce((function(acc,param){var key=param[0],value=param[1];return""===value?acc:acc+=key+"="+encodeURIComponent(value)+"&"}),"?").replace(/&$/,"")}else search=obj.search;return type=type||obj.type,recType=null!=recType?recType:obj.recType,definition=null!=definition?definition:obj.definition,channelNo=channelNo||obj.channelNo,deviceSerial=deviceSerial||obj.deviceSerial,validateCode=null!=validateCode?validateCode:obj.validateCode,obj.protocol+"//"+(validateCode?validateCode+"@":"")+obj.hostname+"/"+deviceSerial+"/"+channelNo+("rec"===type&&recType?"."+recType:"")+("live"===type&&"hd"===definition?"."+definition:"")+"."+type+search}}));
@@ -1,65 +1,238 @@
1
+ /**
2
+ * 可被解析为日期的输入类型。
3
+ *
4
+ * 可以是以下三种之一:
5
+ * - `Date`:原生 Date 对象
6
+ * - `number`:时间戳,支持毫秒(13 位)或秒(10 位)
7
+ * - `string`:日期字符串,支持 ISO 格式及多种常见格式
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const a: DateLike = new Date();
12
+ * const b: DateLike = 1709452800000;
13
+ * const c: DateLike = '2023-10-01';
14
+ * ```
15
+ */
1
16
  export type DateLike = Date | number | string;
17
+ /**
18
+ * 日期时间单位。
19
+ *
20
+ * 为了便于使用,同一单位提供了多种等价写法:
21
+ * - 年:`year` | `y` | `年`
22
+ * - 月:`month` | `M` | `月`
23
+ * - 日:`day` | `d` | `日`
24
+ * - 时:`hour` | `h` | `时`
25
+ * - 分:`minute` | `m` | `分`
26
+ * - 秒:`second` | `s` | `秒`
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * DateTime.add('2023-10-01', 1, 'day');
31
+ * DateTime.add('2023-10-01', 1, 'd');
32
+ * DateTime.add('2023-10-01', 1, '日');
33
+ * ```
34
+ */
35
+ export type DateUnit = 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'y' | 'M' | 'd' | 'h' | 'm' | 's' | '年' | '月' | '日' | '时' | '分' | '秒';
36
+ /**
37
+ * 日期时间工具类。
38
+ *
39
+ * 提供日期的解析、格式化、加减运算以及时间差计算等常用能力。所有方法均为静态方法,
40
+ * 无需实例化即可直接调用。输入统一使用 {@link DateLike} 类型,单位统一使用
41
+ * {@link DateUnit} 类型,并支持中文与英文缩写等多种写法。
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import DateTime from './datetime';
46
+ *
47
+ * // 解析
48
+ * DateTime.toDate('2023-10-01');
49
+ *
50
+ * // 格式化
51
+ * DateTime.format(new Date(), 'yyyy-MM-dd HH:mm:ss');
52
+ *
53
+ * // 加减运算
54
+ * DateTime.add('2023-10-01', 1, 'month');
55
+ * DateTime.subtract('2023-10-01', 2, 'day');
56
+ *
57
+ * // 时间差
58
+ * DateTime.diff('2023-10-02', '2023-10-01', 'day'); // 1
59
+ * ```
60
+ */
2
61
  declare class DateTime {
3
62
  /**
4
- * 数字格式化 十位补0
5
- * @param {number | string} num - 要格式化的数字
6
- * @returns {string} 返回的数字格式化后的字符串
63
+ * 将 {@link DateUnit} 的各种写法归一化为标准的英文单位。
7
64
  *
65
+ * 例如 `y`、`年` 都会被归一化为 `year`。当传入未匹配到的值时,
66
+ * 兜底返回 `second`。
67
+ *
68
+ * @param unit - 待归一化的日期时间单位
69
+ * @returns 归一化后的标准单位(`year` | `month` | `day` | `hour` | `minute` | `second`)
70
+ * @example
71
+ * ```ts
72
+ * DateTime['normalizeUnit']('年'); // 'year'
73
+ * DateTime['normalizeUnit']('d'); // 'day'
74
+ * ```
75
+ */
76
+ private static normalizeUnit;
77
+ /**
78
+ * 计算指定年月的天数(即该月的最大日期)。
79
+ *
80
+ * 通过构造下个月的第 0 天来获取当前月份的最后一天,可自动处理闰年的 2 月。
81
+ *
82
+ * @param year - 四位年份,例如 `2024`
83
+ * @param month - 月份索引,从 0 开始(0 表示 1 月,11 表示 12 月)
84
+ * @returns 该月份包含的天数(28 ~ 31)
85
+ * @example
86
+ * ```ts
87
+ * DateTime['daysInMonth'](2024, 1); // 29(2024 年为闰年)
88
+ * DateTime['daysInMonth'](2023, 1); // 28
89
+ * ```
90
+ */
91
+ private static daysInMonth;
92
+ /**
93
+ * 在基准日期上偏移指定的月份数,并对溢出的日期进行夹取(clamp)。
94
+ *
95
+ * 例如对 1 月 31 日加 1 个月时,由于 2 月没有 31 日,会被夹取到该月的最后一天,
96
+ * 避免出现日期自动进位到下个月的问题。
97
+ *
98
+ * @param baseDate - 基准日期
99
+ * @param months - 偏移的月份数,可为负数表示往前偏移
100
+ * @returns 偏移后的新 Date 对象(不会修改入参)
101
+ * @example
102
+ * ```ts
103
+ * DateTime['shiftMonth'](new Date(2023, 0, 31), 1); // 2023-02-28
104
+ * DateTime['shiftMonth'](new Date(2023, 2, 15), -1); // 2023-02-15
105
+ * ```
106
+ */
107
+ private static shiftMonth;
108
+ /**
109
+ * 日期时间加法。
110
+ *
111
+ * 在给定日期上增加指定的时间量。年、月运算会对溢出日期做夹取处理
112
+ * (参见 {@link DateTime.shiftMonth}),日、时、分、秒运算则基于毫秒进行精确累加。
113
+ *
114
+ * @param input - 输入日期,{@link DateLike} 类型
115
+ * @param value - 增加的数值,可为负数(负数等价于减法)
116
+ * @param unit - 增加单位,默认 `day`,支持 {@link DateUnit} 的所有写法
117
+ * @returns 计算后的新 Date 对象(不会修改入参)
118
+ * @throws 当 `value` 不是有限数字(如 `NaN`、`Infinity`)时抛出 `Invalid value`
119
+ * @example
120
+ * ```ts
121
+ * DateTime.add('2023-10-01', 1, 'day'); // 2023-10-02
122
+ * DateTime.add('2023-10-01', 1, 'month'); // 2023-11-01
123
+ * DateTime.add('2023-01-31', 1, 'month'); // 2023-02-28(自动夹取)
124
+ * DateTime.add('2023-10-01', -2, 'hour'); // 2023-09-30 22:00:00
125
+ * ```
126
+ */
127
+ static add(input: DateLike, value: number, unit?: DateUnit): Date;
128
+ /**
129
+ * 日期时间减法。
130
+ *
131
+ * 在给定日期上减少指定的时间量,内部等价于调用 {@link DateTime.add} 并取负数。
132
+ *
133
+ * @param input - 输入日期,{@link DateLike} 类型
134
+ * @param value - 减少的数值,可为负数(负数等价于加法)
135
+ * @param unit - 减少单位,默认 `day`,支持 {@link DateUnit} 的所有写法
136
+ * @returns 计算后的新 Date 对象(不会修改入参)
137
+ * @throws 当 `value` 不是有限数字(如 `NaN`、`Infinity`)时抛出 `Invalid value`
138
+ * @example
139
+ * ```ts
140
+ * DateTime.subtract('2023-10-02', 1, 'day'); // 2023-10-01
141
+ * DateTime.subtract('2023-11-01', 1, 'month'); // 2023-10-01
142
+ * DateTime.subtract('2023-10-01', 30, 'minute'); // 2023-09-30 23:30:00
143
+ * ```
144
+ */
145
+ static subtract(input: DateLike, value: number, unit?: DateUnit): Date;
146
+ /**
147
+ * 数字格式化,在左侧补 0 至指定长度。
148
+ *
149
+ * @param num - 要格式化的数字
150
+ * @param len - 目标字符串长度,默认 `2`;当数字本身长度已达到或超过该值时原样返回
151
+ * @returns 补 0 后的字符串
8
152
  * @example
9
- * ```js
10
- * fillZero(0) // "00"
11
- * fillZero(9) // "09"
12
- * fillZero(23) // "23"
153
+ * ```ts
154
+ * DateTime.fillZero(0); // "00"
155
+ * DateTime.fillZero(9); // "09"
156
+ * DateTime.fillZero(23); // "23"
157
+ * DateTime.fillZero(5, 3); // "005"
13
158
  * ```
14
159
  */
15
160
  static fillZero(num: number, len?: number): string;
16
161
  /**
17
- * 日期时间格式化库
18
- * 支持常用模式:yyyy-MM-dd HH:mm:ss,MM/dd/yyyy,yyyy年MM月dd日 等
19
- * 支持自定义格式
20
- * @param input - 输入的日期,可以是 Date 对象、时间戳(毫秒)或 ISO 格式字符串
21
- * @param format - 输出的日期格式字符串,支持 yyyy, MM, dd, HH, mm, ss 等占位符
162
+ * 日期时间格式化。
163
+ *
164
+ * 将日期按照给定的格式模板输出为字符串,支持常用模式(如 `yyyy-MM-dd HH:mm:ss`、
165
+ * `MM/dd/yyyy`、`yyyy年MM月dd日`)以及自定义组合。
166
+ *
167
+ * 支持的占位符:
168
+ * - `yyyy` / `YYYY`:四位年份;`yy` / `YY`:两位年份
169
+ * - `MM`:两位月份;`M`:不补零月份
170
+ * - `dd` / `DD`:两位日期;`d` / `D`:不补零日期
171
+ * - `HH` / `hh`:两位小时(24 小时制);`H` / `h`:不补零小时
172
+ * - `mm`:两位分钟;`m`:不补零分钟
173
+ * - `ss` / `SS`:两位秒;`s` / `S`:不补零秒
174
+ * - `fff`:三位毫秒
175
+ *
176
+ * @param input - 输入日期,可以是 Date 对象、时间戳(毫秒/秒)或日期字符串
177
+ * @param format - 输出格式模板,包含上述占位符
22
178
  * @returns 格式化后的日期字符串
23
- * @throws 如果输入的日期格式不正确或无法解析,将抛出错误
179
+ * @throws 当输入既不是 Date,也不是 number 或 string 时抛出 `Invalid date input`
24
180
  * @example
25
- * DateTime.format(new Date(), "yyyy-MM-dd HH:mm:ss") // "2023-10-01 12:00:00"
26
- * DateTime.format("2023-10-01T12:00:00Z", "MM/dd/yyyy") // "10/01/2023"
27
- * DateTime.format("2023-10-01", "MM/dd/yyyy") // "10/01/2023"
28
- * DateTime.format("2023/10/01", "MM/dd/yyyy") // "10/01/2023"
29
- * DateTime.format("2023/10/01T01:01:01", "MM/dd/yyyy") // "10/01/2023"
30
- * DateTime.format(1709452800000, "yyyy年MM月dd日") // "2024年01月01日"
181
+ * ```ts
182
+ * DateTime.format(new Date(), 'yyyy-MM-dd HH:mm:ss'); // "2023-10-01 12:00:00"
183
+ * DateTime.format('2023-10-01T12:00:00Z', 'MM/dd/yyyy'); // "10/01/2023"
184
+ * DateTime.format('2023-10-01', 'MM/dd/yyyy'); // "10/01/2023"
185
+ * DateTime.format('2023/10/01', 'MM/dd/yyyy'); // "10/01/2023"
186
+ * DateTime.format(1709452800000, 'yyyy年MM月dd日'); // "2024年03月03日"
187
+ * ```
31
188
  */
32
189
  static format(input: DateLike, format: string): string;
33
190
  /**
34
- * 解析日期字符串为 Date 对象
35
- * 支持 ISO 格式、常见日期格式等
36
- * @param str - 日期字符串
191
+ * 将多种格式的输入解析为 Date 对象。
192
+ *
193
+ * 解析时会先将 `/`、`.` 等分隔符统一替换为 `-`,再根据字符串长度与格式匹配相应的解析规则:
194
+ * - 仅年份(`2023`)或年月(`2023-10`):自动补全为该月/年的第一天
195
+ * - 标准日期(`2023-10-01`):按本地时间 00:00:00 解析
196
+ * - 紧凑日期(`20231001`)/ 紧凑日期时间(`20231001010101`):按位切分解析
197
+ * - 13 位数字:按毫秒时间戳解析;10 位数字:按秒时间戳解析
198
+ * - 其余情况回退到原生 `new Date()` 解析
199
+ *
200
+ * 若入参已是 Date 对象,则原样返回(不会拷贝)。
201
+ *
202
+ * @param str - 待解析的日期,{@link DateLike} 类型
37
203
  * @returns 解析后的 Date 对象
38
- * @throws 如果日期字符串格式不正确,将抛出错误
204
+ * @throws 当解析过程中发生异常时抛出 `Invalid date string`
39
205
  * @example
40
- * DateTime.Date("2023") // new Date("2023-10-01T00:00:00")
41
- * DateTime.Date("2023-01") // new Date("2023-10-01T00:00:00")
42
- * DateTime.Date("2023-10-01") // new Date("2023-10-01T00:00:00")
43
- * DateTime.Date("2023/10/01") // new Date("2023-10-01T00:00:00")
44
- * DateTime.Date("2023.10.01") // new Date("2023-10-01T00:00:00")
45
- * DateTime.Date("20241001010101") // new Date("2024-10-01T01:01:01")
46
- * DateTime.Date("1709452800000") // new Date("2024-03-03T16:00:00") // 毫秒
47
- * DateTime.Date("1709452800") // new Date("2024-03-03T16:00:00") // 秒
206
+ * ```ts
207
+ * DateTime.toDate('2023'); // 2023-01-01 00:00:00
208
+ * DateTime.toDate('2023-01'); // 2023-01-01 00:00:00
209
+ * DateTime.toDate('2023-10-01'); // 2023-10-01 00:00:00
210
+ * DateTime.toDate('2023/10/01'); // 2023-10-01 00:00:00
211
+ * DateTime.toDate('2023.10.01'); // 2023-10-01 00:00:00
212
+ * DateTime.toDate('20241001010101'); // 2024-10-01 01:01:01
213
+ * DateTime.toDate('1709452800000'); // 毫秒时间戳
214
+ * DateTime.toDate('1709452800'); // 秒时间戳
215
+ * ```
48
216
  */
49
217
  static toDate(str: DateLike): Date;
50
218
  /**
51
- * 对比时间差
52
- * @param date1 - 第一个日期
53
- * @param date2 - 第二个日期
54
- * @param type - 时间单位
55
- * @returns 时间差
219
+ * 计算两个日期之间的时间差(`date1 - date2`)。
220
+ *
221
+ * 按指定单位返回差值并向下取整(`Math.floor`)。当 `date1` 早于 `date2` 时结果为负数。
222
+ * 若 `type` 不属于已知单位,则返回两者毫秒差的绝对值。
223
+ *
224
+ * @param date1 - 第一个日期(被减数),{@link DateLike} 类型
225
+ * @param date2 - 第二个日期(减数),{@link DateLike} 类型
226
+ * @param type - 时间单位,支持 `second`(默认)、`minute`、`hour`、`day`;其他值返回毫秒差绝对值
227
+ * @returns 按指定单位计算的时间差
228
+ * @throws 当任一入参无法被 {@link DateTime.toDate} 解析时抛出 `Invalid date string`
56
229
  * @example
57
230
  * ```ts
58
- * DateTime.diff('2023-10-01', '2023-10-02') // 86400
59
- * DateTime.diff('2023-10-01', '2023-10-02', 'minute') // 1440
60
- * DateTime.diff('2023-10-01', '2023-10-02', 'hour') // 24
61
- * DateTime.diff('2023-10-01', '2023-10-02', 'day') // 1
62
- * DateTime.diff('2023-10-01', '2023-10-02', 'month') // 0.041666666666666664
231
+ * DateTime.diff('2023-10-02', '2023-10-01'); // 86400(秒)
232
+ * DateTime.diff('2023-10-02', '2023-10-01', 'minute'); // 1440
233
+ * DateTime.diff('2023-10-02', '2023-10-01', 'hour'); // 24
234
+ * DateTime.diff('2023-10-02', '2023-10-01', 'day'); // 1
235
+ * DateTime.diff('2023-10-01', '2023-10-02', 'day'); // -1
63
236
  * ```
64
237
  */
65
238
  static diff(date1: DateLike, date2: DateLike, type?: string): number;
@@ -1,9 +1,9 @@
1
1
  import { parseEzopenUrl, switchEzopenUrl, type EzopenURL, type SwitchEzpoenOptions, type EzopenType, type EzopenRecType, type EzopenDefinition } from './ezopenUrl';
2
2
  import { isHttp } from './isHttp';
3
- import { isMobile, isRealMobile } from './isMobile';
3
+ import { isMobile } from './isMobile';
4
4
  import { getQuery } from './query';
5
5
  import { pick } from './pick';
6
6
  import { getStaticPath } from './getStaticPath';
7
7
  import { addVc } from './addVc';
8
8
  import DateTime, { type DateLike } from './datetime';
9
- export { parseEzopenUrl, switchEzopenUrl, type EzopenURL, type SwitchEzpoenOptions, type EzopenType, type EzopenRecType, type EzopenDefinition, type DateLike, isHttp, isMobile, isRealMobile, getQuery, pick, getStaticPath, addVc, DateTime, };
9
+ export { parseEzopenUrl, switchEzopenUrl, type EzopenURL, type SwitchEzpoenOptions, type EzopenType, type EzopenRecType, type EzopenDefinition, type DateLike, isHttp, isMobile, getQuery, pick, getStaticPath, addVc, DateTime, };
package/package.json CHANGED
@@ -1,22 +1,10 @@
1
1
  {
2
2
  "name": "@ezuikit/utils-tools",
3
- "version": "2.0.2",
3
+ "version": "2.0.4",
4
4
  "description": "tools utils",
5
5
  "main": "dist/index.js",
6
6
  "umd": "dist/index.umd.js",
7
7
  "types": "dist/types/index.d.ts",
8
- "scripts": {
9
- "dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs --watch",
10
- "build": "npm run clean && cross-env NODE_ENV=production rollup --config rollup.config.mjs && npm run types && npm run docs",
11
- "types": "tsc src/index.ts --emitDeclarationOnly --declaration --declarationDir dist/types",
12
- "docs": "rimraf docs && typedoc --out docs src",
13
- "prebuild": "npm run clean",
14
- "test": "jest --coverage",
15
- "test:watch": "jest --coverage --watch",
16
- "clean": "rimraf docs dist coverage",
17
- "lint": "eslint .",
18
- "fmt": "prettier --write \"src/*.{ts,tsx,js,mjs,cjs,jsx,md,html}\""
19
- },
20
8
  "files": [
21
9
  "dist"
22
10
  ],
@@ -25,13 +13,18 @@
25
13
  "ezuikit-utils",
26
14
  "utils"
27
15
  ],
28
- "devDependencies": {
29
- "@config/rollup": "workspace: *"
30
- },
31
16
  "author": "Ezviz-OpenBiz",
32
17
  "license": "MIT",
33
18
  "publishConfig": {
34
19
  "access": "public",
35
20
  "registry": "https://registry.npmjs.org/"
36
- }
37
- }
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Ezviz-OpenBiz/EZUIKit-player-utils.git"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/Ezviz-OpenBiz/EZUIKit-player-utils/issues"
28
+ },
29
+ "homepage": "https://github.com/Ezviz-OpenBiz/EZUIKit-player-utils#readme"
30
+ }