@zdepot/utils 1.0.2 → 1.1.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.
- package/README.md +47 -47
- package/dist/index.d.ts +14 -0
- package/dist/index.global.js +1 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
# @zdepot/utils
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Safe type conversion tool library, which provides the method of type judgment and conversion with bottom value, to ensure that your code will not throw exceptions because of type problems.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Features
|
|
6
6
|
|
|
7
|
-
✅
|
|
8
|
-
✅
|
|
9
|
-
✅ **JSON
|
|
10
|
-
✅
|
|
11
|
-
✅ **TypeScript
|
|
12
|
-
✅ **Tree-shaking** -
|
|
7
|
+
✅ **Type Safety** - Accurate type detection based on `Object.prototype.toString`
|
|
8
|
+
✅ **Fallback Protection** - All conversion methods have default fallback values to prevent runtime errors
|
|
9
|
+
✅ **JSON Parsing** - Smart JSON parsing with automatic type detection
|
|
10
|
+
✅ **Circular References** - Safe JSON serialization with automatic circular reference and function handling
|
|
11
|
+
✅ **TypeScript Support** - Complete TypeScript type definitions
|
|
12
|
+
✅ **Tree-shaking** - Side-effect free, compatible with bundler optimization
|
|
13
13
|
|
|
14
|
-
##
|
|
14
|
+
## Installation
|
|
15
15
|
|
|
16
16
|
```bash
|
|
17
17
|
npm install @zdepot/utils
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
##
|
|
20
|
+
## Usage
|
|
21
21
|
|
|
22
22
|
```ts
|
|
23
23
|
import safe from '@zdepot/utils'
|
|
24
24
|
|
|
25
|
-
//
|
|
25
|
+
// Or import only what you need
|
|
26
26
|
import { safe } from '@zdepot/utils'
|
|
27
27
|
```
|
|
28
28
|
|
|
@@ -30,7 +30,7 @@ import { safe } from '@zdepot/utils'
|
|
|
30
30
|
|
|
31
31
|
### isSameType(a, b)
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
Checks if two values are of the same type, using `Object.prototype.toString` for precise detection.
|
|
34
34
|
|
|
35
35
|
```ts
|
|
36
36
|
safe.isSameType([], []) // true
|
|
@@ -40,7 +40,7 @@ safe.isSameType(1, '1') // false
|
|
|
40
40
|
|
|
41
41
|
### array(value)
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
Ensures an array is returned. Returns the input directly if it's an array; parses JSON strings automatically; otherwise returns an empty array `[]`.
|
|
44
44
|
|
|
45
45
|
```ts
|
|
46
46
|
safe.array([1, 2]) // [1, 2]
|
|
@@ -51,7 +51,7 @@ safe.array(null) // []
|
|
|
51
51
|
|
|
52
52
|
### string(value, fallback?)
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
Ensures a string is returned. Returns the input directly if it's a string, otherwise returns the fallback value (default `""`).
|
|
55
55
|
|
|
56
56
|
```ts
|
|
57
57
|
safe.string('hello') // 'hello'
|
|
@@ -61,7 +61,7 @@ safe.string(123, 'default') // 'default'
|
|
|
61
61
|
|
|
62
62
|
### number(value, fallback?)
|
|
63
63
|
|
|
64
|
-
|
|
64
|
+
Ensures a number is returned. Uses `Number()` for conversion, returns fallback value (default `0`) if result is NaN or Infinity.
|
|
65
65
|
|
|
66
66
|
```ts
|
|
67
67
|
safe.number(123) // 123
|
|
@@ -73,64 +73,64 @@ safe.number(Infinity) // 0
|
|
|
73
73
|
|
|
74
74
|
### jsonParse(value, fallback)
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
`JSON.parse` with fallback value. Returns fallback if parsing fails or result type doesn't match fallback type.
|
|
77
77
|
|
|
78
78
|
```ts
|
|
79
79
|
safe.jsonParse('{"a":1}', {}) // { a: 1 }
|
|
80
|
-
safe.jsonParse('invalid', {})
|
|
81
|
-
safe.jsonParse('"hello"', []) // [] (
|
|
80
|
+
safe.jsonParse('invalid', {}) // {}
|
|
81
|
+
safe.jsonParse('"hello"', []) // [] (type mismatch)
|
|
82
82
|
safe.jsonParse(null, {}) // {}
|
|
83
83
|
```
|
|
84
84
|
|
|
85
85
|
### jsonParseObj(value, fallback)
|
|
86
86
|
|
|
87
|
-
|
|
87
|
+
Enhanced `jsonParse` that only processes strings starting with `[` or `{` (objects/arrays), otherwise returns fallback directly. Built-in length limit prevents DoS attacks.
|
|
88
88
|
|
|
89
89
|
```ts
|
|
90
90
|
safe.jsonParseObj('{"a":1}', {}) // { a: 1 }
|
|
91
91
|
safe.jsonParseObj('[1,2]', []) // [1, 2]
|
|
92
|
-
safe.jsonParseObj('"hello"', {}) // {} (
|
|
92
|
+
safe.jsonParseObj('"hello"', {}) // {} (doesn't start with [ or {)
|
|
93
93
|
safe.jsonParseObj('invalid', {}) // {}
|
|
94
94
|
```
|
|
95
95
|
|
|
96
96
|
### split(value, splitStr)
|
|
97
97
|
|
|
98
|
-
|
|
98
|
+
Safe `String.split`. Empty strings return `[]` instead of `['']`, errors also return `[]`.
|
|
99
99
|
|
|
100
100
|
```ts
|
|
101
101
|
safe.split('a,b,c', ',') // ['a', 'b', 'c']
|
|
102
|
-
safe.split('', ',')
|
|
103
|
-
safe.split(null, ',')
|
|
102
|
+
safe.split('', ',') // []
|
|
103
|
+
safe.split(null, ',') // []
|
|
104
104
|
```
|
|
105
105
|
|
|
106
106
|
### boolean(value, fallback?)
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
Ensures a boolean is returned. Supports `true/false` strings (case-insensitive) and `0/1` numbers.
|
|
109
109
|
|
|
110
110
|
```ts
|
|
111
111
|
safe.boolean(true) // true
|
|
112
|
-
safe.boolean('TRUE')
|
|
113
|
-
safe.boolean(1)
|
|
114
|
-
safe.boolean('false')
|
|
115
|
-
safe.boolean(0)
|
|
116
|
-
safe.boolean('hello')
|
|
112
|
+
safe.boolean('TRUE') // true
|
|
113
|
+
safe.boolean(1) // true
|
|
114
|
+
safe.boolean('false') // false
|
|
115
|
+
safe.boolean(0) // false
|
|
116
|
+
safe.boolean('hello') // false (fallback value)
|
|
117
117
|
```
|
|
118
118
|
|
|
119
119
|
### date(value, fallback?)
|
|
120
120
|
|
|
121
|
-
|
|
121
|
+
Ensures a Date object is returned. Supports Date objects, timestamps, and date strings.
|
|
122
122
|
|
|
123
123
|
```ts
|
|
124
|
-
safe.date(new Date()) //
|
|
125
|
-
safe.date(1700000000000)
|
|
126
|
-
safe.date('2023-01-01')
|
|
127
|
-
safe.date('invalid')
|
|
128
|
-
safe.date('invalid', fallback)
|
|
124
|
+
safe.date(new Date()) // returns as-is
|
|
125
|
+
safe.date(1700000000000) // new Date(1700000000000)
|
|
126
|
+
safe.date('2023-01-01') // new Date('2023-01-01')
|
|
127
|
+
safe.date('invalid') // new Date() (current time)
|
|
128
|
+
safe.date('invalid', fallback) // fallback
|
|
129
129
|
```
|
|
130
130
|
|
|
131
131
|
### function(value, fallback?)
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
Ensures a function is returned. Returns the input directly if it's a function, otherwise returns the fallback value (default empty function).
|
|
134
134
|
|
|
135
135
|
```ts
|
|
136
136
|
safe.function(fn) // fn
|
|
@@ -140,18 +140,18 @@ safe.function(null, () => 'hi') // () => 'hi'
|
|
|
140
140
|
|
|
141
141
|
### nonEmptyString(value, fallback?)
|
|
142
142
|
|
|
143
|
-
|
|
143
|
+
Ensures a non-empty string is returned. Returns the input if it's a non-empty string, otherwise returns the fallback value.
|
|
144
144
|
|
|
145
145
|
```ts
|
|
146
146
|
safe.nonEmptyString('hello') // 'hello'
|
|
147
|
-
safe.nonEmptyString(' ') // '' (
|
|
147
|
+
safe.nonEmptyString(' ') // '' (whitespace only)
|
|
148
148
|
safe.nonEmptyString('') // ''
|
|
149
149
|
safe.nonEmptyString(123, 'N/A') // 'N/A'
|
|
150
150
|
```
|
|
151
151
|
|
|
152
152
|
### email(value, fallback?)
|
|
153
153
|
|
|
154
|
-
|
|
154
|
+
Ensures a valid email string is returned.
|
|
155
155
|
|
|
156
156
|
```ts
|
|
157
157
|
safe.email('user@example.com') // 'user@example.com'
|
|
@@ -161,7 +161,7 @@ safe.email('bad', 'a@b.com') // 'a@b.com'
|
|
|
161
161
|
|
|
162
162
|
### timestamp(value, fallback?)
|
|
163
163
|
|
|
164
|
-
|
|
164
|
+
Ensures a valid timestamp is returned.
|
|
165
165
|
|
|
166
166
|
```ts
|
|
167
167
|
safe.timestamp(1700000000000) // 1700000000000
|
|
@@ -172,7 +172,7 @@ safe.timestamp('invalid', 0) // 0
|
|
|
172
172
|
|
|
173
173
|
### jsonStringify(value, indent?)
|
|
174
174
|
|
|
175
|
-
|
|
175
|
+
Safe JSON serialization. Automatically handles circular references and functions without throwing.
|
|
176
176
|
|
|
177
177
|
```ts
|
|
178
178
|
safe.jsonStringify({ a: 1 }) // '{"a":1}'
|
|
@@ -183,22 +183,22 @@ obj.self = obj
|
|
|
183
183
|
safe.jsonStringify(obj) // '{"name":"test","self":"[Circular]"}'
|
|
184
184
|
```
|
|
185
185
|
|
|
186
|
-
##
|
|
186
|
+
## Use Cases
|
|
187
187
|
|
|
188
188
|
```ts
|
|
189
|
-
// API
|
|
189
|
+
// API response handling
|
|
190
190
|
const data = safe.jsonParse(response.data, defaultValue)
|
|
191
191
|
const items = safe.array(data.items)
|
|
192
192
|
|
|
193
|
-
//
|
|
193
|
+
// Config file parsing
|
|
194
194
|
const config = safe.jsonParseObj(fs.readFileSync('config.json', 'utf-8'), {})
|
|
195
195
|
|
|
196
|
-
//
|
|
196
|
+
// User input processing
|
|
197
197
|
const username = safe.string(input.username, 'guest')
|
|
198
198
|
const age = safe.number(input.age, 0)
|
|
199
199
|
|
|
200
|
-
//
|
|
201
|
-
const parts = safe.split(input.tags, ',') //
|
|
200
|
+
// String splitting
|
|
201
|
+
const parts = safe.split(input.tags, ',') // avoids split(',a', ',') returning ['', 'a']
|
|
202
202
|
```
|
|
203
203
|
|
|
204
204
|
## License
|
package/dist/index.d.ts
CHANGED
|
@@ -96,6 +96,20 @@ interface SafeUtils {
|
|
|
96
96
|
* @returns 序列化后的字符串
|
|
97
97
|
*/
|
|
98
98
|
jsonStringify: (value: unknown, indent?: number) => string;
|
|
99
|
+
/**
|
|
100
|
+
* 确保返回正数。如果输入是正数则返回,否则返回兜底值(默认 1)。
|
|
101
|
+
* @param value 输入值
|
|
102
|
+
* @param fallback 兜底值
|
|
103
|
+
* @returns 正数或兜底值
|
|
104
|
+
*/
|
|
105
|
+
positive: (value: unknown, fallback?: number) => number;
|
|
106
|
+
/**
|
|
107
|
+
* 确保返回有效的 URL 字符串。如果是有效 URL 则返回,否则返回兜底值(默认 "")。
|
|
108
|
+
* @param value 输入值
|
|
109
|
+
* @param fallback 兜底值
|
|
110
|
+
* @returns 有效的 URL 字符串
|
|
111
|
+
*/
|
|
112
|
+
url: (value: unknown, fallback?: string) => string;
|
|
99
113
|
}
|
|
100
114
|
|
|
101
115
|
declare const safe: SafeUtils;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var safeUtils=(()=>{var u=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var d=(n,t)=>{for(var r in t)u(n,r,{get:t[r],enumerable:!0})},N=(n,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of y(t))!m.call(n,e)&&e!==r&&u(n,e,{get:()=>t[e],enumerable:!(s=T(t,e))||s.enumerable});return n};var S=n=>N(u({},"__esModule",{value:!0}),n);var R={};d(R,{default:()=>P,safe:()=>p});var k=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,a=/^[\[{]/,h=()=>{},c=n=>Object.prototype.toString.call(n),o=(n,t)=>c(n)===c(t),g=(n,t)=>{if(n==null)return t;try{let r=JSON.parse(n);return o(r,t)?r:t}catch{return t}},x=(n,t)=>{if(typeof n!="string"||n.length>10485760||n.length<2)return t;try{if(!a.test(n))throw new Error;let r=JSON.parse(n);return o(r,t)?r:t}catch{return t}},E=n=>o(n,[])?n:o(n,"")?g(n,[]):[],i=(n,t="")=>typeof n=="string"?n:t??"",f=(n,t=0)=>{let r=Number(n);return Number.isFinite(r)?r:Number.isFinite(t)?t:0},O=(n,t)=>typeof n!="string"||n===""?[]:n.split(t),D=(n,t=!1)=>{if(n===!0||n===1)return!0;if(n===!1||n===0)return!1;let r=String(n).toLowerCase();return r==="true"?!0:r==="false"?!1:t},w=(n,t)=>{if(n instanceof Date)return n;if(typeof n=="number"||typeof n=="string"){let r=new Date(n);return isNaN(r.getTime())?t??new Date:r}return t??new Date},_=(n,t=h)=>typeof n=="function"?n:t,b=(n,t="")=>{let r=i(n,t);return r.trim()!==""?r:t},J=(n,t="")=>{let r=i(n,t);return k.test(r)?r:t},j=(n,t=Date.now())=>w(n,new Date(t)).getTime(),F=(n,t)=>{let r=new WeakSet;try{return JSON.stringify(n,(s,e)=>{if(typeof e=="function")return"[Function]";if(typeof e=="object"&&e!==null){if(r.has(e))return"[Circular]";r.add(e)}return e},t)}catch{return"{}"}},L=(n,t=1)=>{let r=f(n,NaN);return r>0?r:t},M=(n,t="")=>{let r=i(n,t);try{let s=new URL(r);return s.protocol==="http:"||s.protocol==="https:"?r:t}catch{return t}},p={isSameType:o,array:E,string:i,number:f,jsonParse:g,jsonParseObj:x,split:O,boolean:D,date:w,function:_,nonEmptyString:b,email:J,timestamp:j,jsonStringify:F,positive:L,url:M},P=p;return S(R);})();
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var u=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var d=(n,t)=>{for(var r in t)u(n,r,{get:t[r],enumerable:!0})},N=(n,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of y(t))!m.call(n,e)&&e!==r&&u(n,e,{get:()=>t[e],enumerable:!(s=T(t,e))||s.enumerable});return n};var S=n=>N(u({},"__esModule",{value:!0}),n);var R={};d(R,{default:()=>P,safe:()=>p});module.exports=S(R);var k=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,a=/^[\[{]/,h=()=>{},c=n=>Object.prototype.toString.call(n),o=(n,t)=>c(n)===c(t),g=(n,t)=>{if(n==null)return t;try{let r=JSON.parse(n);return o(r,t)?r:t}catch{return t}},x=(n,t)=>{if(typeof n!="string"||n.length>10485760||n.length<2)return t;try{if(!a.test(n))throw new Error;let r=JSON.parse(n);return o(r,t)?r:t}catch{return t}},E=n=>o(n,[])?n:o(n,"")?g(n,[]):[],i=(n,t="")=>typeof n=="string"?n:t??"",f=(n,t=0)=>{let r=Number(n);return Number.isFinite(r)?r:Number.isFinite(t)?t:0},O=(n,t)=>typeof n!="string"||n===""?[]:n.split(t),D=(n,t=!1)=>{if(n===!0||n===1)return!0;if(n===!1||n===0)return!1;let r=String(n).toLowerCase();return r==="true"?!0:r==="false"?!1:t},w=(n,t)=>{if(n instanceof Date)return n;if(typeof n=="number"||typeof n=="string"){let r=new Date(n);return isNaN(r.getTime())?t??new Date:r}return t??new Date},_=(n,t=h)=>typeof n=="function"?n:t,b=(n,t="")=>{let r=i(n,t);return r.trim()!==""?r:t},J=(n,t="")=>{let r=i(n,t);return k.test(r)?r:t},j=(n,t=Date.now())=>w(n,new Date(t)).getTime(),F=(n,t)=>{let r=new WeakSet;try{return JSON.stringify(n,(s,e)=>{if(typeof e=="function")return"[Function]";if(typeof e=="object"&&e!==null){if(r.has(e))return"[Circular]";r.add(e)}return e},t)}catch{return"{}"}},L=(n,t=1)=>{let r=f(n,NaN);return r>0?r:t},M=(n,t="")=>{let r=i(n,t);try{let s=new URL(r);return s.protocol==="http:"||s.protocol==="https:"?r:t}catch{return t}},p={isSameType:o,array:E,string:i,number:f,jsonParse:g,jsonParseObj:x,split:O,boolean:D,date:w,function:_,nonEmptyString:b,email:J,timestamp:j,jsonStringify:F,positive:L,url:M},P=p;0&&(module.exports={safe});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,p=/^[\[{]/,T=()=>{},u=n=>Object.prototype.toString.call(n),s=(n,t)=>u(n)===u(t),c=(n,t)=>{if(n==null)return t;try{let r=JSON.parse(n);return s(r,t)?r:t}catch{return t}},y=(n,t)=>{if(typeof n!="string"||n.length>10485760||n.length<2)return t;try{if(!p.test(n))throw new Error;let r=JSON.parse(n);return s(r,t)?r:t}catch{return t}},m=n=>s(n,[])?n:s(n,"")?c(n,[]):[],o=(n,t="")=>typeof n=="string"?n:t??"",g=(n,t=0)=>{let r=Number(n);return Number.isFinite(r)?r:Number.isFinite(t)?t:0},d=(n,t)=>typeof n!="string"||n===""?[]:n.split(t),N=(n,t=!1)=>{if(n===!0||n===1)return!0;if(n===!1||n===0)return!1;let r=String(n).toLowerCase();return r==="true"?!0:r==="false"?!1:t},f=(n,t)=>{if(n instanceof Date)return n;if(typeof n=="number"||typeof n=="string"){let r=new Date(n);return isNaN(r.getTime())?t??new Date:r}return t??new Date},S=(n,t=T)=>typeof n=="function"?n:t,k=(n,t="")=>{let r=o(n,t);return r.trim()!==""?r:t},a=(n,t="")=>{let r=o(n,t);return w.test(r)?r:t},h=(n,t=Date.now())=>f(n,new Date(t)).getTime(),x=(n,t)=>{let r=new WeakSet;try{return JSON.stringify(n,(i,e)=>{if(typeof e=="function")return"[Function]";if(typeof e=="object"&&e!==null){if(r.has(e))return"[Circular]";r.add(e)}return e},t)}catch{return"{}"}},E=(n,t=1)=>{let r=g(n,NaN);return r>0?r:t},O=(n,t="")=>{let r=o(n,t);try{let i=new URL(r);return i.protocol==="http:"||i.protocol==="https:"?r:t}catch{return t}},D={isSameType:s,array:m,string:o,number:g,jsonParse:c,jsonParseObj:y,split:d,boolean:N,date:f,function:S,nonEmptyString:k,email:a,timestamp:h,jsonStringify:x,positive:E,url:O},_=D;export{_ as default,D as safe};
|
package/package.json
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zdepot/utils",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "安全类型转换工具库,提供带兜底值的类型判断与转换方法",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
7
|
+
"browser": "dist/index.iife.js",
|
|
7
8
|
"types": "dist/index.d.ts",
|
|
8
9
|
"exports": {
|
|
9
10
|
".": {
|
|
11
|
+
"browser": "./dist/index.iife.js",
|
|
10
12
|
"types": "./dist/index.d.ts",
|
|
11
13
|
"import": "./dist/index.mjs",
|
|
12
14
|
"require": "./dist/index.js"
|
|
@@ -43,7 +45,7 @@
|
|
|
43
45
|
"license": "MIT",
|
|
44
46
|
"repository": {
|
|
45
47
|
"type": "git",
|
|
46
|
-
"url": "https://
|
|
48
|
+
"url": "https://gitee.com/DLwebweb/zdepot-utils",
|
|
47
49
|
"directory": ""
|
|
48
50
|
},
|
|
49
51
|
"devDependencies": {
|