dff-util 1.0.9 → 1.1.1

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,6 @@
1
+ export * from './main/util';
2
+ export * from './main/jwt-util';
3
+ export * from './main/http';
4
+ export * from './main/regexr';
5
+ export * from './main/const-value';
6
+ export * from './main/const-type';
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./main/util"), exports);
18
+ __exportStar(require("./main/jwt-util"), exports);
19
+ __exportStar(require("./main/http"), exports);
20
+ __exportStar(require("./main/regexr"), exports);
21
+ __exportStar(require("./main/const-value"), exports);
22
+ __exportStar(require("./main/const-type"), exports);
@@ -0,0 +1,24 @@
1
+ export type SessionInfo = {
2
+ id: string;
3
+ email?: string;
4
+ mobile?: string;
5
+ name?: string;
6
+ roles: string[];
7
+ requestId?: string;
8
+ token?: string;
9
+ iat?: number;
10
+ exp?: number;
11
+ key: string;
12
+ };
13
+ export type SessionUser = {
14
+ id: string;
15
+ email?: string;
16
+ mobile?: string;
17
+ name?: string;
18
+ roles: string[];
19
+ };
20
+ export type ResponseType = {
21
+ status?: string | number;
22
+ data?: any;
23
+ error?: any;
24
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,36 @@
1
+ export declare const ConstValue: {
2
+ AND: string;
3
+ OR: string;
4
+ NOT: string;
5
+ AT: string;
6
+ HASH: string;
7
+ DOLLAR: string;
8
+ PERCENT: string;
9
+ CARET: string;
10
+ AMPERSAND: string;
11
+ ASTERISK: string;
12
+ TILDE: string;
13
+ COLON: string;
14
+ SEMICOLON: string;
15
+ DOUBLE_QUOTE: string;
16
+ SINGLE_QUOTE: string;
17
+ COMMA: string;
18
+ PERIOD: string;
19
+ SLASH: string;
20
+ QUESTION_MARK: string;
21
+ PLUS: string;
22
+ UNDERSCORE: string;
23
+ HYPHEN: string;
24
+ EQUALS: string;
25
+ BACKSLASH: string;
26
+ PIPE: string;
27
+ SPACE: string;
28
+ EMPTY: string;
29
+ TRUE: string;
30
+ FALSE: string;
31
+ NULL: string;
32
+ UNDEFINED: string;
33
+ STR_AND: string;
34
+ STR_OR: string;
35
+ STR_NOT: string;
36
+ };
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConstValue = void 0;
4
+ exports.ConstValue = {
5
+ // Logical operators
6
+ AND: '&&',
7
+ OR: '||',
8
+ NOT: '!',
9
+ // Common special characters
10
+ AT: '@',
11
+ HASH: '#',
12
+ DOLLAR: '$',
13
+ PERCENT: '%',
14
+ CARET: '^',
15
+ AMPERSAND: '&',
16
+ ASTERISK: '*',
17
+ TILDE: '~',
18
+ COLON: ':',
19
+ SEMICOLON: ';',
20
+ DOUBLE_QUOTE: '"',
21
+ SINGLE_QUOTE: "'",
22
+ COMMA: ',',
23
+ PERIOD: '.',
24
+ SLASH: '/',
25
+ QUESTION_MARK: '?',
26
+ PLUS: '+',
27
+ UNDERSCORE: '_',
28
+ HYPHEN: '-',
29
+ EQUALS: '=',
30
+ BACKSLASH: '\\',
31
+ PIPE: '|',
32
+ // Space
33
+ SPACE: ' ',
34
+ EMPTY: '',
35
+ // Other
36
+ TRUE: 'true',
37
+ FALSE: 'false',
38
+ NULL: 'null',
39
+ UNDEFINED: 'undefined',
40
+ STR_AND: 'AND',
41
+ STR_OR: 'OR',
42
+ STR_NOT: 'NOT',
43
+ };
@@ -0,0 +1,29 @@
1
+ export declare enum RespType {
2
+ JSON = "json",
3
+ TEXT = "text",
4
+ BLOB = "blob",
5
+ FORM_DATA = "formData",
6
+ ARRAY_BUFFER = "arrayBuffer"
7
+ }
8
+ export declare const HttpHeaders: {
9
+ 'Content-Type': string;
10
+ authorization: null;
11
+ 'x-request-id': null;
12
+ };
13
+ export declare const BaseHeaders: {
14
+ authorization: null;
15
+ 'x-request-id': null;
16
+ };
17
+ export declare class Http {
18
+ static API_BASE_URL: string | undefined;
19
+ static TOKEN_URL: string;
20
+ private static RespData;
21
+ static Get(url: string, params: any, headers: any, type?: RespType): Promise<any>;
22
+ static Post(url: string, data: any, headers: any, type?: RespType): Promise<any>;
23
+ static Put(url: string, data: any, headers: any, type?: RespType): Promise<any>;
24
+ static Delete(url: string, params: any, headers: any, type?: RespType): Promise<any>;
25
+ static Token(sessionInfo: any, appKey: string, apiKey?: string, type?: RespType): Promise<any>;
26
+ static FormUpload(url: string, file: File, isHeadersAddMultiForm?: boolean, data?: Record<string, any>, headers?: any, method?: 'POST' | 'PUT', type?: RespType): Promise<any>;
27
+ static CloudUpload(fullUrl: string, file: File, headers?: any, method?: 'POST' | 'PUT'): Promise<Response>;
28
+ static FileDownload(fullUrl: string, params: any, headers?: any, method?: string): Promise<Buffer<ArrayBufferLike>>;
29
+ }
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Http = exports.BaseHeaders = exports.HttpHeaders = exports.RespType = void 0;
13
+ var RespType;
14
+ (function (RespType) {
15
+ RespType["JSON"] = "json";
16
+ RespType["TEXT"] = "text";
17
+ RespType["BLOB"] = "blob";
18
+ RespType["FORM_DATA"] = "formData";
19
+ RespType["ARRAY_BUFFER"] = "arrayBuffer";
20
+ })(RespType || (exports.RespType = RespType = {}));
21
+ exports.HttpHeaders = {
22
+ 'Content-Type': 'application/json',
23
+ authorization: null,
24
+ 'x-request-id': null,
25
+ };
26
+ exports.BaseHeaders = {
27
+ authorization: null,
28
+ 'x-request-id': null,
29
+ };
30
+ class Http {
31
+ static RespData(response_1) {
32
+ return __awaiter(this, arguments, void 0, function* (response, type = RespType.JSON) {
33
+ if (!response.ok) {
34
+ throw { status: response.status || 0, statusText: response.statusText || response };
35
+ }
36
+ switch (type) {
37
+ case RespType.JSON:
38
+ return yield (response === null || response === void 0 ? void 0 : response.json());
39
+ case RespType.TEXT:
40
+ return yield (response === null || response === void 0 ? void 0 : response.text());
41
+ case RespType.BLOB:
42
+ return yield (response === null || response === void 0 ? void 0 : response.blob());
43
+ case RespType.FORM_DATA:
44
+ return yield (response === null || response === void 0 ? void 0 : response.formData());
45
+ case RespType.ARRAY_BUFFER:
46
+ return yield (response === null || response === void 0 ? void 0 : response.arrayBuffer());
47
+ case RespType.BLOB:
48
+ return yield (response === null || response === void 0 ? void 0 : response.blob());
49
+ default:
50
+ return null;
51
+ }
52
+ });
53
+ }
54
+ static Get(url_1, params_1, headers_1) {
55
+ return __awaiter(this, arguments, void 0, function* (url, params, headers, type = RespType.JSON) {
56
+ url = url.startsWith('http') ? url : Http.API_BASE_URL + url;
57
+ const fullUrl = params ? `${url}?${new URLSearchParams(params).toString()}` : url;
58
+ try {
59
+ const requestOptions = { method: 'GET', headers: headers || exports.HttpHeaders };
60
+ const response = yield fetch(fullUrl, requestOptions);
61
+ return yield Http.RespData(response, type);
62
+ }
63
+ catch (error) {
64
+ console.error('HttpGet error: ', error);
65
+ throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
66
+ }
67
+ });
68
+ }
69
+ static Post(url_1, data_1, headers_1) {
70
+ return __awaiter(this, arguments, void 0, function* (url, data, headers, type = RespType.JSON) {
71
+ url = url.startsWith('http') ? url : Http.API_BASE_URL + url;
72
+ try {
73
+ const requestOptions = { method: 'POST', body: JSON.stringify(data || {}), headers: headers || exports.HttpHeaders };
74
+ const response = yield fetch(url, requestOptions);
75
+ return yield Http.RespData(response, type);
76
+ }
77
+ catch (error) {
78
+ console.error('HttpPost error: ', error);
79
+ throw { url: url, requestId: exports.HttpHeaders['x-request-id'], body: data, error: error };
80
+ }
81
+ });
82
+ }
83
+ static Put(url_1, data_1, headers_1) {
84
+ return __awaiter(this, arguments, void 0, function* (url, data, headers, type = RespType.JSON) {
85
+ url = url.startsWith('http') ? url : Http.API_BASE_URL + url;
86
+ try {
87
+ const requestOptions = { method: 'PUT', body: JSON.stringify(data || {}), headers: headers || exports.HttpHeaders };
88
+ const response = yield fetch(url, requestOptions);
89
+ return yield Http.RespData(response, type);
90
+ }
91
+ catch (error) {
92
+ console.error('HttpPut error: ', error);
93
+ throw { url: url, requestId: exports.HttpHeaders['x-request-id'], body: data, error: error };
94
+ }
95
+ });
96
+ }
97
+ static Delete(url_1, params_1, headers_1) {
98
+ return __awaiter(this, arguments, void 0, function* (url, params, headers, type = RespType.JSON) {
99
+ url = url.startsWith('http') ? url : Http.API_BASE_URL + url;
100
+ const fullUrl = params ? `${url}?${new URLSearchParams(params).toString()}` : url;
101
+ try {
102
+ const requestOptions = { method: 'DELETE', headers: headers || exports.HttpHeaders };
103
+ const response = yield fetch(fullUrl, requestOptions);
104
+ return yield Http.RespData(response, type);
105
+ }
106
+ catch (error) {
107
+ console.error('HttpDelete error: ', error);
108
+ throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
109
+ }
110
+ });
111
+ }
112
+ static Token(sessionInfo_1, appKey_1, apiKey_1) {
113
+ return __awaiter(this, arguments, void 0, function* (sessionInfo, appKey, apiKey, type = RespType.TEXT) {
114
+ const url = `${Http.API_BASE_URL}${Http.TOKEN_URL}`;
115
+ const params = { key: appKey, payload: JSON.stringify(sessionInfo) };
116
+ const fullUrl = `${url}?${new URLSearchParams(params).toString()}`;
117
+ const headers = Object.assign(Object.assign({}, Headers), { 'X-API-KEY': apiKey || '' });
118
+ try {
119
+ const requestOptions = { method: 'GET', headers: headers };
120
+ const response = yield fetch(fullUrl, requestOptions);
121
+ return yield Http.RespData(response, type);
122
+ }
123
+ catch (error) {
124
+ console.error('HttpToken error: ', error);
125
+ throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
126
+ }
127
+ });
128
+ }
129
+ static FormUpload(url_1, file_1) {
130
+ return __awaiter(this, arguments, void 0, function* (url, file, isHeadersAddMultiForm = false, data = {}, headers = exports.BaseHeaders, method = 'PUT', type = RespType.JSON) {
131
+ url = url.startsWith('http') ? url : Http.API_BASE_URL + url;
132
+ const formData = new FormData();
133
+ formData.append('file', file);
134
+ for (const key in data) {
135
+ if (data[key] !== undefined && data[key] !== null) {
136
+ formData.append(key, data[key]);
137
+ }
138
+ }
139
+ if (isHeadersAddMultiForm) {
140
+ headers = Object.assign(Object.assign({}, headers), { 'Content-Type': headers['Content-Type'] || 'multipart/form-data' });
141
+ }
142
+ try {
143
+ const requestOptions = {
144
+ method: method,
145
+ body: formData,
146
+ headers: Object.assign({}, headers),
147
+ };
148
+ console.log(requestOptions);
149
+ const response = yield fetch(url, requestOptions);
150
+ return yield Http.RespData(response, type);
151
+ }
152
+ catch (error) {
153
+ console.error('HttpUpload error: ', error);
154
+ throw { url: url, requestId: exports.HttpHeaders['x-request-id'], error: error };
155
+ }
156
+ });
157
+ }
158
+ static CloudUpload(fullUrl_1, file_1) {
159
+ return __awaiter(this, arguments, void 0, function* (fullUrl, file, headers = null, method = 'PUT') {
160
+ headers = headers || {
161
+ 'Content-Type': file.type,
162
+ };
163
+ try {
164
+ const requestOptions = {
165
+ method: method,
166
+ body: file,
167
+ headers: Object.assign({}, headers),
168
+ };
169
+ const response = yield fetch(fullUrl, requestOptions);
170
+ return response;
171
+ }
172
+ catch (error) {
173
+ console.error('HttpUpload error: ', error);
174
+ throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
175
+ }
176
+ });
177
+ }
178
+ static FileDownload(fullUrl_1, params_1) {
179
+ return __awaiter(this, arguments, void 0, function* (fullUrl, params, headers = exports.HttpHeaders, method = 'GET') {
180
+ fullUrl = params ? `${fullUrl}?${new URLSearchParams(params).toString()}` : fullUrl;
181
+ try {
182
+ const requestOptions = { method: method, headers: headers || exports.HttpHeaders };
183
+ const response = yield fetch(fullUrl, requestOptions);
184
+ const blob = yield response.blob();
185
+ const buffer = Buffer.from(yield blob.arrayBuffer());
186
+ return buffer;
187
+ }
188
+ catch (error) {
189
+ console.error('HttpDownload error: ', error);
190
+ throw { url: fullUrl, requestId: exports.HttpHeaders['x-request-id'], error: error };
191
+ }
192
+ });
193
+ }
194
+ }
195
+ exports.Http = Http;
196
+ Http.API_BASE_URL = process.env.API_BASE_URL;
197
+ Http.TOKEN_URL = `/apisix/plugin/jwt/sign`;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Encode JWT Token with secret key, expiresIn in seconds (86400 = 1 day) default
3
+ * @param data
4
+ * @param secret
5
+ * @param expiresIn
6
+ * @returns
7
+ */
8
+ export declare const JwtEncode: (data: any, secret: string, expiresIn?: number) => Promise<string>;
9
+ /**
10
+ * Verify JWT token with secret
11
+ * @param token
12
+ * @param secret
13
+ * @returns
14
+ */
15
+ export declare const JwtVerify: (token: string, secret: string) => Promise<import("jose").JWTPayload>;
16
+ /**
17
+ * Decode JWT Token without verification
18
+ * @param token
19
+ * @returns
20
+ */
21
+ export declare const JwtDecode: (token: string) => import("jose").JWTPayload;
22
+ /**
23
+ * Check if token is expired or not
24
+ * @param token
25
+ * @returns
26
+ */
27
+ export declare const JwtValid: (token: string) => boolean;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.JwtValid = exports.JwtDecode = exports.JwtVerify = exports.JwtEncode = void 0;
13
+ const jose_1 = require("jose");
14
+ /**
15
+ * Encode JWT Token with secret key, expiresIn in seconds (86400 = 1 day) default
16
+ * @param data
17
+ * @param secret
18
+ * @param expiresIn
19
+ * @returns
20
+ */
21
+ const JwtEncode = (data_1, secret_1, ...args_1) => __awaiter(void 0, [data_1, secret_1, ...args_1], void 0, function* (data, secret, expiresIn = 86400) {
22
+ const secretKey = new TextEncoder().encode(secret);
23
+ const token = yield new jose_1.SignJWT(data)
24
+ .setProtectedHeader({ alg: 'HS256' })
25
+ .setExpirationTime(`${expiresIn}s`)
26
+ .sign(secretKey);
27
+ return token;
28
+ });
29
+ exports.JwtEncode = JwtEncode;
30
+ /**
31
+ * Verify JWT token with secret
32
+ * @param token
33
+ * @param secret
34
+ * @returns
35
+ */
36
+ const JwtVerify = (token, secret) => __awaiter(void 0, void 0, void 0, function* () {
37
+ if (token) {
38
+ try {
39
+ token = token.replace(/jwt |JWT |Bearer |bearer |BEARER /g, '');
40
+ const secretKey = new TextEncoder().encode(secret);
41
+ const { payload } = yield (0, jose_1.jwtVerify)(token, secretKey, {
42
+ algorithms: ['HS256'],
43
+ });
44
+ return payload;
45
+ }
46
+ catch (err) {
47
+ throw { name: 'error', message: 'Token is not valid' };
48
+ }
49
+ }
50
+ else {
51
+ throw { name: 'error', message: 'Auth token is not supplied' };
52
+ }
53
+ });
54
+ exports.JwtVerify = JwtVerify;
55
+ /**
56
+ * Decode JWT Token without verification
57
+ * @param token
58
+ * @returns
59
+ */
60
+ const JwtDecode = (token) => {
61
+ if (token) {
62
+ try {
63
+ token = token.replace(/jwt |JWT |Bearer |bearer |BEARER /g, '');
64
+ return (0, jose_1.decodeJwt)(token);
65
+ }
66
+ catch (err) {
67
+ console.error(err);
68
+ throw { name: 'error', message: 'Token is not valid' };
69
+ }
70
+ }
71
+ else {
72
+ throw { name: 'error', message: 'Auth token is not supplied' };
73
+ }
74
+ };
75
+ exports.JwtDecode = JwtDecode;
76
+ /**
77
+ * Check if token is expired or not
78
+ * @param token
79
+ * @returns
80
+ */
81
+ const JwtValid = (token) => {
82
+ try {
83
+ if (!token) {
84
+ return false;
85
+ }
86
+ const payload = (0, jose_1.decodeJwt)(token);
87
+ const currentTime = Math.floor(Date.now() / 1000);
88
+ if (payload.exp && payload.exp < currentTime) {
89
+ return false;
90
+ }
91
+ return true;
92
+ }
93
+ catch (error) {
94
+ console.error('Invalid JWT:', error);
95
+ return false;
96
+ }
97
+ };
98
+ exports.JwtValid = JwtValid;
@@ -0,0 +1,22 @@
1
+ export declare const RegExp: {
2
+ NON_ALPHA_NUMERIC: RegExp;
3
+ DIGITS_ONLY: RegExp;
4
+ ALPHABETS_ONLY: RegExp;
5
+ ALPHA_NUMERIC: RegExp;
6
+ EMAIL: RegExp;
7
+ URL: RegExp;
8
+ PHONE_US: RegExp;
9
+ STRONG_PASSWORD: RegExp;
10
+ WHITESPACE: RegExp;
11
+ HTML_TAG: RegExp;
12
+ IPV4: RegExp;
13
+ DATE_YYYY_MM_DD: RegExp;
14
+ TIME_HH_MM: RegExp;
15
+ ISO_DATETIME: RegExp;
16
+ HEX_COLOR: RegExp;
17
+ UUID_V4: RegExp;
18
+ NON_ASCII: RegExp;
19
+ LINE_BREAK: RegExp;
20
+ AMOUNT_DECIMAL: RegExp;
21
+ PERCENTAGE: RegExp;
22
+ };
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RegExp = void 0;
4
+ exports.RegExp = {
5
+ // Matches any non-alphanumeric characters
6
+ NON_ALPHA_NUMERIC: /[^\w\s]/g,
7
+ // Matches only numeric digits (0-9)
8
+ DIGITS_ONLY: /^\d+$/,
9
+ // Matches only alphabets (case-insensitive)
10
+ ALPHABETS_ONLY: /^[a-zA-Z]+$/,
11
+ // Matches alphanumeric characters (letters and digits)
12
+ ALPHA_NUMERIC: /^[a-zA-Z0-9]+$/,
13
+ // Matches an email address
14
+ EMAIL: /^[\w.%+-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/,
15
+ // Matches a URL
16
+ URL: /^(https?:\/\/)?([\w.-]+)\.([a-z]{2,6}\.?)(\/[\w.-]*)*\/?$/i,
17
+ // Matches a US phone number (formats like (123) 456-7890, 123-456-7890, etc.)
18
+ PHONE_US: /^(\(\d{3}\)\s?|\d{3}[-.\s]?)?\d{3}[-.\s]?\d{4}$/,
19
+ // Matches a password with at least one lowercase, one uppercase, one digit, and one special character
20
+ STRONG_PASSWORD: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
21
+ // Matches whitespace characters
22
+ WHITESPACE: /\s+/g,
23
+ // Matches any HTML tags
24
+ HTML_TAG: /<\/?[\w\s="/.':;#-\/\?]+>/gi,
25
+ // Matches IPv4 addresses
26
+ IPV4: /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/,
27
+ // Matches dates in YYYY-MM-DD format
28
+ DATE_YYYY_MM_DD: /^\d{4}-\d{2}-\d{2}$/,
29
+ // Matches time in HH:MM 24-hour format
30
+ TIME_HH_MM: /^([01]\d|2[0-3]):([0-5]\d)$/,
31
+ // Matches ISO 8601 datetime format (e.g., 2023-08-15T13:45:30Z, 2023-08-15T13:45:30+05:30)
32
+ ISO_DATETIME: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,
33
+ // Matches a hexadecimal color code
34
+ HEX_COLOR: /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/,
35
+ // Matches a UUID (version 4)
36
+ UUID_V4: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
37
+ // Matches non-ASCII characters
38
+ NON_ASCII: /[^\x00-\x7F]/g,
39
+ // Matches line breaks (newlines)
40
+ LINE_BREAK: /\r?\n/g,
41
+ // Matches amounts in decimal format (e.g., 123.45, 0.99, 1000)
42
+ AMOUNT_DECIMAL: /^\d+(\.\d{1,2})?$/,
43
+ // Matches percentages from 0-100 or in decimal format (e.g., 25%, 99.99%, 100, 0.5)
44
+ PERCENTAGE: /^(100(\.0{1,2})?|0|0?\.\d{1,2}|[1-9]?\d(\.\d{1,2})?)%?$/,
45
+ };
@@ -0,0 +1,7 @@
1
+ export declare const AppRandomString: (length: number, charset: string) => string;
2
+ export declare const AppUniqueCode: () => string;
3
+ export declare const AppCodeByType: (name: string, type?: null) => string;
4
+ export declare const AppCode: (name: string) => string | null;
5
+ export declare const AppDaysBack: (date: Date, backValue: number, isDays?: boolean) => Date;
6
+ export declare const AppAddDays: (date: Date, addDays: number, isDays?: boolean) => Date;
7
+ export declare const AppUUID4: () => string;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AppUUID4 = exports.AppAddDays = exports.AppDaysBack = exports.AppCode = exports.AppCodeByType = exports.AppUniqueCode = exports.AppRandomString = void 0;
4
+ const randomstring_1 = require("randomstring");
5
+ const regexr_1 = require("./regexr");
6
+ const AppRandomString = (length, charset) => {
7
+ return (0, randomstring_1.generate)({ length: length, charset: charset });
8
+ };
9
+ exports.AppRandomString = AppRandomString;
10
+ let uniqueId = 0;
11
+ const AppUniqueCode = () => {
12
+ let time = new Date().getTime();
13
+ if (uniqueId == time) {
14
+ while (new Date().getTime() < 1 + time) { }
15
+ time = new Date().getTime();
16
+ }
17
+ uniqueId = time;
18
+ return time.toString(36).toUpperCase();
19
+ };
20
+ exports.AppUniqueCode = AppUniqueCode;
21
+ const AppCodeByType = (name, type = null) => {
22
+ let str = '';
23
+ if (type) {
24
+ str = type + '_' + name;
25
+ }
26
+ else {
27
+ str = name + '_' + (0, exports.AppUniqueCode)();
28
+ }
29
+ str = str.replace(regexr_1.RegExp.NON_ALPHA_NUMERIC, '_');
30
+ str = str.replace(/\s/g, '_');
31
+ str = str.substr(0, 128);
32
+ return str.toUpperCase();
33
+ };
34
+ exports.AppCodeByType = AppCodeByType;
35
+ const AppCode = (name) => {
36
+ if (name == null)
37
+ return null;
38
+ let str = '';
39
+ str = name.trim();
40
+ str = str.replace(regexr_1.RegExp.NON_ALPHA_NUMERIC, '_');
41
+ str = str.replace(/\s/g, '_');
42
+ return str.toUpperCase();
43
+ };
44
+ exports.AppCode = AppCode;
45
+ const AppDaysBack = (date, backValue, isDays = true) => {
46
+ date = new Date(date);
47
+ if (isDays) {
48
+ date.setDate(date.getDate() - backValue);
49
+ }
50
+ else {
51
+ date.setMilliseconds(date.getMilliseconds() - backValue);
52
+ }
53
+ date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
54
+ return date;
55
+ };
56
+ exports.AppDaysBack = AppDaysBack;
57
+ const AppAddDays = (date, addDays, isDays = true) => {
58
+ date = new Date(date);
59
+ if (isDays) {
60
+ date.setDate(date.getDate() + addDays);
61
+ }
62
+ else {
63
+ date.setMilliseconds(date.getMilliseconds() + addDays);
64
+ }
65
+ date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
66
+ return date;
67
+ };
68
+ exports.AppAddDays = AppAddDays;
69
+ const AppUUID4 = () => {
70
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
71
+ const r = (Math.random() * 16) | 0;
72
+ const v = c == 'x' ? r : (r & 0x3) | 0x8;
73
+ return v.toString(16);
74
+ });
75
+ };
76
+ exports.AppUUID4 = AppUUID4;
package/dist/tests/jwt.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- // bun run tests/jwt.ts
2
+ // bun run src/tests/jwt.ts
3
3
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
4
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
5
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  });
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- const index_1 = require("../src/index");
13
+ const index_1 = require("../index");
14
14
  const runJwtExamples = () => __awaiter(void 0, void 0, void 0, function* () {
15
15
  const secret = 'your-secret-key';
16
16
  const payload = { userId: '123', role: 'admin' };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dff-util",
3
- "version": "1.0.9",
3
+ "version": "1.1.1",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {
package/tsconfig.json CHANGED
@@ -105,6 +105,6 @@
105
105
  // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
106
106
  "skipLibCheck": true /* Skip type checking all .d.ts files. */
107
107
  },
108
- "include": [ "src/**/*", "tests/jwt.ts" ],
108
+ "include": [ "src/**/*", "src/tests/jwt.ts" ],
109
109
  "exclude": [ "node_modules", "**/*.spec.ts" ]
110
110
  }
package/tests/jwt.ts DELETED
@@ -1,30 +0,0 @@
1
- // bun run tests/jwt.ts
2
-
3
- import { JwtEncode, JwtVerify, JwtDecode, JwtValid } from '../src/index';
4
-
5
- const runJwtExamples = async () => {
6
- const secret = 'your-secret-key';
7
- const payload = { userId: '123', role: 'admin' };
8
-
9
- // 1. Encode a JWT
10
- const token = await JwtEncode(payload, secret, 3600);
11
- console.log('Encoded JWT Token:', token);
12
-
13
- // 2. Verify the JWT
14
- try {
15
- const verifiedPayload = await JwtVerify(token, secret);
16
- console.log('Verified Payload:', verifiedPayload);
17
- } catch (error: any) {
18
- console.error('Verification Error:', error.message);
19
- }
20
-
21
- // 3. Decode the JWT without verification
22
- const decodedPayload = JwtDecode(token);
23
- console.log('Decoded Payload (without verification):', decodedPayload);
24
-
25
- // 4. Check if the JWT is valid
26
- const isValid = JwtValid(token);
27
- console.log('Is JWT valid:', isValid);
28
- };
29
-
30
- runJwtExamples();