@lark-apaas/client-toolkit 1.0.5 → 1.0.7

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.
@@ -1,3 +1,4 @@
1
+ import { batchLogInfo, destroyBatchLogger, initBatchLogger } from "../../logger/batch-logger.js";
1
2
  import { postMessage } from "../../utils/postMessage.js";
2
3
  const PROXY_CONSOLE_METHOD = [
3
4
  'log',
@@ -9,6 +10,20 @@ const LOG_FILTER_PREFIX = [
9
10
  '[Dataloom]',
10
11
  '[MiaoDa]'
11
12
  ];
13
+ function formatArg(arg) {
14
+ if (null === arg) return 'null';
15
+ if (void 0 === arg) return 'undefined';
16
+ if ('object' == typeof arg) {
17
+ if (arg instanceof Error) return `${arg.name}: ${arg.message}\n${arg.stack}`;
18
+ try {
19
+ return JSON.stringify(arg, this.getCircularReplacer(), 2);
20
+ } catch (e) {
21
+ return Object.prototype.toString.call(arg);
22
+ }
23
+ }
24
+ if ('function' == typeof arg) return arg.toString();
25
+ return String(arg);
26
+ }
12
27
  const initHandleError = ()=>{
13
28
  window.onerror = (message, source, lineno, colno, error)=>{
14
29
  const errorList = [];
@@ -24,16 +39,23 @@ const initHandleError = ()=>{
24
39
  };
25
40
  };
26
41
  const initLogInterceptor = ()=>{
42
+ initBatchLogger(console);
43
+ window.addEventListener('beforeunload', ()=>{
44
+ destroyBatchLogger();
45
+ });
27
46
  PROXY_CONSOLE_METHOD.forEach((method)=>{
28
47
  const originalMethod = window.console[method];
29
48
  window.console[method] = (...args)=>{
30
49
  originalMethod(...args);
31
50
  const log = args[0];
32
- if ('string' == typeof log && LOG_FILTER_PREFIX.some((prefix)=>log.startsWith(prefix))) postMessage({
33
- type: 'Console',
34
- method,
35
- data: args
36
- });
51
+ if ('string' == typeof log && LOG_FILTER_PREFIX.some((prefix)=>log.startsWith(prefix))) {
52
+ batchLogInfo(method, args.map(formatArg).join(' '));
53
+ postMessage({
54
+ type: 'Console',
55
+ method,
56
+ data: args
57
+ });
58
+ }
37
59
  };
38
60
  });
39
61
  };
@@ -10,11 +10,13 @@ import { ThemeProvider, findValueByPixel, generateTailwindRadiusToken, themeColo
10
10
  import { registerDayjsPlugins } from "./dayjsPlugins.js";
11
11
  import "../../index.css";
12
12
  import { initAxiosConfig } from "../../utils/axiosConfig.js";
13
+ import { useAppInfo } from "../../hooks/index.js";
13
14
  registerDayjsPlugins();
14
15
  initAxiosConfig();
15
16
  const isMiaodaPreview = window.IS_MIAODA_PREVIEW;
16
17
  const App = (props)=>{
17
18
  const { themeMeta = {} } = props;
19
+ useAppInfo();
18
20
  const { rem } = findValueByPixel(themeMetaOptions.themeRadius, themeMeta.borderRadius) || {
19
21
  rem: '0.625'
20
22
  };
@@ -1,5 +1,4 @@
1
1
  import { normalizeBasePath } from "../../../utils/utils.js";
2
- import { api_delete, api_get, api_head, api_options, api_patch, api_post, api_put } from "./api-panel.js";
3
2
  async function getRoutes() {
4
3
  let routes = [
5
4
  {
@@ -28,15 +27,6 @@ async function getSourceMap() {
28
27
  }
29
28
  const childApi = {
30
29
  getRoutes,
31
- getSourceMap,
32
- apiProxy: {
33
- api_get: api_get,
34
- api_post: api_post,
35
- api_put: api_put,
36
- api_delete: api_delete,
37
- api_patch: api_patch,
38
- api_head: api_head,
39
- api_options: api_options
40
- }
30
+ getSourceMap
41
31
  };
42
32
  export { childApi };
@@ -1,7 +1,7 @@
1
1
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
2
  import { useCallback, useEffect } from "react";
3
3
  import { useLocation } from "react-router-dom";
4
- import { Button } from "antd";
4
+ import { Button } from "../ui/button.js";
5
5
  import { postMessage } from "../../utils/postMessage.js";
6
6
  import { copyToClipboard } from "../../utils/copyToClipboard.js";
7
7
  const RenderError = (props)=>{
@@ -68,12 +68,12 @@ const RenderError = (props)=>{
68
68
  className: "flex space-x-4",
69
69
  children: [
70
70
  /*#__PURE__*/ jsx(Button, {
71
- className: "bg-white text-gray-600 font-[400] border rounded-[6px] shadow-xs hover:bg-gray-100 active:bg-gray-200 focus:outline-hidden h-[32px] border-[#D0D3D6]",
71
+ className: "bg-white cursor-pointer text-gray-600 font-[400] border rounded-[6px] shadow-xs hover:bg-gray-100 active:bg-gray-200 focus:outline-hidden h-[32px] border-[#D0D3D6]",
72
72
  onClick: onClickCopy,
73
73
  children: "复制错误信息"
74
74
  }),
75
75
  /*#__PURE__*/ jsx(Button, {
76
- className: "h-[32px] text-sm font-medium text-white bg-blue-600 border border-transparent rounded-[6px] shadow-xs hover:bg-blue-600 active:bg-blue-700 focus:outline-hidden ",
76
+ className: "cursor-pointer h-[32px] text-sm font-medium text-white bg-blue-600 border border-transparent rounded-[6px] shadow-xs hover:bg-blue-600 active:bg-blue-700 focus:outline-hidden ",
77
77
  onClick: onClickRepair,
78
78
  children: "告诉妙搭修复"
79
79
  })
@@ -1,7 +1,7 @@
1
1
  import * as React from "react";
2
2
  import { type VariantProps } from "class-variance-authority";
3
3
  declare const badgeVariants: (props?: {
4
- variant?: "default" | "secondary" | "destructive" | "outline";
4
+ variant?: "default" | "destructive" | "outline" | "secondary";
5
5
  } & import("class-variance-authority/dist/types").ClassProp) => string;
6
6
  declare function Badge({ className, variant, asChild, ...props }: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & {
7
7
  asChild?: boolean;
@@ -1,8 +1,8 @@
1
1
  import * as React from "react";
2
2
  import { type VariantProps } from "class-variance-authority";
3
3
  declare const buttonVariants: (props?: {
4
- variant?: "default" | "link" | "secondary" | "destructive" | "outline" | "ghost";
5
- size?: "default" | "sm" | "lg" | "icon" | "icon-sm" | "icon-lg";
4
+ variant?: "default" | "link" | "destructive" | "outline" | "secondary" | "ghost";
5
+ size?: "default" | "icon" | "sm" | "lg" | "icon-sm" | "icon-lg";
6
6
  } & import("class-variance-authority/dist/types").ClassProp) => string;
7
7
  declare function Button({ className, variant, size, asChild, ...props }: React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & {
8
8
  asChild?: boolean;
@@ -4,7 +4,18 @@ const useAppInfo = ()=>{
4
4
  const [appInfo, setAppInfo] = useState({});
5
5
  useEffect(()=>{
6
6
  const handleMetaInfoChanged = async ()=>{
7
- setAppInfo(await getAppInfo());
7
+ const info = await getAppInfo();
8
+ if (info.name) document.title = info.name;
9
+ if (info.avatar) {
10
+ let link = document.querySelector("link[rel~='icon']");
11
+ if (!link) {
12
+ link = document.createElement('link');
13
+ link.rel = 'icon';
14
+ document.head.appendChild(link);
15
+ }
16
+ link.href = info.avatar;
17
+ }
18
+ setAppInfo(info);
8
19
  };
9
20
  handleMetaInfoChanged();
10
21
  window.addEventListener('MiaoDaMetaInfoChanged', handleMetaInfoChanged);
@@ -1,13 +1,15 @@
1
1
  import { getInitialInfo } from "../utils/getInitialInfo.js";
2
2
  import { isSparkRuntime } from "../utils/utils.js";
3
3
  async function getAppInfo() {
4
- let appInfo = window._appInfo;
4
+ let appInfo = 'undefined' != typeof window ? window._appInfo : void 0;
5
5
  if (!appInfo && isSparkRuntime()) {
6
- const info = (await getInitialInfo()).app_info;
6
+ const info = (await getInitialInfo())?.app_info;
7
7
  appInfo = {
8
8
  name: info?.app_name || '',
9
9
  avatar: info?.app_avatar || ''
10
10
  };
11
+ if (appInfo.name) appInfo.name = appInfo.name.trim();
12
+ if ('undefined' != typeof window) window._appInfo = appInfo;
11
13
  }
12
14
  return appInfo ?? {};
13
15
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,367 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { BatchLogger, batchLogInfo, initBatchLogger } from "../batch-logger.js";
3
+ var __webpack_require__ = {};
4
+ (()=>{
5
+ __webpack_require__.g = (()=>{
6
+ if ('object' == typeof globalThis) return globalThis;
7
+ try {
8
+ return this || new Function('return this')();
9
+ } catch (e) {
10
+ if ('object' == typeof window) return window;
11
+ }
12
+ })();
13
+ })();
14
+ vi.mock('node-fetch', ()=>({
15
+ default: vi.fn()
16
+ }));
17
+ const mockConsole = {
18
+ debug: vi.fn(),
19
+ info: vi.fn(),
20
+ warn: vi.fn(),
21
+ error: vi.fn(),
22
+ log: vi.fn()
23
+ };
24
+ describe('BatchLogger', ()=>{
25
+ let batchLogger;
26
+ let mockFetch;
27
+ beforeEach(()=>{
28
+ vi.clearAllMocks();
29
+ mockFetch = vi.fn();
30
+ __webpack_require__.g.fetch = mockFetch;
31
+ const mockResponse = new Response(JSON.stringify({
32
+ success: true
33
+ }), {
34
+ status: 200,
35
+ statusText: 'OK',
36
+ headers: {
37
+ 'Content-Type': 'application/json'
38
+ }
39
+ });
40
+ mockFetch.mockResolvedValue(mockResponse);
41
+ if ('undefined' == typeof window) __webpack_require__.g.window = void 0;
42
+ });
43
+ afterEach(async ()=>{
44
+ if (batchLogger) await batchLogger.destroy();
45
+ });
46
+ afterAll(()=>{
47
+ vi.restoreAllMocks();
48
+ });
49
+ describe('Basic Functionality', ()=>{
50
+ it('should create a BatchLogger instance', ()=>{
51
+ batchLogger = new BatchLogger(mockConsole, {
52
+ userId: 'user123',
53
+ tenantId: 'tenant456',
54
+ appId: 'app789'
55
+ });
56
+ expect(batchLogger).toBeInstanceOf(BatchLogger);
57
+ });
58
+ it('should add logs to queue', ()=>{
59
+ batchLogger = new BatchLogger(mockConsole, {
60
+ userId: 'user123',
61
+ tenantId: 'tenant456',
62
+ appId: 'app789'
63
+ });
64
+ batchLogger.batchLog('info', 'Test message', 'test-source');
65
+ expect(batchLogger.getQueueSize()).toBe(1);
66
+ });
67
+ it('should respect batch size limit', async ()=>{
68
+ batchLogger = new BatchLogger(mockConsole, {
69
+ userId: 'user123',
70
+ tenantId: 'tenant456',
71
+ appId: 'app789',
72
+ sizeThreshold: 3,
73
+ flushInterval: 10000
74
+ });
75
+ for(let i = 0; i < 5; i++)batchLogger.batchLog('info', `Message ${i}`);
76
+ await new Promise((resolve)=>setTimeout(resolve, 200));
77
+ expect(mockFetch).toHaveBeenCalled();
78
+ expect(mockFetch.mock.calls.length).toBeGreaterThanOrEqual(1);
79
+ expect(batchLogger.getQueueSize()).toBeLessThanOrEqual(2);
80
+ });
81
+ });
82
+ describe('Log Preservation', ()=>{
83
+ it('should preserve all logs without merging', ()=>{
84
+ batchLogger = new BatchLogger(mockConsole, {
85
+ userId: 'user123',
86
+ tenantId: 'tenant456',
87
+ appId: 'app789'
88
+ });
89
+ for(let i = 0; i < 5; i++)batchLogger.batchLog('error', 'Same error message');
90
+ expect(batchLogger.getQueueSize()).toBe(5);
91
+ });
92
+ it('should handle different log levels independently', ()=>{
93
+ batchLogger = new BatchLogger(mockConsole, {
94
+ userId: 'user123',
95
+ tenantId: 'tenant456',
96
+ appId: 'app789'
97
+ });
98
+ batchLogger.batchLog('info', 'Test message');
99
+ batchLogger.batchLog('info', 'Test message');
100
+ batchLogger.batchLog('warn', 'Test message');
101
+ batchLogger.batchLog('warn', 'Test message');
102
+ expect(batchLogger.getQueueSize()).toBe(4);
103
+ });
104
+ it('should handle large volumes of logs efficiently', ()=>{
105
+ batchLogger = new BatchLogger(mockConsole, {
106
+ userId: 'user123',
107
+ tenantId: 'tenant456',
108
+ appId: 'app789',
109
+ sizeThreshold: 1000,
110
+ flushInterval: 10000
111
+ });
112
+ for(let i = 0; i < 200; i++)batchLogger.batchLog('info', `Message ${i}`);
113
+ expect(batchLogger.getQueueSize()).toBe(200);
114
+ });
115
+ });
116
+ describe('Retry Mechanism', ()=>{
117
+ it('should retry failed requests', async ()=>{
118
+ batchLogger = new BatchLogger(mockConsole, {
119
+ userId: 'user123',
120
+ tenantId: 'tenant456',
121
+ appId: 'app789',
122
+ maxRetries: 2,
123
+ retryDelay: 100,
124
+ flushInterval: 10000
125
+ });
126
+ const successResponse = new Response(JSON.stringify({
127
+ success: true
128
+ }), {
129
+ status: 200,
130
+ statusText: 'OK',
131
+ headers: {
132
+ 'Content-Type': 'application/json'
133
+ }
134
+ });
135
+ mockFetch.mockRejectedValueOnce(new Error('Network error')).mockRejectedValueOnce(new Error('Network error')).mockResolvedValueOnce(successResponse);
136
+ batchLogger.batchLog('info', 'Test message');
137
+ await batchLogger.flush();
138
+ expect(mockFetch).toHaveBeenCalled();
139
+ expect(mockFetch.mock.calls.length).toBeGreaterThanOrEqual(3);
140
+ });
141
+ it('should handle permanent failures', async ()=>{
142
+ batchLogger = new BatchLogger(mockConsole, {
143
+ userId: 'user123',
144
+ tenantId: 'tenant456',
145
+ appId: 'app789',
146
+ maxRetries: 1,
147
+ retryDelay: 100,
148
+ flushInterval: 10000
149
+ });
150
+ mockFetch.mockRejectedValue(new Error('Permanent error'));
151
+ batchLogger.batchLog('info', 'Test message');
152
+ await batchLogger.flush();
153
+ expect(mockConsole.warn).toHaveBeenCalled();
154
+ });
155
+ });
156
+ describe('Auto Flush', ()=>{
157
+ it('should auto flush based on interval', async ()=>{
158
+ batchLogger = new BatchLogger(mockConsole, {
159
+ userId: 'user123',
160
+ tenantId: 'tenant456',
161
+ appId: 'app789',
162
+ flushInterval: 1000,
163
+ sizeThreshold: 100
164
+ });
165
+ for(let i = 0; i < 3; i++)batchLogger.batchLog('info', `Message ${i}`);
166
+ await new Promise((resolve)=>setTimeout(resolve, 1200));
167
+ expect(mockFetch).toHaveBeenCalled();
168
+ expect(batchLogger.getQueueSize()).toBe(0);
169
+ });
170
+ });
171
+ describe('Request Configuration', ()=>{
172
+ it('should include custom headers', async ()=>{
173
+ batchLogger = new BatchLogger(mockConsole, {
174
+ userId: 'user123',
175
+ tenantId: 'tenant456',
176
+ appId: 'app789',
177
+ endpoint: 'https://api.example.com/logs',
178
+ headers: {
179
+ Authorization: 'Bearer token123',
180
+ 'X-Custom-Header': 'custom-value'
181
+ },
182
+ flushInterval: 1000
183
+ });
184
+ batchLogger.batchLog('info', 'Test message');
185
+ await batchLogger.flush();
186
+ expect(mockFetch).toHaveBeenCalledWith('https://api.example.com/logs', expect.objectContaining({
187
+ headers: expect.objectContaining({
188
+ Authorization: 'Bearer token123',
189
+ 'X-Custom-Header': 'custom-value'
190
+ })
191
+ }));
192
+ });
193
+ it('should send correct batch format', async ()=>{
194
+ batchLogger = new BatchLogger(mockConsole, {
195
+ userId: 'user123',
196
+ tenantId: 'tenant456',
197
+ appId: 'app789',
198
+ flushInterval: 10000
199
+ });
200
+ batchLogger.batchLog('info', 'Test message', 'test-source');
201
+ await batchLogger.flush();
202
+ expect(mockFetch).toHaveBeenCalledWith('/dev/logs/collect-batch', expect.objectContaining({
203
+ method: 'POST',
204
+ headers: {
205
+ 'Content-Type': 'application/json'
206
+ }
207
+ }));
208
+ const callBody = JSON.parse(mockFetch.mock.calls[0][1].body);
209
+ expect(Array.isArray(callBody)).toBe(true);
210
+ expect(callBody).toHaveLength(1);
211
+ expect(callBody[0]).toMatchObject({
212
+ level: 'info',
213
+ message: 'Test message',
214
+ source: 'test-source',
215
+ user_id: 'user123',
216
+ tenant_id: 'tenant456',
217
+ app_id: 'app789'
218
+ });
219
+ });
220
+ });
221
+ describe('Global Instance Management', ()=>{
222
+ it('should initialize global batch logger instance', ()=>{
223
+ initBatchLogger(mockConsole, {
224
+ userId: 'user123',
225
+ tenantId: 'tenant456',
226
+ appId: 'app789'
227
+ });
228
+ expect(()=>batchLogInfo('info', 'Test message')).not.toThrow();
229
+ });
230
+ it('should handle batchLogInfo when no instance exists', ()=>{
231
+ expect(()=>batchLogInfo('info', 'Test message')).not.toThrow();
232
+ });
233
+ });
234
+ describe('Configuration Updates', ()=>{
235
+ it('should update configuration', ()=>{
236
+ batchLogger = new BatchLogger(mockConsole, {
237
+ userId: 'user123',
238
+ tenantId: 'tenant456',
239
+ appId: 'app789',
240
+ sizeThreshold: 10
241
+ });
242
+ batchLogger.updateConfig({
243
+ sizeThreshold: 20,
244
+ maxRetries: 5
245
+ });
246
+ for(let i = 0; i < 21; i++)batchLogger.batchLog('info', `Message ${i}`);
247
+ expect(batchLogger.getQueueSize()).toBe(1);
248
+ });
249
+ });
250
+ describe('High Volume Log Processing', ()=>{
251
+ it('should handle large batch of logs without crashing', async ()=>{
252
+ batchLogger = new BatchLogger(mockConsole, {
253
+ userId: 'user123',
254
+ tenantId: 'tenant456',
255
+ appId: 'app789',
256
+ sizeThreshold: 50,
257
+ flushInterval: 1000
258
+ });
259
+ const largeBatchSize = 1000;
260
+ const startTime = Date.now();
261
+ for(let i = 0; i < largeBatchSize; i++)batchLogger.batchLog('info', `High volume log message ${i % 100}`, 'stress-test');
262
+ const endTime = Date.now();
263
+ expect(endTime - startTime).toBeLessThan(5000);
264
+ await new Promise((resolve)=>setTimeout(resolve, 2000));
265
+ expect(batchLogger.getQueueSize()).toBe(0);
266
+ expect(mockFetch).toHaveBeenCalled();
267
+ const callCount = mockFetch.mock.calls.length;
268
+ expect(callCount).toBeGreaterThan(0);
269
+ expect(callCount).toBeLessThanOrEqual(25);
270
+ });
271
+ it('should control request frequency under high load', async ()=>{
272
+ batchLogger = new BatchLogger(mockConsole, {
273
+ userId: 'user123',
274
+ tenantId: 'tenant456',
275
+ appId: 'app789',
276
+ sizeThreshold: 30,
277
+ flushInterval: 500
278
+ });
279
+ const requestsBefore = mockFetch.mock.calls.length;
280
+ for(let batch = 0; batch < 5; batch++){
281
+ for(let i = 0; i < 25; i++)batchLogger.batchLog('error', `Error message ${batch}`, 'high-frequency-test');
282
+ await new Promise((resolve)=>setTimeout(resolve, 50));
283
+ }
284
+ await new Promise((resolve)=>setTimeout(resolve, 1000));
285
+ const totalRequests = mockFetch.mock.calls.length - requestsBefore;
286
+ expect(totalRequests).toBeGreaterThan(0);
287
+ expect(totalRequests).toBeLessThanOrEqual(10);
288
+ });
289
+ });
290
+ describe('Edge Cases', ()=>{
291
+ it('should handle empty flush', async ()=>{
292
+ batchLogger = new BatchLogger(mockConsole, {
293
+ userId: 'user123',
294
+ tenantId: 'tenant456',
295
+ appId: 'app789'
296
+ });
297
+ await batchLogger.flush();
298
+ expect(mockFetch).not.toHaveBeenCalled();
299
+ });
300
+ it('should handle concurrent flush calls safely', async ()=>{
301
+ batchLogger = new BatchLogger(mockConsole, {
302
+ userId: 'user123',
303
+ tenantId: 'tenant456',
304
+ appId: 'app789',
305
+ flushInterval: 10000
306
+ });
307
+ for(let i = 0; i < 20; i++)batchLogger.batchLog('info', `Message ${i}`);
308
+ const flushPromises = [];
309
+ for(let i = 0; i < 10; i++)flushPromises.push(batchLogger.flush());
310
+ await Promise.all(flushPromises);
311
+ expect(batchLogger.getQueueSize()).toBe(0);
312
+ expect(mockFetch.mock.calls.length).toBeGreaterThan(0);
313
+ expect(mockFetch.mock.calls.length).toBeLessThanOrEqual(3);
314
+ });
315
+ it('should ensure no logs remain after destroy', async ()=>{
316
+ mockFetch.mockResolvedValueOnce(new Response(JSON.stringify({
317
+ success: true
318
+ }), {
319
+ status: 200,
320
+ statusText: 'OK',
321
+ headers: {
322
+ 'Content-Type': 'application/json'
323
+ }
324
+ }));
325
+ batchLogger = new BatchLogger(mockConsole, {
326
+ userId: 'user123',
327
+ tenantId: 'tenant456',
328
+ appId: 'app789',
329
+ flushInterval: 10000,
330
+ sizeThreshold: 1000
331
+ });
332
+ for(let i = 0; i < 50; i++){
333
+ batchLogger.batchLog('info', `Test message info ${i}`);
334
+ batchLogger.batchLog('warn', `Warning message warn ${i}`);
335
+ }
336
+ const queueSize = batchLogger.getQueueSize();
337
+ expect(queueSize).toBe(100);
338
+ const fetchCallsBefore = mockFetch.mock.calls.length;
339
+ await batchLogger.destroy();
340
+ const queueSizeAfter = batchLogger.getQueueSize();
341
+ const fetchCallsAfter = mockFetch.mock.calls.length;
342
+ expect(queueSizeAfter).toBe(0);
343
+ expect(fetchCallsAfter).toBeGreaterThan(fetchCallsBefore);
344
+ });
345
+ it('should handle environment detection without browser APIs', ()=>{
346
+ batchLogger = new BatchLogger(mockConsole, {
347
+ userId: 'user123',
348
+ tenantId: 'tenant456',
349
+ appId: 'app789'
350
+ });
351
+ batchLogger.batchLog('info', 'Test message');
352
+ expect(batchLogger.getQueueSize()).toBe(1);
353
+ });
354
+ it('should handle destroy method with pending logs', async ()=>{
355
+ batchLogger = new BatchLogger(mockConsole, {
356
+ userId: 'user123',
357
+ tenantId: 'tenant456',
358
+ appId: 'app789'
359
+ });
360
+ batchLogger.batchLog('info', 'Test message');
361
+ batchLogger.batchLog('warn', 'Warning message');
362
+ await batchLogger.destroy();
363
+ expect(batchLogger.getQueueSize()).toBe(0);
364
+ expect(mockFetch).toHaveBeenCalled();
365
+ });
366
+ });
367
+ });
@@ -0,0 +1,78 @@
1
+ interface BatchLoggerConfig {
2
+ /** 用户ID */
3
+ userId: string;
4
+ /** 租户ID */
5
+ tenantId: string;
6
+ /** 应用ID */
7
+ appId: string;
8
+ /** 后端接收日志的接口地址,默认为/dev/logs/collect */
9
+ endpoint?: string;
10
+ /** 达到此数量时触发刷新 */
11
+ sizeThreshold?: number;
12
+ /** 自动刷新的时间间隔(毫秒) */
13
+ flushInterval?: number;
14
+ /** 最大重试次数 */
15
+ maxRetries?: number;
16
+ /** 重试延迟(毫秒) */
17
+ retryDelay?: number;
18
+ /** 自定义请求头 */
19
+ headers?: Record<string, string>;
20
+ }
21
+ export declare class BatchLogger {
22
+ private config;
23
+ private logQueue;
24
+ private flushTimer;
25
+ private isProcessing;
26
+ private originConsole;
27
+ constructor(console: Console, config?: BatchLoggerConfig);
28
+ /**
29
+ * 批量记录日志(对外暴露的唯一方法)
30
+ */
31
+ batchLog(level: string, message: string, source?: string): void;
32
+ /**
33
+ * 刷新日志队列,全部发送
34
+ */
35
+ flush(): Promise<void>;
36
+ /**
37
+ * 发送日志批次到后端
38
+ */
39
+ private sendBatch;
40
+ /**
41
+ * 执行实际的fetch请求
42
+ */
43
+ private execFetch;
44
+ /**
45
+ * 启动自动刷新定时器
46
+ */
47
+ private startFlushTimer;
48
+ /**
49
+ * 设置页面卸载时的处理
50
+ */
51
+ private setupBeforeUnloadHandler;
52
+ /**
53
+ * 延迟函数
54
+ */
55
+ private delay;
56
+ /**
57
+ * 生成唯一ID
58
+ */
59
+ private generateId;
60
+ /**
61
+ * 销毁资源
62
+ */
63
+ destroy(): Promise<void>;
64
+ /**
65
+ * 获取队列大小
66
+ */
67
+ getQueueSize(): number;
68
+ /**
69
+ * 更新配置
70
+ */
71
+ updateConfig(newConfig: Partial<BatchLoggerConfig>): void;
72
+ }
73
+ export declare function getBatchLogger(): BatchLogger;
74
+ export declare function initBatchLogger(oldConsole: Console, config?: BatchLoggerConfig): void;
75
+ /** 记录日志进行批量同步 */
76
+ export declare function batchLogInfo(level: string, message: string, source?: string): void;
77
+ export declare function destroyBatchLogger(): void;
78
+ export {};