utils-uniapp 1.0.0

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.
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 扁平化树结构(深度优先,父节点排在子节点前)
3
+ * @param { T[] } tree 树结构数组
4
+ * @param { string } key 子节点字段名,默认'children'
5
+ * @param { function } fn 每项回调
6
+ */
7
+ export function flatWithKey<T>(tree: T[], key?: string, fn?: (item: T, index: number) => void): T[];
8
+
9
+ /**
10
+ * 深度查找树中第一个满足条件的节点
11
+ * @param { T[] } tree 树结构数组
12
+ * @param { function } fn 谓词函数
13
+ * @param { string } childrenKey 子节点字段名,默认'children'
14
+ */
15
+ export function findTreeItem<T>(tree: T[], fn: (item: T, index: number) => boolean, childrenKey?: string): T | null;
16
+
17
+ /**
18
+ * 为树节点挂载$parent父引用与$index索引(返回浅拷贝新树)
19
+ * @param { T[] } tree 树结构数组
20
+ * @param { string } childrenKey 子节点字段名,默认'children'
21
+ * @param { string } parentKey 父引用字段名,默认'$parent'
22
+ * @param { any } parent 起始父节点,默认null
23
+ * @param { string } indexKey 索引字段名,默认'$index'
24
+ */
25
+ export function treeItemSetParent<T extends Record<string, any>>(
26
+ tree: T[],
27
+ childrenKey?: string,
28
+ parentKey?: string,
29
+ parent?: any,
30
+ indexKey?: string
31
+ ): T[];
32
+
33
+ /**
34
+ * 获取节点到根节点的路径数组(需先用treeItemSetParent挂载$parent)
35
+ * @param { T } item 目标节点
36
+ * @param { string } key 父引用字段名,默认'$parent'
37
+ */
38
+ export function getTreePath<T>(item: T, key?: string): T[];
39
+
40
+ /**
41
+ * 过滤树结构(保留满足条件的节点,递归处理子节点)
42
+ * @param { T[] } tree 树结构数组
43
+ * @param { function } fn 谓词函数
44
+ * @param { string } childrenKey 子节点字段名,默认'children'
45
+ */
46
+ export function filterTree<T>(tree: T[], fn: (item: T, index: number) => boolean, childrenKey?: string): T[];
47
+
48
+ /**
49
+ * 多级分组(支持多字段联合分组,倒序遍历)
50
+ * @param { Array<string | string[]> } keys 分组字段(末位可为字段数组,联合分组)
51
+ * @param { T[] } arr 数据数组
52
+ * @param { function } callback 每项回调(item, quote分组附加对象)
53
+ * @param { function } callbackAll 每项回调(item, index)
54
+ * @param { string } join 联合分组字段连接符,默认','
55
+ * @param { number } num 递归用分组层级,默认keys.length
56
+ * @param { boolean } flag 是否校验参数,默认true
57
+ */
58
+ export function groupBy<T extends Record<string, any>>(
59
+ keys: Array<string | string[]>,
60
+ arr: T[],
61
+ callback?: (item: T, quote: Record<string, any>) => void,
62
+ callbackAll?: (item: T, index: number) => void,
63
+ join?: string,
64
+ num?: number,
65
+ flag?: boolean
66
+ ): Array<{ key: string | string[]; value: any; [key: string]: any }>;
67
+
68
+ /**
69
+ * 倒序遍历数组
70
+ * @param { T[] } arr 数组
71
+ * @param { function } callback 回调(item, index)
72
+ */
73
+ export function reverseForEach<T>(arr: T[], callback: (item: T, index: number) => void): void;
74
+
75
+ /**
76
+ * 交换数组两项位置
77
+ * @param { T[] } arr 数组
78
+ * @param { number } o 索引一
79
+ * @param { number } k 索引二
80
+ */
81
+ export function exchangeArrP<T>(arr: T[], o: number, k: number): void;
@@ -0,0 +1,35 @@
1
+ /** 日期信息(格式化占位符对应值,isPad为true时补零) */
2
+ export interface DateInfo {
3
+ year: number;
4
+ month: number;
5
+ date: number;
6
+ hour: number;
7
+ minute: number;
8
+ second: number;
9
+ millisecond: number;
10
+ yyyy: string;
11
+ MM: string;
12
+ dd: string;
13
+ HH: string;
14
+ mm: string;
15
+ ss: string;
16
+ ms: string;
17
+ }
18
+
19
+ /**
20
+ * 日期格式化(占位符:yyyy、MM、dd、HH、mm、ss、ms)
21
+ * @param { Date | number | string } date 日期,默认当前时间
22
+ * @param { 'date' | 'datetime' | string | function } formatter 'date'即'yyyy-MM-dd','datetime'即'yyyy-MM-dd HH:mm:ss',或自定义占位符字符串/函数
23
+ * @param { boolean } isPad 是否补零,默认true
24
+ */
25
+ export function getDate(
26
+ date?: Date | number | string,
27
+ formatter?: 'date' | 'datetime' | string | ((dateInfo: DateInfo) => string),
28
+ isPad?: boolean
29
+ ): string;
30
+
31
+ /**
32
+ * 宽松日期串规范化(自动补零、修正月日越界,如'2023-2-31' -> '2023-02-28')
33
+ * @param { string } str 日期字符串
34
+ */
35
+ export function dateFormat(str: string): string;
@@ -0,0 +1,103 @@
1
+ /** 文件编码类型 */
2
+ export type FsEncoding =
3
+ | 'ascii'
4
+ | 'base64'
5
+ | 'binary'
6
+ | 'hex'
7
+ | 'ucs2'
8
+ | 'ucs-2'
9
+ | 'utf16le'
10
+ | 'utf-16le'
11
+ | 'utf-8'
12
+ | 'utf8'
13
+ | 'latin1';
14
+
15
+ /** uni文件系统管理器(非H5平台) */
16
+ export const $fs: any;
17
+
18
+ /**
19
+ * 生成图片base64前缀
20
+ * @param { string } imgType 图片类型,默认'png'
21
+ */
22
+ export function getImgBase64Prefix(imgType?: string): string;
23
+
24
+ /** 读取文件参数(非H5平台) */
25
+ export interface ReadFileOptions {
26
+ filePath: string;
27
+ encoding: FsEncoding;
28
+ sync?: boolean;
29
+ opts?: { position?: number; length?: number; [key: string]: any };
30
+ }
31
+
32
+ /**
33
+ * 读取文件(非H5平台)
34
+ * @param { ReadFileOptions } opts 同步时返回内容或null(失败),异步时返回Promise
35
+ */
36
+ export function readFile(opts: ReadFileOptions & { sync?: false }): Promise<any>;
37
+ export function readFile(opts: ReadFileOptions & { sync: true }): string | ArrayBuffer | null;
38
+ export namespace readFile {
39
+ /** 同步读取文件 */
40
+ function sync(opts: Omit<ReadFileOptions, 'sync'>): string | ArrayBuffer | null;
41
+ }
42
+
43
+ /** 写文件结果 */
44
+ export interface WriteFileResult {
45
+ tempFilePath: string;
46
+ /** 删除该临时文件 */
47
+ unlink: () => void;
48
+ }
49
+
50
+ /** 写文件参数(非H5平台) */
51
+ export interface WriteFileOptions {
52
+ filePath: string;
53
+ data: string | ArrayBuffer;
54
+ encoding?: FsEncoding;
55
+ sync?: boolean;
56
+ opts?: Record<string, any>;
57
+ }
58
+
59
+ /**
60
+ * 写文件(非H5平台,encoding默认'binary')
61
+ * @param { WriteFileOptions } opts 同步时返回结果或null(失败),异步时返回Promise
62
+ */
63
+ export function writeFile(opts: WriteFileOptions & { sync?: false }): Promise<WriteFileResult>;
64
+ export function writeFile(opts: WriteFileOptions & { sync: true }): WriteFileResult | null;
65
+ export namespace writeFile {
66
+ /** 同步写文件 */
67
+ function sync(opts: Omit<WriteFileOptions, 'sync'>): WriteFileResult | null;
68
+ }
69
+
70
+ /** ArrayBuffer转临时文件参数(非H5平台) */
71
+ export interface ArraybufferTempPathOptions {
72
+ arraybuffer: ArrayBuffer;
73
+ /** 文件类型,默认'png' */
74
+ fileType?: string;
75
+ /** 转换方式,默认'canvas' */
76
+ method?: 'canvas' | 'fs';
77
+ /** method为'canvas'时的canvas节点选择器(#id) */
78
+ canvasId?: string;
79
+ width?: number;
80
+ height?: number;
81
+ /** 组件内调用时传入组件实例 */
82
+ ctx?: any;
83
+ /** method为'fs'时是否同步写文件 */
84
+ sync?: boolean;
85
+ }
86
+
87
+ /**
88
+ * ArrayBuffer转图片临时文件路径(非H5平台)
89
+ * @param { ArraybufferTempPathOptions } opts method为'fs'时返回writeFile结果,'canvas'时返回Promise(含tempFilePath)
90
+ */
91
+ export function getArraybufferTempPath(opts: ArraybufferTempPathOptions): Promise<any> | WriteFileResult | null;
92
+
93
+ /**
94
+ * 选择图片(优先uni.chooseMedia,降级uni.chooseImage,count默认1)
95
+ * @param { object } opts chooseMedia/chooseImage参数
96
+ */
97
+ export function chooseImg(opts?: { count?: number; [key: string]: any }): Promise<string[]>;
98
+
99
+ /**
100
+ * 下载网络图片并保存到相册(非H5平台)
101
+ * @param { string } url 图片地址
102
+ */
103
+ export function saveImageToPhotosAlbum(url: string): Promise<any>;
@@ -0,0 +1,35 @@
1
+ /** 定位结果(uni.getLocation success) */
2
+ export interface LocationResult {
3
+ latitude: number;
4
+ longitude: number;
5
+ accuracy: number;
6
+ altitude: number;
7
+ verticalAccuracy: number;
8
+ horizontalAccuracy: number;
9
+ errMsg: string;
10
+ [key: string]: any;
11
+ }
12
+
13
+ /**
14
+ * 获取当前定位(gcj02)
15
+ * @param { boolean } check 定位失败时是否检查并跳转错误页,默认false
16
+ */
17
+ export function getLocation(check?: boolean): Promise<LocationResult>;
18
+
19
+ /** 打开地图查看位置参数 */
20
+ export interface OpenLocationOptions {
21
+ /** 纬度 */
22
+ latitude: string | number;
23
+ /** 经度 */
24
+ longitude: string | number;
25
+ /** 位置名 */
26
+ name?: string;
27
+ /** 详细地址 */
28
+ address?: string;
29
+ }
30
+
31
+ /**
32
+ * 使用微信内置地图查看位置(失败时toast错误信息)
33
+ * @param { OpenLocationOptions } opts 位置参数
34
+ */
35
+ export function openLocation(opts: OpenLocationOptions): Promise<any>;
@@ -0,0 +1,108 @@
1
+ /** 请求Content-Type常量 */
2
+ export const CONTENT_TYPES: Readonly<{
3
+ JSON: string;
4
+ TEXT: string;
5
+ FORM_URLENCODED: string;
6
+ FORM_DATA: string;
7
+ }>;
8
+
9
+ /** uni请求task对象 */
10
+ interface UniTask {
11
+ abort: () => void;
12
+ [key: string]: any;
13
+ }
14
+
15
+ /** 请求取消控制器(仿axios CancelToken) */
16
+ export const CancelToken: {
17
+ caches: Record<string, UniTask>;
18
+ /** 注册任务 */
19
+ add(token: string, task: UniTask): void;
20
+ /** 移除任务缓存 */
21
+ delete(token: string): void;
22
+ /** 取消全部请求 */
23
+ cancelAll(): void;
24
+ /** 创建token与取消函数 */
25
+ source(): { token: string; cancel: () => void };
26
+ };
27
+
28
+ /**
29
+ * 包装uni异步API为Promise
30
+ * @param type uni接口名称
31
+ * @param opts 请求参数
32
+ */
33
+ export function promisifyRequest(
34
+ type: 'request' | 'uploadFile' | 'downloadFile',
35
+ opts: Record<string, any>
36
+ ): Promise<any>;
37
+
38
+ /** 开启loading计数 @param title 提示文案,默认'加载中...' */
39
+ export function startLoading(title?: string): void;
40
+
41
+ /** 关闭loading计数 */
42
+ export function endLoading(): void;
43
+
44
+ /** 基础配置 */
45
+ export interface RequestConfig {
46
+ baseURL?: string;
47
+ headers?: Record<string, any> | (() => Record<string, any>);
48
+ [key: string]: any;
49
+ }
50
+
51
+ /** 请求额外配置 */
52
+ export interface RequestOptions {
53
+ /** 非GET请求是否使用urlencode表单(默认true) */
54
+ qs?: boolean;
55
+ /** 是否展示错误提示 */
56
+ showError?: boolean;
57
+ /** 是否启用缓存 */
58
+ isCache?: boolean;
59
+ /** 缓存键名 */
60
+ cacheKey?: string;
61
+ /** 缓存过期时间(毫秒),默认1小时 */
62
+ cacheExpire?: number;
63
+ /** loading文案 */
64
+ loadingText?: string;
65
+ /** 是否展示loading,默认true */
66
+ loading?: boolean;
67
+ /** 请求前置拦截器 */
68
+ reqInterceptor?: ((args: any) => any) | ((args: any) => any)[];
69
+ /** 响应拦截器 */
70
+ resInterceptor?: ((res: any, opts: any, reload: (() => any) | null) => any) | Array<(res: any, opts: any, reload: (() => any) | null) => any>;
71
+ /** 错误拦截器 */
72
+ errInterceptor?: ((err: any) => any) | ((err: any) => any)[];
73
+ [key: string]: any;
74
+ }
75
+
76
+ /** 常规http请求实例(get/post) */
77
+ export type RequestFn = {
78
+ (url: string, method: string, params?: any, config?: RequestConfig, options?: RequestOptions): Promise<any>;
79
+ get(url: string, params?: any, config?: RequestConfig, options?: RequestOptions): Promise<any>;
80
+ post(url: string, params?: any, config?: RequestConfig, options?: RequestOptions): Promise<any>;
81
+ };
82
+
83
+ /**
84
+ * 创建常规http请求实例(get/post)
85
+ * @param defaultConfig 默认基础配置(baseURL、headers等)
86
+ * @param defaultOpts 默认额外配置(拦截器、缓存、loading等)
87
+ */
88
+ export function createRequest(defaultConfig?: RequestConfig, defaultOpts?: RequestOptions): RequestFn;
89
+
90
+ /**
91
+ * 创建上传文件实例
92
+ * @param defaultConfig 默认基础配置
93
+ * @param defaultOpts 默认额外配置
94
+ */
95
+ export function createUploadFile(
96
+ defaultConfig?: RequestConfig,
97
+ defaultOpts?: RequestOptions
98
+ ): (url: string, params: { filePath: string; keyName?: string; [key: string]: any }, config?: RequestConfig, options?: RequestOptions) => Promise<any>;
99
+
100
+ /**
101
+ * 创建下载文件实例
102
+ * @param defaultConfig 默认基础配置
103
+ * @param defaultOpts 默认额外配置
104
+ */
105
+ export function createDownloadFile(
106
+ defaultConfig?: RequestConfig,
107
+ defaultOpts?: RequestOptions
108
+ ): (url: string, params?: Record<string, any>, config?: RequestConfig, options?: RequestOptions) => Promise<any>;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("../index-e3f8a8ef.js"),A=require("../object/index.js"),C=Object.freeze({JSON:"application/json;charset=UTF-8",TEXT:"text/plain;charset=UTF-8",FORM_URLENCODED:"application/x-www-form-urlencoded;charset=UTF-8",FORM_DATA:"multipart/form-data;charset=UTF-8"}),T={caches:Object.create(null),add(e,t){this.caches[e]=t},delete(e){Reflect.deleteProperty(this.caches,e)},_cancel(e){const t=this.caches[e];typeof(t==null?void 0:t.abort)=="function"&&t.abort()},cancelAll(){Object.values(this.caches).forEach(e=>{typeof(e==null?void 0:e.abort)=="function"&&e.abort()}),this.caches=Object.create(null)},source(){const e=`${Date.now()}-${y.getRandomStr(16)}`;return{token:e,cancel:()=>this._cancel(e)}}};function b(e,t){return new Promise((r,a)=>{const o=uni[e]({...t,success(n){if(n.statusCode>=200&&n.statusCode<300)return r(n);a({type:"fail",res:n})},fail(n){a({type:"fail",res:n})},complete(){t.cancelToken&&T.delete(t.cancelToken)}});t.cancelToken&&T.add(t.cancelToken,o)})}let v=0,x=!1;function S(e){x||(x=!0,uni.showLoading({title:e,mask:!0}))}function P(){x&&(x=!1,uni.hideLoading())}function I(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"加载中...";v++,v===1&&S(e)}function D(){v>0&&v--,v===0&&P()}function w(e,t){return function(r,a,o,n){return e(r,t,a,o,n)}}function U(e){return typeof e=="function"?e:()=>e||{}}function _(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const a=U(t.headers)(),o=U(r.headers)(),n={...t,...r,headers:{...a,...o}},{headers:c,...l}=n;return{urlRes:e.startsWith("http")?e:n.baseURL?n.baseURL+e:e,headers:c,configRes:l}}function j(e){return typeof e=="function"?[e]:Array.isArray(e)?e.filter(t=>typeof t=="function"):[]}function k(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const a={qs:!0,showError:!0,isCache:!1,cacheKey:`api:${e.url}`,cacheExpire:1e3*60*60*1,loadingText:e.loadingText,loading:!0,reqInterceptor:o=>o,resInterceptor:o=>o,errInterceptor:()=>{},...t,...r};return["reqInterceptor","resInterceptor","errInterceptor"].forEach(o=>{const n=[...j(t[o]),...j(r[o])];a[o]=n.length?y.composeAsync(...n):c=>c}),a}function q(e,t){const r=Array.from(t);return()=>e(...A.cloneDeepWithDescriptors(r))}function E(e,t,r,a,o){return F.apply(this,arguments)}function F(){return F=y._asyncToGenerator(function*(e,t,r,a,o){let n;a.loading&&(I(a.loadingText),n=()=>{D(),n=null});try{var c;const i=yield a.reqInterceptor(r),d=yield e(t,i);return(c=n)===null||c===void 0||c(),yield a.resInterceptor(d,a,o)}catch(i){var l;return(l=n)===null||l===void 0||l(),yield a.errInterceptor(i),Promise.reject(i)}}),F.apply(this,arguments)}function L(e,t){function r(a,o,n,c,l){const i=T.source(),d=q(r,arguments),s=k({url:a,loadingText:"加载中..."},t,l),{urlRes:R,headers:O,configRes:h}=_(a,e,c);if(s.isCache){const u=y.getCache(s.cacheKey);if(u)return Promise.resolve(u)}const m=o.toUpperCase()==="GET"?C.JSON:s.qs?C.FORM_URLENCODED:C.JSON,p={cancelToken:i.token,method:o,url:R,data:n,header:{"Content-Type":m,...O},...h};return E(b,"request",p,s,d).then(u=>(s.isCache&&y.setCache(s.cacheKey,u,s.cacheExpire),u))}return r.get=w(r,"get"),r.post=w(r,"post"),r}function z(e,t){return function r(a,o,n,c){const l=T.source(),i=q(r,arguments),d=k({loadingText:"上传中..."},t,c),{urlRes:s,headers:R,configRes:O}=_(a,e,n),{keyName:h="file",filePath:f,...m}={keyName:"file",...o};if(!f||!f.startsWith("http://tmp")&&!f.startsWith("wxfile://tmp"))return Promise.resolve({data:f});const p={cancelToken:l.token,url:s,filePath:f,name:h,formData:m,header:{...R},...O};return E(b,"uploadFile",p,d,i).then(function(){var u=y._asyncToGenerator(function*(g){try{return g.data=typeof g.data=="string"?JSON.parse(g.data):g.data,yield d.resInterceptor(g,d,i)}catch(N){return Promise.reject({type:"code error",res:N})}});return function(g){return u.apply(this,arguments)}}())}}function G(e,t){return function r(a,o,n,c){const l=T.source(),i=q(r,arguments),d=k({loadingText:"下载中..."},t,c),{urlRes:s,headers:R,configRes:O}=_(a,e,n);let h=s;if(o&&typeof o=="object"){const m=Object.entries(o).filter(p=>{let[,u]=p;return u!=null&&u!==""}).map(p=>{let[u,g]=p;return`${encodeURIComponent(u)}=${encodeURIComponent(g)}`}).join("&");m&&(h+=(h.includes("?")?"&":"?")+m)}const f={cancelToken:l.token,url:h,header:{...R},...O};return E(b,"downloadFile",f,d,i)}}exports.CONTENT_TYPES=C;exports.CancelToken=T;exports.createDownloadFile=G;exports.createRequest=L;exports.createUploadFile=z;exports.endLoading=D;exports.promisifyRequest=b;exports.startLoading=I;
@@ -0,0 +1 @@
1
+ "use strict";function l(r,t,a,n,o,e,u){try{var c=r[e](u),i=c.value}catch(m){return void a(m)}c.done?t(i):Promise.resolve(i).then(n,o)}function g(r){return function(){var t=this,a=arguments;return new Promise(function(n,o){var e=r.apply(t,a);function u(i){l(e,n,o,u,c,"next",i)}function c(i){l(e,n,o,u,c,"throw",i)}u(void 0)})}}function p(){for(var r=arguments.length,t=new Array(r),a=0;a<r;a++)t[a]=arguments[a];if(t.some(n=>typeof n!="function"))throw new TypeError("compose 参数必须是函数");return t.length===0?function(){for(var n=arguments.length,o=new Array(n),e=0;e<n;e++)o[e]=arguments[e];return o.length===1?o[0]:o}:t.reduce((n,o)=>function(){for(var e=this,u=arguments.length,c=new Array(u),i=0;i<u;i++)c[i]=arguments[i];return o.call(this,function(){for(var m=arguments.length,f=new Array(m),s=0;s<m;s++)f[s]=arguments[s];return n.apply(e,f.concat(c))},...c)})}function d(){for(var r=arguments.length,t=new Array(r),a=0;a<r;a++)t[a]=arguments[a];if(t.some(n=>typeof n!="function"))throw new TypeError("composeAsync 参数必须是函数");return t.length===0?g(function*(){for(var n=arguments.length,o=new Array(n),e=0;e<n;e++)o[e]=arguments[e];return o.length===1?o[0]:o}):t.reduce((n,o)=>g(function*(){for(var e=this,u=arguments.length,c=new Array(u),i=0;i<u;i++)c[i]=arguments[i];return o.call(this,g(function*(){for(var m=arguments.length,f=new Array(m),s=0;s<m;s++)f[s]=arguments[s];return n.apply(e,f.concat(c))}),...c)}))}function w(){for(var r=arguments.length,t=new Array(r),a=0;a<r;a++)t[a]=arguments[a];if(t.some(n=>typeof n!="function"))throw new TypeError("pipe 参数必须是函数");return t.length===0?function(){for(var n=arguments.length,o=new Array(n),e=0;e<n;e++)o[e]=arguments[e];return o.length===1?o[0]:o}:t.reduce((n,o)=>function(){for(var e=this,u=arguments.length,c=new Array(u),i=0;i<u;i++)c[i]=arguments[i];return n.call(this,function(){for(var m=arguments.length,f=new Array(m),s=0;s<m;s++)f[s]=arguments[s];return o.apply(e,f.concat(c))},...c)})}function S(){for(var r=arguments.length,t=new Array(r),a=0;a<r;a++)t[a]=arguments[a];if(t.some(n=>typeof n!="function"))throw new TypeError("pipeAsync 参数必须是函数");return t.length===0?g(function*(){for(var n=arguments.length,o=new Array(n),e=0;e<n;e++)o[e]=arguments[e];return o.length===1?o[0]:o}):t.reduce((n,o)=>g(function*(){for(var e=this,u=arguments.length,c=new Array(u),i=0;i<u;i++)c[i]=arguments[i];return n.call(this,g(function*(){for(var m=arguments.length,f=new Array(m),s=0;s<m;s++)f[s]=arguments[s];return o.apply(e,f.concat(c))}),...c)}))}function v(r,t){let a=null;n.stop=()=>a&&clearTimeout(a);function n(){for(var o=arguments.length,e=new Array(o),u=0;u<o;u++)e[u]=arguments[u];n.stop(),a=setTimeout(()=>{r.apply(this,e)},t)}return n}function A(r,t){let a=null,n=[];o.stop=()=>{if(a){var e;(e=n.shift())===null||e===void 0||e("cancel"),clearTimeout(a)}};function o(){for(var e=arguments.length,u=new Array(e),c=0;c<e;c++)u[c]=arguments[c];return new Promise((i,m)=>{o.stop(),n.push(m),a=setTimeout(()=>{i(r.apply(this,u))},t)})}return o}function C(r){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:500,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,n;return a?function(){if(!n){n=!0;for(var o=arguments.length,e=new Array(o),u=0;u<o;u++)e[u]=arguments[u];typeof r=="function"&&r.apply(this,e),setTimeout(()=>{n=!1},t)}}:function(){for(var o=arguments.length,e=new Array(o),u=0;u<o;u++)e[u]=arguments[u];n||(n=!0,setTimeout(()=>{n=!1,typeof r=="function"&&r.apply(this,e)},t))}}function P(r){return encodeURIComponent(JSON.stringify(r||{}))}function I(r){return JSON.parse(decodeURIComponent(r||"{}"))}function h(r){const t={};return decodeURIComponent(r).replace(/([^?^&]*?)=([^?^&]*)/g,(a,n,o)=>{const e=t[n];if(!e)return t[n]=o;if(e&&typeof e=="string")return t[n]=[e,o];t[n].push(o)}),t}function T(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"-";return[Date.now().toString(),Math.random().toString(16).slice(2,10),Math.random().toString(16).slice(7),r.toString()].join(t)}function R(r){return r.replace(/([^-])([^-]*)/g,function(t,a,n){return a.toLocaleUpperCase()+n.toLocaleLowerCase()}).replace(/-/g,"")}function x(r,t){r=r.split("."),t=t.split(".");const a=Math.max(r.length,t.length);for(;r.length<a;)r.push("0");for(;t.length<a;)t.push("0");for(let n=0;n<a;n++){const o=parseInt(r[n]),e=parseInt(t[n]);if(o>e)return 1;if(o<e)return-1}return 0}function b(){return"#"+Math.floor(Math.random()*16777215).toString(16).padEnd(6,"0")}function M(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:8,t=arguments.length>1?arguments[1]:void 0;r=r||32,t||(t="ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678");const a=t.length;let n="";for(let o=0;o<r;o++)n+=t.charAt(Math.floor(Math.random()*a));return n}function U(r){return Object.keys(r).map(t=>{const a=r[t];return`${t}=${a&&typeof a=="object"?JSON.stringify(a):a}`}).join("&")}function j(r){const t=r.scene;return t&&(r={fromCode:!0,...r,...h(t)}),r}function D(r,t){let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:36e5;try{return uni.setStorageSync(r,{time:Date.now(),expire:a,data:t}),!0}catch(n){return console.error(`设置缓存[${r}]失败:`,n),!1}}function E(r){try{const t=uni.getStorageSync(r);return!t||typeof t!="object"||Array.isArray(t)||!("time"in t)||!("expire"in t)?(t&&uni.removeStorageSync(r),null):Date.now()-t.time>=t.expire?(uni.removeStorageSync(r),null):t.data}catch(t){return console.error(`获取缓存[${r}]失败:`,t),null}}function O(r){try{const t=uni.getStorageSync(r);return!t||typeof t!="object"||Array.isArray(t)||!("time"in t)||!("expire"in t)?!1:Date.now()-t.time>=t.expire?(uni.removeStorageSync(r),!1):(t.time=Date.now(),uni.setStorageSync(r,t),!0)}catch(t){return console.error(`续期缓存[${r}]失败:`,t),!1}}function L(r){try{return uni.removeStorageSync(r),!0}catch(t){return console.error(`删除缓存[${r}]失败:`,t),!1}}exports._asyncToGenerator=g;exports.compareVersion=x;exports.compose=p;exports.composeAsync=d;exports.debounce=v;exports.debouncePromise=A;exports.decodeURIParams=I;exports.encodeURIParams=P;exports.getCache=E;exports.getOnLoadParams=j;exports.getPascalCase=R;exports.getRandom=T;exports.getRandomStr=M;exports.getSearchParams=h;exports.getSearchStr=U;exports.pipe=w;exports.pipeAsync=S;exports.randomColor=b;exports.removeCache=L;exports.renewCache=O;exports.setCache=D;exports.throttle=C;
package/lib/index.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export * from './array';
2
+ export * from './date';
3
+ export * from './fs';
4
+ export * from './getLocation';
5
+ export * from './http';
6
+ export * from './magic';
7
+ export * from './object';
8
+ export * from './validate';
9
+ export * as wx from './wx';
package/lib/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./index-e3f8a8ef.js"),f=require("./http/index.js"),A=require("./object/index.js");function v(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"children",n=arguments.length>2?arguments[2]:void 0;return e.reduce((t,o,a)=>{const s=t.concat(o,Array.isArray(o[r])&&o[r].length?v(o[r],r,n):[]);return typeof n=="function"&&n(o,a),s},[])}function x(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"children",t=null;return e.some((o,a)=>r(o,a)?(t=o,!0):t=x(o[n],r,n)),t}function F(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"children",n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"$parent",t=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"$index";return e.map((a,s)=>{const i={...a};return i[o]=s,i[n]=t,i[r]=F(a[r],r,n,i,o),i})}function D(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"$parent";const n=[e];for(;e=e[r];)n.unshift(e);return n}function I(e,r){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"children";return e.filter(r).map(t=>({...t,[n]:I(t[n],r,n)}))}function M(e,r,n,t){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:",",a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:e.length;if(arguments.length>6&&arguments[6]!==void 0?arguments[6]:!0){if(!Array.isArray(e))throw new TypeError("arg1:keys must be an Array!");if(!Array.isArray(r))throw new TypeError("arg2:arr must be an Array!");if(n&&typeof n!="function")throw new TypeError("arg3:callback must be a function!");if(t&&typeof t!="function")throw new TypeError("arg4:callbackAll must be a function!");if(o&&typeof o!="string")throw new TypeError("arg5:join must be a string!");if(a&&typeof a!="number")throw new TypeError("arg6:num must be a number!")}const i=a-1,d=e[i],p=[],l={},P=Array.isArray(d),y={};for(let g=r.length-1;g>=0;g--){const c=r[g];let m=c[d];t&&t(c,g),P&&(m=d.map(w=>c[w]).join(o)),l[m]?(l[m].push(c),n&&n(c,y[m])):(l[m]=[c],n&&n(c,y[m]={}))}const S=Object.keys(l);for(let g=S.length-1;g>=0;g--){const c=S[g],m={key:P?c.split(o):c,value:i!==0?M(e,l[c],n,null,o,i,!1):l[c]};n&&Object.assign(m,y[c]),p.push(m)}return p}function E(e,r){for(let n=e.length-1;n>=0;n--)r(e[n],n)}function L(e,r,n){let t=e[r];e[r]=e[n],e[n]=t}function R(e){if(typeof e=="function")return e;if(typeof e!="string")throw new TypeError("formatter must be a string");return e==="date"?e="yyyy-MM-dd":e==="datetime"&&(e="yyyy-MM-dd HH:mm:ss"),n=>{const{yyyy:t,MM:o,dd:a,HH:s,mm:i,ss:d,ms:p}=n;return e.replaceAll("yyyy",t).replaceAll("MM",o).replaceAll("dd",a).replaceAll("HH",s).replaceAll("mm",i).replaceAll("ss",d).replaceAll("ms",p)}}function k(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Date,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"date",n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;(typeof e=="number"||typeof e=="string")&&(e=new Date(e)),r=R(r);const t={year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),millisecond:e.getMilliseconds()};t.yyyy=t.year.toString(),t.MM=t.month.toString(),t.dd=t.date.toString(),t.HH=t.hour.toString(),t.mm=t.minute.toString(),t.ss=t.second.toString(),t.ms=t.millisecond.toString();function o(a,s){t[a]=t[a].padStart(s,"0")}return n&&(o("yyyy",4),o("MM",2),o("dd",2),o("HH",2),o("mm",2),o("ss",2),o("ms",3)),r(t)}function z(e){return e.replace(/([0-9]{0,4})[^0-9]*([0-9]{0,2})[^0-9]*([0-9]{0,2}).*/,(r,n,t,o)=>{if(n=n.length==4?n+"-":n,t.length&&(t=t>12?"12":t==0?"01":t,t=t.padStart(2,"0")+"-"),o.length){const a=Number(n.slice(0,4)),s=Number(t.slice(0,2)),i=s==12?new Date(a+1,0,0).getDate():new Date(a,s,0).getDate();o=o.padStart(2,"0"),o=o>i?i.toString():o==0?"01":o}return n+t+o})}const q=f.createDownloadFile(),h=uni.getFileSystemManager(),C=["ascii","base64","binary","hex","ucs2","ucs-2","utf16le","utf-16le","utf-8","utf8","latin1"];function B(){return`data:image/${arguments.length>0&&arguments[0]!==void 0?arguments[0]:"png"};base64,`}function b(e){let{filePath:r,encoding:n,sync:t,opts:o={}}=e;if(!C.includes(n))throw"编码不符合";if(t===!0)try{return h.readFileSync(r,n,o.position,o.length)}catch(a){return console.error(a),null}return new Promise(function(a,s){h.readFile({filePath:r,encoding:n,...o,success(i){a(i)},fail:s})})}b.sync=function(e){return b({...e,sync:!0})};function T(e){let{filePath:r,data:n,encoding:t,sync:o,opts:a}=e;if(t=t||"binary",!C.includes(t))throw"编码不符合";if(o===!0)try{return h.writeFileSync(r,n,t),{tempFilePath:r,unlink:()=>h.unlinkSync(r)}}catch(s){return console.error(s),null}return new Promise(function(s,i){h.writeFile({filePath:r,encoding:t,data:n,...a,success(d){if(d.errMsg!=="writeFile:ok")return i(new Error(d.errMsg));s({tempFilePath:r,unlink:()=>h.unlinkSync(r)})},fail:i})})}T.sync=function(e){return T({...e,sync:!0})};function O(e){let{arraybuffer:r,fileType:n,method:t,canvasId:o,width:a,height:s,ctx:i,sync:d}=e;if(typeof r!="object"||r.toString().slice(8,-1)!=="ArrayBuffer")return reject(new Error("ArrayBuffer must be a ArrayBuffer"));if(t=t||"canvas",n=n||"png",t==="fs"){const p=wx.env.USER_DATA_PATH+"/"+Date.now()+"."+n;return T({filePath:p,data:r,sync:d})}if(t==="canvas")return new Promise(function(p,l){if(!["canvas","fs"].includes(t))return l(new Error("method must be canvas | fs"));const P=`data:image/${n};base64,${uni.arrayBufferToBase64(r)}`;if(typeof o!="string")return l(new Error("canvasId must be a string [#id]"));const y=uni.createSelectorQuery();i&&y.in(i),y.select(o).fields({node:!0,size:!0}).exec(function(){var S=u._asyncToGenerator(function*(g){if(g=g[0],!g)return l(new Error("No canvas nodes were obtained"));a=a||g.width,s=s||g.height;const c=g.node;if(!c)return l(new Error("No canvas instances were obtained"));const m=c.getContext("2d"),w=c.createImage();yield new Promise(_=>{w.onload=_,w.src=P}).catch(l),m.clearRect(0,0,a,s),m.drawImage(w,0,0,a,s),uni.canvasToTempFilePath({canvas:c,width:a,height:s,fileType:n,success:p,fail:l})});return function(g){return S.apply(this,arguments)}}())})}const H=uni.canIUse("chooseMedia");function N(e){return e={count:1,...e},new Promise((r,n)=>{H?uni.chooseMedia({...e,mediaType:"image",sizeType:["original","compressed"],success(t){if(t.errMsg=="chooseMedia:ok"&&t.tempFiles[0]){const o=t.tempFiles.map(a=>a.tempFilePath);r(o)}else n(t.errMsg)},fail(t){n(t)}}):uni.chooseImage({count,success(t){r(t.tempFilePaths)},fail(t){n(t)}})})}function U(e){return new Promise((r,n)=>{q(e).then(t=>{uni.saveImageToPhotosAlbum({filePath:t.tempFilePath,success:o=>{uni.showToast({icon:"none",title:"保存成功"}),r(o)},fail:o=>{n(o)}})})})}function K(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return new Promise((r,n)=>{uni.getLocation({altitude:!0,type:"gcj02",success:r,fail:function(t){e&&uni.getNetworkType({success:function(o){if(o.networkType!="none"){const a=getCurrentPages(),s=a[a.length-1];if(s.route.indexOf("errorPage")!=-1)return;uni.redirectTo({url:"/packageOther/pages/errorPage/errorPage"+u.getSearchStr({url:s.$page.fullPath,message:"定位失败",type:2})})}}}),n(t)}})})}function W(e){let{latitude:r,longitude:n,name:t="",address:o=""}=e;return new Promise((a,s)=>{uni.openLocation({latitude:Number(r),longitude:Number(n),name:t,address:o,success:a,fail:function(i){uni.showToast({icon:"none",title:i.errMsg}),s(i)}})})}function Z(e){return/^(https?:|mailto:|tel:)/.test(e)}function j(e){return/^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/.test(e)}function Y(e){return/^\d{4}-\d{1,2}-\d{1,2}/.test(e)}function J(e){return/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(e)}function Q(e){return/^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$|^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/.test(e)}function V(e){return/[1-9]\d{5}(?!\d)/.test(e)}const G={userLocation:"scope.userLocation",userFuzzyLocation:"scope.userFuzzyLocation",userLocationBackground:"scope.userLocationBackground",record:"scope.record",camera:"scope.camera",bluetooth:"scope.bluetooth",writePhotosAlbum:"scope.writePhotosAlbum",addPhoneContact:"scope.addPhoneContact",addPhoneCalendar:"scope.addPhoneCalendar",werun:"scope.werun",address:"scope.address",invoiceTitle:"scope.invoiceTitle",invoice:"scope.invoice",userInfo:"scope.userInfo"};function X(){let{withSubscriptions:e,scope:r}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return e=e||!1,r=G[r]||["scope."+r],new Promise(function(n,t){wx.getSetting({withSubscriptions:e,success(o){if(o.authSetting[r]===!1)return wx.openSetting({withSubscriptions:e,success(a){a.authSetting[r]?n(a):t(a)},fail:t});wx.authorize({scope:r,success:n,fail:t})},fail:t})})}function $(e){let{type:r="file",format:n="png"}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((t,o)=>{uni.createSelectorQuery().select(e).node().exec(a=>{a[0].node.takeSnapshot({type:r,format:n,success:t,fail:o})})})}function ee(e){return new Promise((r,n)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType,paySign:e.sign,success:r,fail(t){n(t),t.errMsg!=="requestPayment:fail cancel"&&uni.showToast({title:"支付失败",icon:"none",duration:2e3})}})})}function te(e){return new Promise((r,n)=>{wx.requestSubscribeMessage({...e,success(t){const o=[],a=[];for(let s in t)t[s]==="accept"?o.push(s):t[s]==="reject"&&a.push(s);r({allowTemplateIds:o,rejectTemplateIds:a})},fail:n})})}function ne(e){return new Promise((r,n)=>{WeixinJSBridge&&WeixinJSBridge.invoke("getBrandWCPayRequest",{appId:e.appId,nonceStr:e.nonceStr,package:e.package,signType:e.signType,paySign:e.sign,timeStamp:e.timeStamp},function(t){t.err_msg==="get_brand_wcpay_request:ok"?r(t):t.err_msg==="get_brand_wcpay_request:cancel"?n(t):(n(t),uni.showToast({title:"支付失败",icon:"none",duration:2e3}))})})}const re=Object.freeze(Object.defineProperty({__proto__:null,authorize:X,subscribeMessage:te,takeSnapshot:$,wxPayInMiniPrograms:ee,wxPayInWxBrowser:ne},Symbol.toStringTag,{value:"Module"}));exports.compareVersion=u.compareVersion;exports.compose=u.compose;exports.composeAsync=u.composeAsync;exports.debounce=u.debounce;exports.debouncePromise=u.debouncePromise;exports.decodeURIParams=u.decodeURIParams;exports.encodeURIParams=u.encodeURIParams;exports.getCache=u.getCache;exports.getOnLoadParams=u.getOnLoadParams;exports.getPascalCase=u.getPascalCase;exports.getRandom=u.getRandom;exports.getRandomStr=u.getRandomStr;exports.getSearchParams=u.getSearchParams;exports.getSearchStr=u.getSearchStr;exports.pipe=u.pipe;exports.pipeAsync=u.pipeAsync;exports.randomColor=u.randomColor;exports.removeCache=u.removeCache;exports.renewCache=u.renewCache;exports.setCache=u.setCache;exports.throttle=u.throttle;exports.CONTENT_TYPES=f.CONTENT_TYPES;exports.CancelToken=f.CancelToken;exports.createDownloadFile=f.createDownloadFile;exports.createRequest=f.createRequest;exports.createUploadFile=f.createUploadFile;exports.endLoading=f.endLoading;exports.promisifyRequest=f.promisifyRequest;exports.startLoading=f.startLoading;exports.cloneDeepWithDescriptors=A.cloneDeepWithDescriptors;exports.getRawType=A.getRawType;exports.hasOwnProperty=A.hasOwnProperty;exports.$fs=h;exports.chooseImg=N;exports.dateFormat=z;exports.exchangeArrP=L;exports.filterTree=I;exports.findTreeItem=x;exports.flatWithKey=v;exports.getArraybufferTempPath=O;exports.getDate=k;exports.getImgBase64Prefix=B;exports.getLocation=K;exports.getTreePath=D;exports.groupBy=M;exports.isExternal=Z;exports.openLocation=W;exports.readFile=b;exports.reverseForEach=E;exports.saveImageToPhotosAlbum=U;exports.treeItemSetParent=F;exports.validDate=Y;exports.validIDCard=Q;exports.validPhone=J;exports.validPostalCode=V;exports.validURL=j;exports.writeFile=T;exports.wx=re;
@@ -0,0 +1,136 @@
1
+ // 基础组合类型
2
+ type Compose<T extends any[]> = T extends [infer F]
3
+ ? F
4
+ : T extends [infer F, ...infer R]
5
+ ? F extends (...args: any[]) => any
6
+ ? Compose<R> extends (...args: any[]) => any
7
+ ? (...args: Parameters<Compose<R>>) => ReturnType<F>
8
+ : never
9
+ : never
10
+ : never;
11
+
12
+ type ComposeAsync<T extends any[]> = T extends [infer F]
13
+ ? F
14
+ : T extends [infer F, ...infer R]
15
+ ? F extends (...args: any[]) => any
16
+ ? ComposeAsync<R> extends (...args: any[]) => any
17
+ ? (...args: Parameters<ComposeAsync<R>>) => Promise<Awaited<ReturnType<F>>>
18
+ : never
19
+ : never
20
+ : never;
21
+
22
+ // 反转数组类型用于 pipe
23
+ type Reverse<T extends any[]> = T extends [infer First, ...infer Rest] ? [...Reverse<Rest>, First] : [];
24
+
25
+ type Pipe<T extends any[]> = Compose<Reverse<T>>;
26
+ type PipeAsync<T extends any[]> = ComposeAsync<Reverse<T>>;
27
+
28
+ /** 同步 compose - 支持任意数量函数 */
29
+ export function compose<T extends any[]>(...fns: T): T extends [] ? <U>(arg: U) => U : Compose<T>;
30
+
31
+ /** 异步 compose - 支持任意数量函数 */
32
+ export function composeAsync<T extends any[]>(...fns: T): T extends [] ? <U>(arg: U) => Promise<U> : ComposeAsync<T>;
33
+
34
+ /** 同步 pipe - 支持任意数量函数 */
35
+ export function pipe<T extends any[]>(...fns: T): T extends [] ? <U>(arg: U) => U : Pipe<T>;
36
+
37
+ /** 异步 pipe - 支持任意数量函数 */
38
+ export function pipeAsync<T extends any[]>(...fns: T): T extends [] ? <U>(arg: U) => Promise<U> : PipeAsync<T>;
39
+
40
+ /**
41
+ * 防抖
42
+ * @param { function } fn 要执行的函数
43
+ * @param { number } delay 防抖延迟时间
44
+ */
45
+ export function debounce<A extends any[], R>(
46
+ fn: (...argvs: A) => R,
47
+ delay?: number
48
+ ): ((...argvs: A) => void) & {
49
+ stop(): void;
50
+ };
51
+
52
+ /**
53
+ * 防抖(Promise版),被取消时reject('cancel')
54
+ * @param { function } fn 要执行的函数
55
+ * @param { number } delay 防抖延迟时间
56
+ */
57
+ export function debouncePromise<A extends any[], R>(
58
+ fn: (...argvs: A) => R,
59
+ delay?: number
60
+ ): ((...argvs: A) => Promise<R>) & {
61
+ stop(): void;
62
+ };
63
+
64
+ /**
65
+ * 节流
66
+ * @param { function } func 要执行的函数
67
+ * @param { number } wait 节流时间,默认500
68
+ * @param { boolean } immediate 是否立即执行,默认true
69
+ */
70
+ export function throttle<T extends (...argvs: any[]) => any>(func: T, wait?: number, immediate?: boolean): T;
71
+
72
+ /**
73
+ * 路径参数编码(JSON序列化后encodeURIComponent)
74
+ * @param { any } params 参数对象
75
+ */
76
+ export function encodeURIParams(params: any): string;
77
+
78
+ /**
79
+ * 路径参数解码
80
+ * @param { string } params encodeURIParams编码后的字符串
81
+ */
82
+ export function decodeURIParams<T = any>(params?: string): T;
83
+
84
+ /** 路径参数对象化结果,同名key聚合为数组 */
85
+ export type SearchParams = Record<string, string | string[]>;
86
+
87
+ /**
88
+ * 路径参数对象化
89
+ * @param { string } str 查询字符串
90
+ */
91
+ export function getSearchParams(str: string): SearchParams;
92
+
93
+ /**
94
+ * 生成随机字符串
95
+ * @param { number } len 长度,默认8
96
+ * @param { string } $chars 字符集
97
+ */
98
+ export function getRandomStr(len?: number, $chars?: string): string;
99
+
100
+ /**
101
+ * 对象转为查询字符串(对象值JSON序列化)
102
+ * @param { Record<string,any> } params 参数对象
103
+ */
104
+ export function getSearchStr(params: Record<string, any>): string;
105
+
106
+ /**
107
+ * 获取页面onLoad参数(自动解析小程序扫码scene)
108
+ * @param { Record<string,any> } e onLoad参数
109
+ */
110
+ export function getOnLoadParams<T extends Record<string, any>>(e: T & { scene?: string }): T & { fromCode?: boolean } & Record<string, any>;
111
+
112
+ /**
113
+ * 设置本地缓存(带过期时间)
114
+ * @param { string } key 缓存键名
115
+ * @param { any } data 缓存数据
116
+ * @param { number } expire 过期时间(毫秒),默认1小时
117
+ */
118
+ export function setCache(key: string, data: any, expire?: number): boolean;
119
+
120
+ /**
121
+ * 获取本地缓存(自动校验有效性,过期自动清理)
122
+ * @param { string } key 缓存键名
123
+ */
124
+ export function getCache<T = any>(key: string): T | null;
125
+
126
+ /**
127
+ * 续期缓存,重置过期倒计时(沿用原有expire时长)
128
+ * @param { string } key 缓存键名
129
+ */
130
+ export function renewCache(key: string): boolean;
131
+
132
+ /**
133
+ * 删除指定缓存
134
+ * @param { string } key 缓存键名
135
+ */
136
+ export function removeCache(key: string): boolean;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../index-e3f8a8ef.js");exports.compareVersion=e.compareVersion;exports.compose=e.compose;exports.composeAsync=e.composeAsync;exports.debounce=e.debounce;exports.debouncePromise=e.debouncePromise;exports.decodeURIParams=e.decodeURIParams;exports.encodeURIParams=e.encodeURIParams;exports.getCache=e.getCache;exports.getOnLoadParams=e.getOnLoadParams;exports.getPascalCase=e.getPascalCase;exports.getRandom=e.getRandom;exports.getRandomStr=e.getRandomStr;exports.getSearchParams=e.getSearchParams;exports.getSearchStr=e.getSearchStr;exports.pipe=e.pipe;exports.pipeAsync=e.pipeAsync;exports.randomColor=e.randomColor;exports.removeCache=e.removeCache;exports.renewCache=e.renewCache;exports.setCache=e.setCache;exports.throttle=e.throttle;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 获取值原始类型(Object.prototype.toString结果,如 'Array'、'Object')
3
+ * @param { any } val 目标值
4
+ */
5
+ export function getRawType(val: any): string;
6
+
7
+ /**
8
+ * 安全的hasOwnProperty
9
+ * @param { any } val 目标对象
10
+ * @param { string } key 属性名
11
+ */
12
+ export function hasOwnProperty(val: any, key: string | number | symbol): boolean;
13
+
14
+ /**
15
+ * 深拷贝(保留getter/setter属性描述符,处理循环引用)
16
+ * @param { T } data 目标数据
17
+ */
18
+ export function cloneDeepWithDescriptors<T>(data: T): T;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=Object.prototype.toString,f=Object.prototype.hasOwnProperty,O=Object.getOwnPropertyDescriptors,g=Object.defineProperty;function p(t){return y.call(t).slice(8,-1)}function h(t,o){return t==null?!1:f.call(t,o)}function w(t){const o=new WeakMap;return function u(e){if(o.has(e))return o.get(e);const c=p(e)==="Array";if(!c&&p(e)!=="Object")return e;const s=c?[]:{};if(o.set(e,s),c)e.forEach(r=>s.push(u(r)));else{const r=O(e);Object.keys(r).reduce((i,n)=>(r[n].get||r[n].set?g(i,n,r[n]):i[n]=u(e[n]),i),s)}return s}(t)}exports.cloneDeepWithDescriptors=w;exports.getRawType=p;exports.hasOwnProperty=h;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * 校验是否为外部链接(https?:、mailto:、tel:)
3
+ * @param { string } path 路径
4
+ */
5
+ export function isExternal(path: string): boolean;
6
+
7
+ /**
8
+ * 校验是否为合法URL
9
+ * @param { string } url 地址
10
+ */
11
+ export function validURL(url: string): boolean;
12
+
13
+ /**
14
+ * 校验是否为日期格式(yyyy-M-d起头)
15
+ * @param { string } str 日期字符串
16
+ */
17
+ export function validDate(str: string): boolean;
18
+
19
+ /**
20
+ * 校验是否为大陆手机号
21
+ * @param { string } str 手机号
22
+ */
23
+ export function validPhone(str: string): boolean;
24
+
25
+ /**
26
+ * 校验是否为身份证号(15/18位)
27
+ * @param { string } str 身份证号
28
+ */
29
+ export function validIDCard(str: string): boolean;
30
+
31
+ /**
32
+ * 校验是否为邮政编码(6位非零开头)
33
+ * @param { string } str 邮政编码
34
+ */
35
+ export function validPostalCode(str: string): boolean;
@@ -0,0 +1,54 @@
1
+ /** 授权参数 */
2
+ export interface AuthorizeOptions {
3
+ /** 是否同时获取订阅消息状态 */
4
+ withSubscriptions?: boolean;
5
+ /** 授权scope(支持简写如'userLocation',或完整'scope.userLocation') */
6
+ scope: string;
7
+ }
8
+
9
+ /**
10
+ * 微信授权(已拒绝时自动唤起openSetting,需在用户手势事件中调用)
11
+ * @param { AuthorizeOptions } opts 授权参数
12
+ */
13
+ export function authorize(opts?: AuthorizeOptions): Promise<any>;
14
+
15
+ /**
16
+ * skyline渲染下节点截图
17
+ * @param { string } id 节点选择器(#id)
18
+ * @param { object } opts { type: 'file'|'arraybuffer',默认'file';format: 'png'|'jpg'|'webp',默认'png' }
19
+ */
20
+ export function takeSnapshot(
21
+ id: string,
22
+ opts?: { type?: string; format?: string }
23
+ ): Promise<any>;
24
+
25
+ /** 微信支付参数 */
26
+ export interface WxPayParams {
27
+ timeStamp: string;
28
+ nonceStr: string;
29
+ package: string;
30
+ signType: string;
31
+ /** 支付签名 */
32
+ sign: string;
33
+ }
34
+
35
+ /**
36
+ * 微信小程序支付(uni.requestPayment)
37
+ * @param { WxPayParams } data 后端返回的支付参数
38
+ */
39
+ export function wxPayInMiniPrograms(data: WxPayParams): Promise<any>;
40
+
41
+ /**
42
+ * 微信小程序消息订阅
43
+ * @param { object } opts wx.requestSubscribeMessage参数(tmplIds等)
44
+ */
45
+ export function subscribeMessage(opts: Record<string, any>): Promise<{
46
+ allowTemplateIds: string[];
47
+ rejectTemplateIds: string[];
48
+ }>;
49
+
50
+ /**
51
+ * 微信浏览器支付(WeixinJSBridge)
52
+ * @param { WxPayParams } data 后端返回的支付参数(需含appId)
53
+ */
54
+ export function wxPayInWxBrowser(data: WxPayParams & { appId: string }): Promise<any>;
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "utils-uniapp",
3
+ "version": "1.0.0",
4
+ "description": "aubyn's utils for uniapp",
5
+ "main": "lib/index.js",
6
+ "typings": "lib/index.d.ts",
7
+ "files": [
8
+ "lib"
9
+ ],
10
+ "scripts": {
11
+ "build": "vite build",
12
+ "test": "echo \"Error: no test specified\" && exit 1"
13
+ },
14
+ "keywords": [
15
+ "aubyn",
16
+ "uniapp",
17
+ "utils"
18
+ ],
19
+ "author": "aubyn",
20
+ "license": "MIT",
21
+ "devDependencies": {
22
+ "@babel/core": "^7.23.3",
23
+ "@babel/plugin-proposal-async-generator-functions": "^7.20.7",
24
+ "@babel/plugin-proposal-logical-assignment-operators": "^7.20.7",
25
+ "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
26
+ "@babel/plugin-proposal-optional-chaining": "^7.21.0",
27
+ "@babel/plugin-transform-async-to-generator": "^7.28.6",
28
+ "@babel/plugin-transform-parameters": "^7.25.9",
29
+ "@rollup/plugin-babel": "^6.0.4",
30
+ "rollup-plugin-copy": "^3.5.0",
31
+ "vite": "^4.5.0"
32
+ },
33
+ "dependencies": {}
34
+ }