@pisell/core 1.0.41 → 1.0.43

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.
Files changed (37) hide show
  1. package/es/app/app.d.ts +99 -0
  2. package/es/applicationManager/application.d.ts +197 -0
  3. package/es/applicationManager/index.d.ts +19 -0
  4. package/es/history/index.d.ts +23 -0
  5. package/es/index.d.ts +7 -0
  6. package/es/indexDB/index.js +48 -68
  7. package/es/logger/index.d.ts +1 -1
  8. package/es/logger/index.js +199 -165
  9. package/es/menuManager/index.d.ts +28 -0
  10. package/es/request/cache.d.ts +46 -0
  11. package/es/request/index.d.ts +24 -0
  12. package/es/request/type.d.ts +52 -0
  13. package/es/request/utils.d.ts +46 -0
  14. package/es/tasks/index.d.ts +127 -0
  15. package/es/tasks/scheduledTasksExample.d.ts +61 -0
  16. package/es/tasks/type.d.ts +100 -0
  17. package/es/utils/adaptiveThrottle/index.d.ts +36 -0
  18. package/es/utils/adaptiveThrottle/index.js +136 -0
  19. package/lib/app/app.d.ts +99 -0
  20. package/lib/applicationManager/application.d.ts +197 -0
  21. package/lib/applicationManager/index.d.ts +19 -0
  22. package/lib/history/index.d.ts +23 -0
  23. package/lib/index.d.ts +7 -0
  24. package/lib/indexDB/index.js +2 -48
  25. package/lib/logger/index.d.ts +1 -1
  26. package/lib/logger/index.js +21 -6
  27. package/lib/menuManager/index.d.ts +28 -0
  28. package/lib/request/cache.d.ts +46 -0
  29. package/lib/request/index.d.ts +24 -0
  30. package/lib/request/type.d.ts +52 -0
  31. package/lib/request/utils.d.ts +46 -0
  32. package/lib/tasks/index.d.ts +127 -0
  33. package/lib/tasks/scheduledTasksExample.d.ts +61 -0
  34. package/lib/tasks/type.d.ts +100 -0
  35. package/lib/utils/adaptiveThrottle/index.d.ts +36 -0
  36. package/lib/utils/adaptiveThrottle/index.js +121 -0
  37. package/package.json +1 -1
@@ -0,0 +1,28 @@
1
+ import React from 'react';
2
+ import App from '../app';
3
+ export interface MenuItem {
4
+ key: string;
5
+ label: string;
6
+ path: string;
7
+ children?: MenuItem[];
8
+ icon?: string | React.ReactNode;
9
+ hide?: boolean;
10
+ }
11
+ export declare class MenuManager {
12
+ private menuItems;
13
+ private menuMaps;
14
+ private app;
15
+ useMenu: () => import("./hooks").MenuContextType;
16
+ MenuProvider: React.FC<{
17
+ children: React.ReactNode;
18
+ menus: MenuItem[];
19
+ }>;
20
+ constructor(items: MenuItem[], app: App);
21
+ set(items: MenuItem[]): void;
22
+ getMenus(): MenuItem[];
23
+ getMenuMaps(): void;
24
+ findMenuItemByPath(items: MenuItem[], path: string): MenuItem | null;
25
+ findParent(items: MenuItem[], key: string, parent?: MenuItem | null): MenuItem | null;
26
+ getShowChildren(items: MenuItem[]): MenuItem[];
27
+ findMenuItemByKey(items: MenuItem[], key: string): MenuItem | null;
28
+ }
@@ -0,0 +1,46 @@
1
+ import { CacheProps } from './type';
2
+ export declare type CacheType = 'memory' | 'storage' | 'indexDB';
3
+ /**
4
+ * @title: 设置缓存
5
+ * @description:
6
+ * @return {*}
7
+ * @Author: zhiwei.Wang
8
+ */
9
+ export declare const setCache: (key: string, data: any, cache: CacheProps) => Promise<void>;
10
+ /**
11
+ * @title: 删除缓存数据
12
+ * @description:
13
+ * @return {*}
14
+ * @Author: zhiwei.Wang
15
+ */
16
+ export declare const removeCache: (key: string, cache: CacheProps) => void;
17
+ /**
18
+ * @title: 获取数据
19
+ * @description:
20
+ * @param {any} url
21
+ * @param {any} data
22
+ * @return {*}
23
+ * @Author: zhiwei.Wang
24
+ */
25
+ export declare const getCacheData: (url: string, data: any, cache: CacheProps) => Promise<any>;
26
+ /**
27
+ * @title: 设置缓存
28
+ * @description:
29
+ * @param {any} url 路径
30
+ * @param {any} data 参数
31
+ * @param {any} res 数据
32
+ * @return {*}
33
+ * @Author: zhiwei.Wang
34
+ */
35
+ export declare const setCacheData: (url: string, data: any, res: any, cache?: CacheProps) => any | null;
36
+ /**
37
+ * @title: 缓存函数包装器
38
+ * @description:
39
+ * @param {any} url
40
+ * @param {any} data
41
+ * @param {any} config
42
+ * @param {any} fn
43
+ * @return {*}
44
+ * @Author: zhiwei.Wang
45
+ */
46
+ export declare const cacheFn: (props: any, fn: any) => Promise<any>;
@@ -0,0 +1,24 @@
1
+ import { RequestWrapperProps, RequestConfig } from "./type";
2
+ export declare const createRequest: (props: RequestWrapperProps) => Promise<unknown>;
3
+ /**
4
+ * 请求
5
+ * @param props
6
+ * @returns
7
+ */
8
+ export declare const request: (props: RequestWrapperProps) => any;
9
+ export declare const get: (url: RequestWrapperProps["url"], data: RequestWrapperProps["data"], config: RequestWrapperProps["config"]) => Promise<any>;
10
+ export declare const post: (url: RequestWrapperProps["url"], data: RequestWrapperProps["data"], config: RequestWrapperProps["config"]) => Promise<any>;
11
+ export declare const put: (url: RequestWrapperProps["url"], data: RequestWrapperProps["data"], config: RequestWrapperProps["config"]) => Promise<any>;
12
+ export declare const remove: (url: RequestWrapperProps["url"], data: RequestWrapperProps["data"], config: RequestWrapperProps["config"]) => Promise<any>;
13
+ export declare const custom: (url: RequestWrapperProps["url"], config: RequestWrapperProps["config"]) => any;
14
+ export * from "./type";
15
+ declare const _default: {
16
+ get: (url: string, data: any, config: import("./type").RequestSetting | undefined) => Promise<any>;
17
+ post: (url: string, data: any, config: import("./type").RequestSetting | undefined) => Promise<any>;
18
+ put: (url: string, data: any, config: import("./type").RequestSetting | undefined) => Promise<any>;
19
+ remove: (url: string, data: any, config: import("./type").RequestSetting | undefined) => Promise<any>;
20
+ custom: (url: string, config: import("./type").RequestSetting | undefined) => any;
21
+ setConfig: (newConfig: Partial<RequestConfig>) => void;
22
+ getConfig: () => RequestConfig;
23
+ };
24
+ export default _default;
@@ -0,0 +1,52 @@
1
+ import { CreateAxiosDefaults } from "axios";
2
+ import { CacheType } from './cache';
3
+ export interface RequestConfig {
4
+ interceptorsRequest?: ((value: any) => any | Promise<any>) | null;
5
+ interceptorsRequestError?: ((error: any) => any) | null;
6
+ interceptorsResponse?: any;
7
+ interceptorsResponseError?: ((error: any) => any) | null;
8
+ axiosConfig?: CreateAxiosDefaults;
9
+ storage?: any;
10
+ getToken?: () => string | null;
11
+ setToken?: (token: string) => void;
12
+ getLocale?: () => string | null;
13
+ getUrl?: (config: any) => string;
14
+ requestCallbacks?: {
15
+ 200?: (data: any) => void;
16
+ 401?: (data: any) => void;
17
+ 403?: (data: any) => void;
18
+ other?: (data: any) => void;
19
+ [key: string]: any;
20
+ };
21
+ }
22
+ export declare enum RequestModeENUM {
23
+ LOCAL = "local",
24
+ REMOTE = "remote",
25
+ LOCAL_REMOTE = "local_remote",
26
+ REMOTE_LOCAL = "remote_local",
27
+ OS_SERVER = "os_server"
28
+ }
29
+ export declare type RequestModeType = RequestModeENUM.LOCAL | RequestModeENUM.REMOTE | RequestModeENUM.LOCAL_REMOTE | RequestModeENUM.REMOTE_LOCAL | RequestModeENUM.OS_SERVER;
30
+ export interface CacheProps {
31
+ key?: string;
32
+ type?: CacheType;
33
+ updateCache?: boolean;
34
+ cacheUpdateChange?: (data: any) => void;
35
+ mode?: RequestModeType;
36
+ cacheKeyData?: any;
37
+ }
38
+ export interface RequestSetting {
39
+ abort?: boolean;
40
+ headers?: any;
41
+ cache?: CacheProps;
42
+ signal?: any;
43
+ token?: string;
44
+ osServer?: boolean;
45
+ [key: string]: any;
46
+ }
47
+ export interface RequestWrapperProps {
48
+ url: string;
49
+ method: 'get' | 'post' | 'remove' | 'put';
50
+ data?: any;
51
+ config?: RequestSetting;
52
+ }
@@ -0,0 +1,46 @@
1
+ import { InternalAxiosRequestConfig } from "axios";
2
+ import { RequestSetting, RequestConfig, RequestWrapperProps } from "./type";
3
+ export declare const getRequestHeaders: (config: InternalAxiosRequestConfig<RequestSetting> & Record<string, any>) => Record<string, string | null>;
4
+ /**
5
+ * @title: 请求前拦截
6
+ * @description:
7
+ * @param {any} config
8
+ * @return {*}
9
+ * @Author: zhiwei.Wang
10
+ * @Date: 2024-07-04 10:51
11
+ */
12
+ export declare const interceptorsRequest: (config: InternalAxiosRequestConfig<RequestSetting> & Record<string, any>) => Promise<InternalAxiosRequestConfig<RequestSetting> & Record<string, any>>;
13
+ /**
14
+ * @title: 请求前error
15
+ * @description:
16
+ * @param {any} err
17
+ * @return {*}
18
+ * @Author: zhiwei.Wang
19
+ * @Date: 2024-07-04 10:51
20
+ */
21
+ export declare const interceptorsRequestError: (err: RequestConfig["interceptorsRequestError"]) => any;
22
+ /**
23
+ * @title: 请求后拦截
24
+ * @description:
25
+ * @param {any} response
26
+ * @return {*}
27
+ * @Author: zhiwei.Wang
28
+ * @Date: 2024-07-04 10:51
29
+ */
30
+ export declare const interceptorsResponse: (response: RequestConfig["interceptorsResponse"]) => any;
31
+ /**
32
+ * @title: 请求后错误拦截
33
+ * @description:
34
+ * @param {any} response
35
+ * @return {*}
36
+ * @Author: zhiwei.Wang
37
+ * @Date: 2024-07-04 10:51
38
+ */
39
+ export declare const interceptorsResponseError: (response: RequestConfig["interceptorsResponseError"]) => any;
40
+ export declare const requestCallback: (resData: {
41
+ res?: any;
42
+ props: RequestWrapperProps;
43
+ resolve: (value: unknown) => void;
44
+ reject: () => void;
45
+ err?: any;
46
+ }) => void;
@@ -0,0 +1,127 @@
1
+ import { Task, TasksModule, RunTaskParams, AddTaskParams, DeleteTaskParams } from "./type";
2
+ import App from "../app";
3
+ export declare class TasksManager {
4
+ private static instance;
5
+ private taskFunctions;
6
+ private tasks;
7
+ private app;
8
+ private db;
9
+ useTasks: () => {
10
+ tasks: TasksModule;
11
+ };
12
+ watchTaskCallback: (taskModule: TasksModule) => void;
13
+ private timerIds;
14
+ constructor(app: App);
15
+ static getInstance(app?: App): TasksManager;
16
+ addTaskFunction<T>(name: string, fun: T): void;
17
+ addTaskFunctions<T>(tasks: {
18
+ name: string;
19
+ fun: T;
20
+ }[]): void;
21
+ getTasks(): TasksModule;
22
+ getTaskFunction(name: string): any;
23
+ init(): Promise<void>;
24
+ private saveTaskQueueToLocal;
25
+ private loadTaskQueueFromLocal;
26
+ /**
27
+ * @title: 执行任务
28
+ * @description:
29
+ * @param {Task} task
30
+ * @return {*}
31
+ * @Author: zhiwei.Wang
32
+ * @Date: 2024-09-26 13:53
33
+ */
34
+ private runTask;
35
+ /**
36
+ * @title: 清除任务定时器
37
+ */
38
+ private clearTaskTimer;
39
+ /**
40
+ * @title: 计算下一次执行时间
41
+ * @description: 根据定时任务配置计算下一次执行时间
42
+ * @param {Task} task
43
+ * @return {string | null} 下一次执行时间
44
+ */
45
+ private calculateNextExecuteTime;
46
+ /**
47
+ * @title: 启动定时任务
48
+ * @description: 在特定时间点执行任务(仅在 scheduledTasks 模块中生效)
49
+ * @param {Task} task
50
+ * @return {*}
51
+ */
52
+ private startScheduledTask;
53
+ /**
54
+ * @title: 启动轮询
55
+ * @description: 根据轮询间隔定期执行任务
56
+ * @param {Task} task
57
+ * @return {*}
58
+ */
59
+ private startPolling;
60
+ /**
61
+ * @title: 创建任务数据
62
+ * @description:
63
+ * @param {Partial} payload
64
+ * @return {*}
65
+ * @Author: zhiwei.Wang
66
+ * @Date: 2024-09-26 13:54
67
+ */
68
+ private createTaskData;
69
+ private getTaskQueue;
70
+ private timeout;
71
+ /**
72
+ * @title: 执行任务队列
73
+ * @description:
74
+ * @return {*}
75
+ * @Author: zhiwei.Wang
76
+ * @Date: 2024-09-26 13:52
77
+ */
78
+ run(payload: RunTaskParams): Promise<void>;
79
+ deleteTask(payload: DeleteTaskParams): void;
80
+ /**
81
+ * @title: 重试任务
82
+ * @description:
83
+ * @return {*}
84
+ * @Author: zhiwei.Wang
85
+ * @Date: 2024-09-26 13:53
86
+ */
87
+ retryTask(payload: RunTaskParams): void;
88
+ addTask(payload: AddTaskParams): void;
89
+ private updateTask;
90
+ private updateQueueStatus;
91
+ /**
92
+ * @title: 更新队列运行状态
93
+ * @description: 标记队列是否正在执行
94
+ */
95
+ private updateQueueRunningState;
96
+ private setTasksData;
97
+ private setTasks;
98
+ clearAllTaskTimer(tasks: Task[]): void;
99
+ clearTasks(payload: RunTaskParams): void;
100
+ clearAllTasks(): void;
101
+ watchTask(callback: (taskModule: TasksModule) => void): void;
102
+ /**
103
+ * @title: 获取队列执行状态
104
+ * @description: 获取指定队列的执行状态和进度信息
105
+ * @param {string} module - 模块名
106
+ * @param {string} queueId - 队列ID
107
+ * @return {object} 队列状态信息
108
+ */
109
+ getQueueStatus(module: string, queueId: string): {
110
+ isRunning: boolean;
111
+ status: "uncompleted" | "completed";
112
+ progress: {
113
+ total: number;
114
+ completed: number;
115
+ failed: number;
116
+ inProgress: number;
117
+ };
118
+ lastRunAt: string | null;
119
+ tasksCount: number;
120
+ } | null;
121
+ /**
122
+ * @title: 获取所有队列状态
123
+ * @description: 获取所有任务队列的执行状态概览
124
+ * @return {object} 所有队列的状态信息
125
+ */
126
+ getAllQueuesStatus(): any;
127
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 定时任务示例代码
3
+ * 本文件展示了如何使用定时任务功能
4
+ *
5
+ * 重要提示:
6
+ * - 定时任务必须添加到 'scheduledTasks' 模块才能生效
7
+ * - 在其他模块中,scheduled 配置会被忽略,任务将作为普通任务立即执行
8
+ * - 这是为了性能优化,避免在所有模块中检查定时任务配置
9
+ */
10
+ import { TasksManager } from './index';
11
+ /**
12
+ * 示例1:创建一次性定时任务
13
+ * 在特定时间点执行一次
14
+ *
15
+ * 注意:定时任务必须添加到 'scheduledTasks' 模块才能生效
16
+ */
17
+ export declare function createOnceScheduledTask(tasksManager: TasksManager): void;
18
+ /**
19
+ * 示例2:创建每日重复的定时任务
20
+ * 每天在固定时间执行
21
+ */
22
+ export declare function createDailyScheduledTask(tasksManager: TasksManager): void;
23
+ /**
24
+ * 示例3:创建带结束时间的重复任务
25
+ * 在特定时间段内重复执行
26
+ */
27
+ export declare function createLimitedRepeatTask(tasksManager: TasksManager): void;
28
+ /**
29
+ * 示例4:创建多个时间点的任务
30
+ * 在一天中的多个时间点分别执行
31
+ */
32
+ export declare function createMultiTimeTask(tasksManager: TasksManager): void;
33
+ /**
34
+ * 示例5:创建每周重复任务
35
+ * 每周一早上9点执行周报
36
+ */
37
+ export declare function createWeeklyTask(tasksManager: TasksManager): void;
38
+ /**
39
+ * 示例6:创建每月重复任务
40
+ * 每月1号生成月报
41
+ */
42
+ export declare function createMonthlyTask(tasksManager: TasksManager): void;
43
+ /**
44
+ * 示例7:查询和管理定时任务
45
+ */
46
+ export declare function manageScheduledTasks(tasksManager: TasksManager): void;
47
+ /**
48
+ * 完整使用示例
49
+ */
50
+ export declare function fullExample(app: any): void;
51
+ declare const _default: {
52
+ createOnceScheduledTask: typeof createOnceScheduledTask;
53
+ createDailyScheduledTask: typeof createDailyScheduledTask;
54
+ createLimitedRepeatTask: typeof createLimitedRepeatTask;
55
+ createMultiTimeTask: typeof createMultiTimeTask;
56
+ createWeeklyTask: typeof createWeeklyTask;
57
+ createMonthlyTask: typeof createMonthlyTask;
58
+ manageScheduledTasks: typeof manageScheduledTasks;
59
+ fullExample: typeof fullExample;
60
+ };
61
+ export default _default;
@@ -0,0 +1,100 @@
1
+ export declare type TaskRunStatus = "pending" | "in-progress" | "success" | "failure";
2
+ export interface Task {
3
+ id?: string;
4
+ type?: "local" | "cloud";
5
+ retries?: number;
6
+ maxRetries?: number;
7
+ status?: TaskRunStatus;
8
+ action: string;
9
+ payload: any;
10
+ beforeAction?: string;
11
+ beforePayload?: any;
12
+ afterAction?: string;
13
+ afterPayload?: any;
14
+ polling?: {
15
+ interval?: number;
16
+ };
17
+ pollingResult?: {
18
+ count: number;
19
+ timerId?: any;
20
+ };
21
+ scheduled?: {
22
+ executeAt: string | string[];
23
+ repeat?: boolean;
24
+ repeatType?: 'daily' | 'weekly' | 'monthly' | 'yearly';
25
+ repeatInterval?: number;
26
+ endAt?: string;
27
+ };
28
+ scheduledResult?: {
29
+ count: number;
30
+ timerId?: any;
31
+ nextExecuteTime?: string;
32
+ };
33
+ manual?: boolean;
34
+ destroy?: boolean;
35
+ [key: string]: any;
36
+ }
37
+ export interface TaskConfig {
38
+ tasks: Task[];
39
+ }
40
+ declare type TaskModuleName = string;
41
+ declare type TaskQueueName = string;
42
+ declare type TaskStatus = "uncompleted" | "completed";
43
+ export interface TaskQueue {
44
+ status: TaskStatus;
45
+ tasks: Task[];
46
+ isRunning?: boolean;
47
+ progress?: {
48
+ total: number;
49
+ completed: number;
50
+ failed: number;
51
+ inProgress: number;
52
+ };
53
+ lastRunAt?: string;
54
+ }
55
+ export interface RunTaskParams {
56
+ module: TaskModuleName;
57
+ queueId: TaskQueueName;
58
+ callback?: () => void;
59
+ }
60
+ export interface DeleteTaskParams {
61
+ module: TaskModuleName;
62
+ queueId: TaskQueueName;
63
+ taskId: string;
64
+ }
65
+ export interface AddTaskParams {
66
+ module: TaskModuleName;
67
+ queueId: TaskQueueName;
68
+ tasks: Task[];
69
+ }
70
+ export interface AddTaskDataParams {
71
+ module: TaskModuleName;
72
+ queueId: TaskQueueName;
73
+ [key: string]: any;
74
+ }
75
+ export interface TaskRunResult {
76
+ status: TaskRunStatus;
77
+ [key: string]: any;
78
+ }
79
+ /**
80
+ * 任务模块
81
+ * 注意:'scheduledTasks' 是保留的模块名,专门用于定时任务
82
+ * 在其他模块中,scheduled 配置会被忽略,任务将作为普通任务执行
83
+ */
84
+ export interface TasksModule {
85
+ [key: TaskModuleName]: {
86
+ [key: TaskQueueName]: {
87
+ status: TaskStatus;
88
+ tasks: Task[];
89
+ isRunning?: boolean;
90
+ progress?: {
91
+ total: number;
92
+ completed: number;
93
+ failed: number;
94
+ inProgress: number;
95
+ };
96
+ lastRunAt?: string;
97
+ };
98
+ };
99
+ }
100
+ export {};
@@ -0,0 +1,36 @@
1
+ export declare type ThrottleLevel = number;
2
+ export interface ThrottleExecuteContext {
3
+ /** 事务唯一 key */
4
+ key: string;
5
+ /** 当前节流窗口内的触发次数 */
6
+ count: number;
7
+ /** 是否首次立即执行 */
8
+ isFirst: boolean;
9
+ /** 当前节流等级 */
10
+ level: ThrottleLevel;
11
+ /** 上一次执行时间 */
12
+ lastExecuteTime: number;
13
+ }
14
+ export declare type ThrottleHandler = (ctx: ThrottleExecuteContext) => void | Promise<void>;
15
+ export declare const DEFAULT_THROTTLE_INTERVALS: number[];
16
+ export declare class AdaptiveThrottle {
17
+ private store;
18
+ private intervals;
19
+ constructor(intervals?: number[]);
20
+ /**
21
+ * 触发事务
22
+ */
23
+ trigger(key: string, handler: ThrottleHandler): void;
24
+ /**
25
+ * 调度下一次节流执行
26
+ */
27
+ private schedule;
28
+ /**
29
+ * 主动清理某个事务
30
+ */
31
+ clear(key: string): void;
32
+ /**
33
+ * 清空所有事务
34
+ */
35
+ clearAll(): void;
36
+ }
@@ -0,0 +1,136 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
7
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
8
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
10
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
11
+ export var DEFAULT_THROTTLE_INTERVALS = [5 * 60 * 1000,
12
+ // 5分钟
13
+ 30 * 60 * 1000,
14
+ // 30分钟
15
+ 60 * 60 * 1000,
16
+ // 1小时
17
+ 6 * 60 * 60 * 1000,
18
+ // 6小时
19
+ 24 * 60 * 60 * 1000 // 1天
20
+ ];
21
+ export var AdaptiveThrottle = /*#__PURE__*/function () {
22
+ function AdaptiveThrottle() {
23
+ var intervals = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_THROTTLE_INTERVALS;
24
+ _classCallCheck(this, AdaptiveThrottle);
25
+ _defineProperty(this, "store", new Map());
26
+ _defineProperty(this, "intervals", void 0);
27
+ this.intervals = intervals;
28
+ }
29
+
30
+ /**
31
+ * 触发事务
32
+ */
33
+ _createClass(AdaptiveThrottle, [{
34
+ key: "trigger",
35
+ value: function trigger(key, handler) {
36
+ var now = Date.now();
37
+ var record = this.store.get(key);
38
+
39
+ // ① 首次调用:立即执行
40
+ if (!record) {
41
+ handler({
42
+ key: key,
43
+ count: 1,
44
+ isFirst: true,
45
+ level: 0,
46
+ lastExecuteTime: now
47
+ });
48
+ record = {
49
+ key: key,
50
+ count: 0,
51
+ level: 0,
52
+ lastExecuteTime: now
53
+ };
54
+ this.store.set(key, record);
55
+ this.schedule(key, handler, record);
56
+ return;
57
+ }
58
+
59
+ // ② 同 key 事务:累计次数
60
+ record.count++;
61
+ }
62
+
63
+ /**
64
+ * 调度下一次节流执行
65
+ */
66
+ }, {
67
+ key: "schedule",
68
+ value: function schedule(key, handler, record) {
69
+ var _this = this;
70
+ var interval = this.intervals[record.level];
71
+ record.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
72
+ var count;
73
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
74
+ while (1) switch (_context.prev = _context.next) {
75
+ case 0:
76
+ count = record.count;
77
+ if (!(count > 0)) {
78
+ _context.next = 4;
79
+ break;
80
+ }
81
+ _context.next = 4;
82
+ return handler({
83
+ key: key,
84
+ count: count,
85
+ isFirst: false,
86
+ level: record.level,
87
+ lastExecuteTime: record.lastExecuteTime
88
+ });
89
+ case 4:
90
+ // 自适应升级节流等级
91
+ if (count > 0 && record.level < _this.intervals.length - 1) {
92
+ record.level++;
93
+ }
94
+ record.count = 0;
95
+ record.lastExecuteTime = Date.now();
96
+
97
+ // 继续下一轮
98
+ _this.schedule(key, handler, record);
99
+ case 8:
100
+ case "end":
101
+ return _context.stop();
102
+ }
103
+ }, _callee);
104
+ })), interval);
105
+ }
106
+
107
+ /**
108
+ * 主动清理某个事务
109
+ */
110
+ }, {
111
+ key: "clear",
112
+ value: function clear(key) {
113
+ var record = this.store.get(key);
114
+ if (!record) return;
115
+ if (record.timer) {
116
+ clearTimeout(record.timer);
117
+ }
118
+ this.store.delete(key);
119
+ }
120
+
121
+ /**
122
+ * 清空所有事务
123
+ */
124
+ }, {
125
+ key: "clearAll",
126
+ value: function clearAll() {
127
+ this.store.forEach(function (record) {
128
+ if (record.timer) {
129
+ clearTimeout(record.timer);
130
+ }
131
+ });
132
+ this.store.clear();
133
+ }
134
+ }]);
135
+ return AdaptiveThrottle;
136
+ }();