ziya-utils 1.1.4 → 1.1.6

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/es/index.d.ts CHANGED
@@ -6,3 +6,6 @@ export * from "./regexp";
6
6
  export * from "./form";
7
7
  export * from "./count";
8
8
  export * from "./xhr";
9
+ export * from "./constant";
10
+ export * from "./document";
11
+ export * from "./async";
package/es/index.js CHANGED
@@ -6,3 +6,7 @@ export { RegexPatterns, RegexValidator } from './regexp/index.js';
6
6
  export { createFormData } from './form/index.js';
7
7
  export { precisionFormat } from './count/index.js';
8
8
  export { XHRInterceptor, xhrInterceptor } from './xhr/index.js';
9
+ export { Lib_Name } from './constant/index.js';
10
+ export { addStyleStr, createMaskLoading } from './document/index.js';
11
+ export { createAsyncTask } from './async/index.js';
12
+ export { ScriptDomBuilder } from './document/script-dom-builder.js';
@@ -15,6 +15,18 @@ PERFORMANCE OF THIS SOFTWARE.
15
15
  /* global Reflect, Promise, SuppressedError, Symbol */
16
16
 
17
17
 
18
+ function __rest(s, e) {
19
+ var t = {};
20
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
21
+ t[p] = s[p];
22
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
23
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
24
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
25
+ t[p[i]] = s[p[i]];
26
+ }
27
+ return t;
28
+ }
29
+
18
30
  function __awaiter(thisArg, _arguments, P, generator) {
19
31
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
32
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -30,4 +42,4 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
30
42
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
31
43
  };
32
44
 
33
- export { __awaiter };
45
+ export { __awaiter, __rest };
package/es/xhr/index.d.ts CHANGED
@@ -7,8 +7,12 @@
7
7
  * 拦截规则
8
8
  */
9
9
  interface InterceptRule {
10
+ /** 拦截的 URL,模糊匹配 */
10
11
  url: string;
11
- responseCallback: (data: any) => any | Promise<any>;
12
+ /** 拦截响应的回调函数 */
13
+ responseCallback: (data: any) => any;
14
+ /** 拦截请求的回调函数 */
15
+ requestCallback?: (data: any) => any;
12
16
  }
13
17
  /**
14
18
  * 拦截器配置
@@ -40,7 +44,7 @@ declare class XHRInterceptor {
40
44
  /**
41
45
  * 添加单个拦截规则
42
46
  */
43
- addRule(url: string, responseCallback: InterceptRule["responseCallback"]): void;
47
+ addRule(url: string, responseCallback: InterceptRule["responseCallback"], requestCallback?: InterceptRule["requestCallback"]): void;
44
48
  /**
45
49
  * 移除指定URL的拦截规则
46
50
  */
package/es/xhr/index.js CHANGED
@@ -1,5 +1,3 @@
1
- import { __awaiter } from '../node_modules/tslib/tslib.es6.js';
2
-
3
1
  /**
4
2
  * @fileoverview XMLHttpRequest模块
5
3
  * @created 2025-04-02
@@ -44,41 +42,51 @@ class XHRInterceptor {
44
42
  // 没有匹配的规则,直接执行原始请求
45
43
  return originalSend.call(this, body);
46
44
  }
45
+ // 处理请求数据拦截
46
+ let processedBody = body;
47
+ if (matchingRule.requestCallback && body) {
48
+ try {
49
+ processedBody = matchingRule.requestCallback(body);
50
+ }
51
+ catch (error) {
52
+ console.error('XHR请求拦截器处理失败:', error);
53
+ // 出错时使用原始请求体
54
+ processedBody = body;
55
+ }
56
+ }
47
57
  // 保存原始的 onreadystatechange
48
58
  const originalOnReadyStateChange = xhr.onreadystatechange;
49
59
  xhr.onreadystatechange = function (event) {
50
- return __awaiter(this, void 0, void 0, function* () {
51
- if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
52
- try {
53
- // 解析原始响应
54
- const originalData = JSON.parse(xhr.responseText);
55
- // 使用回调函数处理响应数据
56
- const modifiedData = yield matchingRule.responseCallback(originalData);
57
- // 重写响应属性
58
- Object.defineProperty(xhr, "responseText", {
59
- writable: true,
60
- configurable: true,
61
- value: JSON.stringify(modifiedData),
62
- });
63
- Object.defineProperty(xhr, "response", {
64
- writable: true,
65
- configurable: true,
66
- value: JSON.stringify(modifiedData),
67
- });
68
- self.log(`已拦截并修改响应: ${requestUrl}`);
69
- }
70
- catch (error) {
71
- self.log("拦截器处理失败:", error);
72
- // 出错时保持原始响应
73
- }
60
+ if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
61
+ try {
62
+ // 解析原始响应
63
+ const originalData = JSON.parse(xhr.responseText);
64
+ // 使用回调函数处理响应数据
65
+ const modifiedData = matchingRule.responseCallback(originalData);
66
+ // 重写响应属性
67
+ Object.defineProperty(xhr, "responseText", {
68
+ writable: true,
69
+ configurable: true,
70
+ value: JSON.stringify(modifiedData),
71
+ });
72
+ Object.defineProperty(xhr, "response", {
73
+ writable: true,
74
+ configurable: true,
75
+ value: JSON.stringify(modifiedData),
76
+ });
77
+ self.log(`已拦截并修改响应: ${requestUrl}`);
74
78
  }
75
- // 调用原始的 onreadystatechange
76
- if (originalOnReadyStateChange) {
77
- originalOnReadyStateChange.call(this, event);
79
+ catch (error) {
80
+ self.log("拦截器处理失败:", error);
81
+ // 出错时保持原始响应
78
82
  }
79
- });
83
+ }
84
+ // 调用原始的 onreadystatechange
85
+ if (originalOnReadyStateChange) {
86
+ originalOnReadyStateChange.call(this, event);
87
+ }
80
88
  };
81
- return originalSend.call(this, body);
89
+ return originalSend.call(this, processedBody);
82
90
  };
83
91
  return xhr;
84
92
  };
@@ -110,8 +118,8 @@ class XHRInterceptor {
110
118
  /**
111
119
  * 添加单个拦截规则
112
120
  */
113
- addRule(url, responseCallback) {
114
- this.interceptRules.push({ url, responseCallback });
121
+ addRule(url, responseCallback, requestCallback) {
122
+ this.interceptRules.push({ url, responseCallback, requestCallback });
115
123
  this.log(`已添加拦截规则: ${url}`);
116
124
  }
117
125
  /**
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ var tslib_es6 = require('../node_modules/tslib/tslib.es6.js');
4
+
5
+ /**
6
+ * 创建异步任务,定时检查条件直到满足后执行初始化函数
7
+ * @param checkFun 检查函数,返回 true 值时表示条件满足
8
+ * @param initFun 初始化函数,在条件满足后执行
9
+ * @param options 配置选项
10
+ * @returns Promise,resolve 初始化函数的返回值
11
+ */
12
+ function createAsyncTask(checkFun = () => null, initFun = () => undefined, options = {}) {
13
+ const { duration = 1, timeout, immediate = false } = options;
14
+ return new Promise((resolve, reject) => {
15
+ let timer = null;
16
+ let timeoutTimer = null;
17
+ // 清理定时器
18
+ const cleanup = () => {
19
+ if (timer) {
20
+ clearInterval(timer);
21
+ timer = null;
22
+ }
23
+ if (timeoutTimer) {
24
+ clearTimeout(timeoutTimer);
25
+ timeoutTimer = null;
26
+ }
27
+ };
28
+ // 检查逻辑
29
+ const check = () => tslib_es6.__awaiter(this, void 0, void 0, function* () {
30
+ try {
31
+ const res = yield checkFun();
32
+ if (res) {
33
+ cleanup();
34
+ const res2 = yield initFun(res);
35
+ resolve(res2);
36
+ }
37
+ }
38
+ catch (error) {
39
+ cleanup();
40
+ reject(error);
41
+ }
42
+ });
43
+ // 设置超时
44
+ if (timeout && timeout > 0) {
45
+ timeoutTimer = setTimeout(() => {
46
+ cleanup();
47
+ reject(new Error(`${timeout} 秒后任务将会超时。`));
48
+ }, timeout * 1000);
49
+ }
50
+ // 立即执行一次检查
51
+ if (immediate) {
52
+ check();
53
+ }
54
+ // 设置定时检查
55
+ timer = setInterval(check, duration * 1000);
56
+ });
57
+ }
58
+
59
+ exports.createAsyncTask = createAsyncTask;
@@ -0,0 +1,3 @@
1
+ /** 工具名称 */
2
+ declare const Lib_Name = "ziya-utils";
3
+ export { Lib_Name };
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+
3
+ /** 工具名称 */
4
+ const Lib_Name = "ziya-utils";
5
+
6
+ exports.Lib_Name = Lib_Name;
@@ -1,7 +1,30 @@
1
1
  /**
2
- * @fileoverview Document模块
2
+ * @fileoverview Document 模块
3
3
  * @created 2025-04-02
4
4
  * @author glk
5
5
  */
6
- declare function addStyleStr(styStr?: string): HTMLStyleElement;
7
- export { addStyleStr };
6
+ /**
7
+ * 向head追加一个样式表
8
+ * @param styStr
9
+ * @returns
10
+ */
11
+ declare const addStyleStr: (styStr?: string) => HTMLStyleElement;
12
+ /**
13
+ * 创建一个全局唯一的遮罩 Loading
14
+ * @param msg
15
+ * @param style
16
+ * @returns
17
+ */
18
+ declare const createMaskLoading: (msg?: string, style?: string) => {
19
+ /**
20
+ * 关闭loading
21
+ */
22
+ close: () => void;
23
+ /**
24
+ * 更新信息
25
+ * @param msg
26
+ */
27
+ updateMsg: (msg: string) => void;
28
+ };
29
+ export { addStyleStr, createMaskLoading };
30
+ export * from "./script-dom-builder";
@@ -0,0 +1,87 @@
1
+ 'use strict';
2
+
3
+ var index = require('../constant/index.js');
4
+ require('../node_modules/tslib/tslib.es6.js');
5
+
6
+ /**
7
+ * @fileoverview Document 模块
8
+ * @created 2025-04-02
9
+ * @author glk
10
+ */
11
+ /**
12
+ * 向head追加一个样式表
13
+ * @param styStr
14
+ * @returns
15
+ */
16
+ const addStyleStr = (styStr = "") => {
17
+ let _style = document.createElement("style");
18
+ _style.innerHTML = styStr;
19
+ document.getElementsByTagName("head")[0].appendChild(_style);
20
+ return _style;
21
+ };
22
+ /**
23
+ * 创建一个全局唯一的遮罩 Loading
24
+ * @param msg
25
+ * @param style
26
+ * @returns
27
+ */
28
+ const createMaskLoading = (msg = "加载中...", style = "") => {
29
+ const Container_Id = `${index.Lib_Name}-mask-loading-container`;
30
+ const prevLoading = document.getElementById(Container_Id);
31
+ !!prevLoading && document.body.removeChild(prevLoading);
32
+ const ele = document.createElement("div");
33
+ ele.id = Container_Id;
34
+ ele.innerHTML = `
35
+ <div class="mask"></div>
36
+ <div class="message">${msg}</div>
37
+ `;
38
+ const styleEle = document.createElement("style");
39
+ styleEle.innerHTML = `
40
+ #${Container_Id} {
41
+ position: fixed;
42
+ top: 0;
43
+ left: 0;
44
+ width: 100%;
45
+ height: 100%;
46
+ z-index: 9999;
47
+ transition: opacity 0.3s;
48
+ }
49
+ #${Container_Id} .mask {
50
+ position: absolute;
51
+ top: 0;
52
+ left: 0;
53
+ width: 100%;
54
+ height: 100%;
55
+ background-color: rgba(0, 0, 0, 0.45);
56
+ }
57
+ #${Container_Id} .message {
58
+ position: absolute;
59
+ top: 50%;
60
+ left: 50%;
61
+ transform: translate(-50%, -50%);
62
+ color: #fff;
63
+ }
64
+
65
+ ${style}
66
+ `;
67
+ document.head.appendChild(styleEle);
68
+ document.body.append(ele);
69
+ return {
70
+ /**
71
+ * 关闭loading
72
+ */
73
+ close: () => {
74
+ document.body.removeChild(ele);
75
+ },
76
+ /**
77
+ * 更新信息
78
+ * @param msg
79
+ */
80
+ updateMsg: (msg) => {
81
+ ele.querySelector(".message").innerHTML = msg;
82
+ },
83
+ };
84
+ };
85
+
86
+ exports.addStyleStr = addStyleStr;
87
+ exports.createMaskLoading = createMaskLoading;
@@ -0,0 +1,80 @@
1
+ interface ElementConfig {
2
+ type: 'input' | 'button' | 'select' | 'textarea' | 'checkbox' | 'label' | 'div';
3
+ keyword?: string;
4
+ saveToLocal?: boolean;
5
+ inputType?: string;
6
+ placeholder?: string;
7
+ value?: string;
8
+ text?: string;
9
+ options?: Array<{
10
+ value?: string;
11
+ text?: string;
12
+ selected?: boolean;
13
+ } | string>;
14
+ rows?: number;
15
+ checked?: boolean;
16
+ html?: string;
17
+ props?: Record<string, any>;
18
+ onClick?: (event: Event) => void;
19
+ onChange?: (event: Event) => void;
20
+ onInput?: (event: Event) => void;
21
+ onFocus?: (event: Event) => void;
22
+ onBlur?: (event: Event) => void;
23
+ onMouseEnter?: (event: Event) => void;
24
+ onMouseLeave?: (event: Event) => void;
25
+ }
26
+ interface ContainerConfig {
27
+ [key: string]: any;
28
+ }
29
+ interface DOMBuilderReturn {
30
+ container: HTMLDivElement;
31
+ get: (keyword: string) => HTMLElement | null;
32
+ getValue: (keyword: string) => string | boolean | null;
33
+ setValue: (keyword: string, value: string | boolean) => void;
34
+ show: (keyword?: string) => void;
35
+ hide: (keyword?: string) => void;
36
+ remove: () => void;
37
+ on: (keyword: string, event: string, handler: (event: Event) => void) => void;
38
+ getData: (key: string) => any;
39
+ setData: (key: string, value: any) => void;
40
+ }
41
+ /**
42
+ * 开发浏览器脚本DOM构建器
43
+ */
44
+ declare class ScriptDomBuilder {
45
+ private parentNode;
46
+ private container;
47
+ private elements;
48
+ private data;
49
+ private containerId;
50
+ private styleElement;
51
+ constructor(parentNode?: HTMLElement, containerId?: string);
52
+ createMain(items: ElementConfig[], styles?: string, containerConfig?: ContainerConfig): DOMBuilderReturn;
53
+ private createStyles;
54
+ private createItem;
55
+ private isFormElement;
56
+ private handleLocalStorage;
57
+ private createInput;
58
+ private createButton;
59
+ private createSelect;
60
+ private createTextarea;
61
+ private createCheckbox;
62
+ private createLabel;
63
+ private createDiv;
64
+ private createElement;
65
+ private bindEvents;
66
+ private getChild;
67
+ private setChild;
68
+ private getValue;
69
+ private setValue;
70
+ private show;
71
+ private hide;
72
+ private remove;
73
+ private on;
74
+ private getStorageKey;
75
+ private saveToLocalStorage;
76
+ private getFromLocalStorage;
77
+ private setData;
78
+ private getData;
79
+ }
80
+ export { ScriptDomBuilder };