@ohbug/core 2.2.0 → 2.2.2

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/dist/index.js DELETED
@@ -1,635 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __spreadValues = (a, b) => {
10
- for (var prop in b || (b = {}))
11
- if (__hasOwnProp.call(b, prop))
12
- __defNormalProp(a, prop, b[prop]);
13
- if (__getOwnPropSymbols)
14
- for (var prop of __getOwnPropSymbols(b)) {
15
- if (__propIsEnum.call(b, prop))
16
- __defNormalProp(a, prop, b[prop]);
17
- }
18
- return a;
19
- };
20
- var __export = (target, all) => {
21
- for (var name in all)
22
- __defProp(target, name, { get: all[name], enumerable: true });
23
- };
24
- var __copyProps = (to, from, except, desc) => {
25
- if (from && typeof from === "object" || typeof from === "function") {
26
- for (let key of __getOwnPropNames(from))
27
- if (!__hasOwnProp.call(to, key) && key !== except)
28
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
- }
30
- return to;
31
- };
32
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
- var __publicField = (obj, key, value) => {
34
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
35
- return value;
36
- };
37
-
38
- // src/index.ts
39
- var src_exports = {};
40
- __export(src_exports, {
41
- Client: () => Client,
42
- EventTypes: () => EventTypes,
43
- defineExtension: () => defineExtension,
44
- isEvent: () => isEvent
45
- });
46
- module.exports = __toCommonJS(src_exports);
47
-
48
- // src/client.ts
49
- var import_utils4 = require("@ohbug/utils");
50
-
51
- // src/config.ts
52
- var import_utils = require("@ohbug/utils");
53
- var schema = {
54
- // base
55
- apiKey: {
56
- defaultValue: void 0,
57
- message: "is required",
58
- validate: (value) => Boolean(value) && (0, import_utils.isString)(value)
59
- },
60
- appVersion: {
61
- defaultValue: void 0,
62
- message: "should be a string",
63
- validate: (value) => value === void 0 || (0, import_utils.isString)(value)
64
- },
65
- appType: {
66
- defaultValue: void 0,
67
- message: "should be a string",
68
- validate: (value) => value === void 0 || (0, import_utils.isString)(value)
69
- },
70
- releaseStage: {
71
- defaultValue: "production",
72
- message: "should be a string",
73
- validate: (value) => value === void 0 || (0, import_utils.isString)(value)
74
- },
75
- endpoint: {
76
- defaultValue: "http://localhost:6660",
77
- message: "should be a string",
78
- validate: (value) => value === void 0 || (0, import_utils.isString)(value)
79
- },
80
- maxActions: {
81
- defaultValue: 30,
82
- message: "should be a number between 0 and 100",
83
- validate: (value) => value === void 0 || (0, import_utils.isNumber)(value) && value >= 0 && value <= 100
84
- },
85
- // hooks
86
- onEvent: {
87
- defaultValue: (event) => event,
88
- message: "should be a function",
89
- validate: (value) => value === void 0 || (0, import_utils.isFunction)(value)
90
- },
91
- onNotify: {
92
- defaultValue: () => {
93
- },
94
- message: "should be a function",
95
- validate: (value) => value === void 0 || (0, import_utils.isFunction)(value)
96
- },
97
- // utils
98
- logger: {
99
- defaultValue: import_utils.logger,
100
- message: "should be null or an object with methods { log, info, warn, error }",
101
- validate: (value) => value === void 0 || value && ["log", "info", "warn", "error"].reduce(
102
- (accumulator, method) => accumulator && typeof value[method] === "function",
103
- true
104
- )
105
- },
106
- // data
107
- user: {
108
- defaultValue: void 0,
109
- message: "should be an object and have up to 6 attributes",
110
- validate: (value) => value === void 0 || (0, import_utils.isObject)(value) && Object.keys(value).length <= 6
111
- },
112
- metadata: {
113
- defaultValue: void 0,
114
- message: "should be an object",
115
- validate: (value) => value === void 0 || (0, import_utils.isObject)(value)
116
- }
117
- };
118
-
119
- // src/event.ts
120
- var import_utils2 = require("@ohbug/utils");
121
-
122
- // src/action.ts
123
- var Action = class {
124
- constructor(message, data, type, timestamp) {
125
- __publicField(this, "type");
126
- __publicField(this, "timestamp");
127
- __publicField(this, "message");
128
- __publicField(this, "data");
129
- this.type = type;
130
- this.timestamp = timestamp || (/* @__PURE__ */ new Date()).toISOString();
131
- this.message = message;
132
- this.data = data;
133
- }
134
- };
135
-
136
- // src/lib/getErrorMessage.ts
137
- function getConfigErrorMessage(errors, config) {
138
- return new Error(`Invalid configuration
139
- ${Object.keys(errors).map((key) => {
140
- return `- ${key} ${errors[key]}, got ${JSON.stringify(config[key])}`;
141
- }).join("\n")}
142
- `);
143
- }
144
- function getErrorMessage(message, data) {
145
- return new Error(`Invalid data
146
- - ${message}, got ${JSON.stringify(data)}`);
147
- }
148
-
149
- // src/lib/metadata.ts
150
- function addMetadata(map, section, data) {
151
- if (!section)
152
- return;
153
- map[section] = data;
154
- }
155
- function getMetadata(map, section) {
156
- if (map[section]) {
157
- return map[section];
158
- }
159
- return void 0;
160
- }
161
- function deleteMetadata(map, section) {
162
- if (map[section]) {
163
- return delete map[section];
164
- }
165
- return void 0;
166
- }
167
-
168
- // src/event.ts
169
- var Event = class {
170
- constructor(values, client) {
171
- __publicField(this, "apiKey");
172
- __publicField(this, "appVersion");
173
- __publicField(this, "appType");
174
- __publicField(this, "timestamp");
175
- __publicField(this, "category");
176
- __publicField(this, "type");
177
- __publicField(this, "sdk");
178
- __publicField(this, "device");
179
- __publicField(this, "detail");
180
- __publicField(this, "user");
181
- __publicField(this, "actions");
182
- __publicField(this, "metadata");
183
- __publicField(this, "releaseStage");
184
- __publicField(this, "__client");
185
- const {
186
- apiKey,
187
- appVersion,
188
- appType,
189
- releaseStage,
190
- timestamp,
191
- category,
192
- type,
193
- sdk,
194
- detail,
195
- device,
196
- user,
197
- actions,
198
- metadata
199
- } = values;
200
- this.apiKey = apiKey;
201
- this.appVersion = appVersion;
202
- this.appType = appType;
203
- this.releaseStage = releaseStage;
204
- this.timestamp = timestamp;
205
- this.category = category;
206
- this.type = type;
207
- this.sdk = sdk;
208
- this.detail = detail;
209
- this.device = device;
210
- this.user = user;
211
- this.actions = actions;
212
- this.metadata = metadata != null ? metadata : {};
213
- this.__client = client;
214
- }
215
- get __isOhbugEvent() {
216
- return true;
217
- }
218
- /**
219
- * Add an action.
220
- * Once the threshold is reached, the oldest actions will be deleted.
221
- * 新增一个动作。
222
- * 一旦达到阈值,最老的 Action 将被删除。
223
- *
224
- * @param message
225
- * @param data
226
- * @param type
227
- * @param timestamp
228
- */
229
- addAction(message, data, type, timestamp) {
230
- var _a, _b;
231
- const actions = this.actions;
232
- const targetMessage = (0, import_utils2.isString)(message) ? message : "";
233
- const targetData = data || {};
234
- const targetType = (0, import_utils2.isString)(type) ? type : "";
235
- const action = new Action(targetMessage, targetData, targetType, timestamp);
236
- const maxActions = (_b = (_a = this.__client) == null ? void 0 : _a.__config.maxActions) != null ? _b : 30;
237
- if (maxActions > 0) {
238
- if (actions.length >= maxActions) {
239
- actions.shift();
240
- }
241
- actions.push(action);
242
- }
243
- }
244
- /**
245
- * Get current user information
246
- * 获取当前的用户信息
247
- */
248
- getUser() {
249
- return this.user;
250
- }
251
- /**
252
- * Set current user information
253
- * 设置当前的用户信息
254
- */
255
- setUser(user) {
256
- var _a;
257
- if ((0, import_utils2.isObject)(user) && Object.keys(user).length <= 6) {
258
- this.user = __spreadValues(__spreadValues({}, this.user), user);
259
- return this.getUser();
260
- }
261
- (_a = this.__client) == null ? void 0 : _a.__logger.error(getErrorMessage(
262
- "setUser should be an object and have up to 6 attributes",
263
- user
264
- ));
265
- return void 0;
266
- }
267
- /**
268
- * Add metadata
269
- * 新增 metadata
270
- *
271
- * @param section
272
- * @param data
273
- */
274
- addMetadata(section, data) {
275
- return addMetadata(this.metadata, section, data);
276
- }
277
- /**
278
- * Get metadata
279
- * 获取 metadata
280
- *
281
- * @param section
282
- */
283
- getMetadata(section) {
284
- return getMetadata(this.metadata, section);
285
- }
286
- /**
287
- * Delete metadata
288
- * 删除 metadata
289
- *
290
- * @param section
291
- */
292
- deleteMetadata(section) {
293
- return deleteMetadata(this.metadata, section);
294
- }
295
- toJSON() {
296
- const {
297
- apiKey,
298
- appVersion,
299
- appType,
300
- timestamp,
301
- category,
302
- type,
303
- sdk,
304
- device,
305
- detail,
306
- user,
307
- actions,
308
- metadata,
309
- releaseStage
310
- } = this;
311
- return {
312
- apiKey,
313
- appVersion,
314
- appType,
315
- timestamp,
316
- category,
317
- type,
318
- sdk,
319
- device,
320
- detail,
321
- user,
322
- actions,
323
- metadata,
324
- releaseStage
325
- };
326
- }
327
- };
328
- function createEvent(values, client) {
329
- const { apiKey, appVersion, appType, releaseStage } = client.__config;
330
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
331
- const device = client.__device(client);
332
- let category;
333
- let type;
334
- let detail;
335
- if ((0, import_utils2.isObject)(values) && Object.prototype.hasOwnProperty.call(values, "type") && Object.prototype.hasOwnProperty.call(values, "detail")) {
336
- category = values.category || "error";
337
- type = values.type;
338
- detail = values.detail;
339
- } else {
340
- category = "error";
341
- type = "unknownError";
342
- detail = values;
343
- }
344
- return new Event(
345
- {
346
- apiKey,
347
- appVersion,
348
- appType,
349
- timestamp,
350
- category,
351
- type,
352
- sdk: client.__sdk,
353
- device,
354
- user: client.__user,
355
- detail,
356
- actions: client.__actions,
357
- metadata: client.__metadata,
358
- releaseStage
359
- },
360
- client
361
- );
362
- }
363
- function handleEventCreated(event, client) {
364
- const funcs = [
365
- client.__config.onEvent,
366
- ...client.__extensions.map(({ onEvent }) => onEvent)
367
- ].filter((v) => (0, import_utils2.isFunction)(v));
368
- if (funcs.length === 0) {
369
- return event;
370
- }
371
- return funcs.reduce((previous, current) => {
372
- if (previous && (0, import_utils2.isFunction)(current)) {
373
- return current(previous, client);
374
- }
375
- return null;
376
- }, event);
377
- }
378
- function isEvent(eventLike) {
379
- return Boolean(eventLike == null ? void 0 : eventLike.__isOhbugEvent);
380
- }
381
-
382
- // src/notify.ts
383
- var import_utils3 = require("@ohbug/utils");
384
- function handleNotified(event, client) {
385
- const funcs = [
386
- client.__config.onNotify,
387
- ...client.__extensions.filter(({ onNotify }) => (0, import_utils3.isFunction)(onNotify)).map(({ onNotify }) => onNotify)
388
- ];
389
- funcs.forEach((func) => func == null ? void 0 : func(event, client));
390
- }
391
- async function notify(event, client) {
392
- try {
393
- let result = null;
394
- if (event) {
395
- result = await client.__notifier(event);
396
- handleNotified(event, client);
397
- }
398
- return result;
399
- } catch (e) {
400
- client.__logger.error(e);
401
- }
402
- }
403
-
404
- // src/lib/verifyConfig.ts
405
- function verifyConfig(config, schema2) {
406
- const keys = Object.keys(schema2);
407
- return keys.reduce(
408
- (accumulator, key) => {
409
- const configValue = config[key];
410
- const { defaultValue, message, validate } = schema2[key];
411
- if (configValue !== void 0) {
412
- const valid = validate(configValue);
413
- if (valid) {
414
- accumulator.config[key] = configValue;
415
- } else {
416
- accumulator.config[key] = defaultValue;
417
- accumulator.errors[key] = message;
418
- }
419
- } else {
420
- accumulator.config[key] = defaultValue;
421
- }
422
- return accumulator;
423
- },
424
- {
425
- config: {},
426
- errors: {}
427
- }
428
- );
429
- }
430
-
431
- // src/client.ts
432
- var Client = class Client2 {
433
- constructor({
434
- sdk,
435
- config: baseConfig,
436
- schema: schema2 = schema,
437
- device,
438
- notifier,
439
- destroy
440
- }) {
441
- __publicField(this, "__sdk");
442
- __publicField(this, "__config");
443
- __publicField(this, "__logger");
444
- __publicField(this, "__device");
445
- __publicField(this, "__notifier");
446
- __publicField(this, "__destroy");
447
- __publicField(this, "__extensions");
448
- __publicField(this, "__actions");
449
- __publicField(this, "__user");
450
- __publicField(this, "__metadata");
451
- const { config, errors } = verifyConfig(baseConfig, schema2);
452
- this.__sdk = sdk;
453
- this.__config = config;
454
- this.__logger = config.logger;
455
- this.__device = device;
456
- this.__notifier = notifier;
457
- this.__destroy = destroy;
458
- this.__extensions = [];
459
- this.__actions = [];
460
- this.__user = config.user;
461
- this.__metadata = {};
462
- if ((0, import_utils4.isObject)(config.metadata)) {
463
- Object.keys(config.metadata).forEach((key) => {
464
- this.addMetadata(key, config.metadata[key]);
465
- });
466
- }
467
- if (Object.keys(errors).length) {
468
- this.__logger.warn(getConfigErrorMessage(errors, baseConfig));
469
- }
470
- }
471
- /**
472
- * Load extension
473
- * 加载扩展
474
- *
475
- * @param extension
476
- */
477
- use(extension) {
478
- var _a;
479
- this.__extensions.push(extension);
480
- (_a = extension.onSetup) == null ? void 0 : _a.call(extension, this);
481
- return this;
482
- }
483
- destroy() {
484
- var _a;
485
- if (this.__destroy) {
486
- this.__logger.info(
487
- "%c @ohbug/core %c has been destroyed %c",
488
- "background:#333; padding: 2px 1px; color: #FFF",
489
- "background:#FF6F61; padding: 2px 1px; color: #FFF",
490
- "background:transparent"
491
- );
492
- return (_a = this.__destroy) == null ? void 0 : _a.call(this);
493
- }
494
- }
495
- /**
496
- * Create an event, you will get a data body containing device actions and other information
497
- * 创建事件,将会得到一个含有 device actions 等信息的数据体
498
- *
499
- * @param value
500
- */
501
- createEvent(value) {
502
- const event = createEvent(value, this);
503
- return handleEventCreated(event, this);
504
- }
505
- /**
506
- * Used to trigger the reporting interface
507
- * 用于触发上报接口
508
- *
509
- * @param eventLike
510
- * @param beforeNotify
511
- */
512
- notify(eventLike, beforeNotify) {
513
- let event;
514
- if (Boolean(eventLike) && !isEvent(eventLike)) {
515
- event = this.createEvent(eventLike);
516
- } else {
517
- event = eventLike;
518
- }
519
- if (beforeNotify)
520
- event = beforeNotify(event);
521
- return notify(event, this);
522
- }
523
- /**
524
- * Add an action.
525
- * Once the threshold is reached, the oldest actions will be deleted.
526
- * 新增一个动作。
527
- * 一旦达到阈值,最老的 Action 将被删除。
528
- *
529
- * @param message
530
- * @param data
531
- * @param type
532
- * @param timestamp
533
- */
534
- addAction(message, data, type, timestamp) {
535
- var _a;
536
- const actions = this.__actions;
537
- const targetMessage = (0, import_utils4.isString)(message) ? message : "";
538
- const targetData = data || {};
539
- const targetType = (0, import_utils4.isString)(type) ? type : "";
540
- const action = new Action(targetMessage, targetData, targetType, timestamp);
541
- const maxActions = (_a = this.__config.maxActions) != null ? _a : 30;
542
- if (maxActions > 0) {
543
- if (actions.length >= maxActions) {
544
- actions.shift();
545
- }
546
- actions.push(action);
547
- }
548
- }
549
- /**
550
- * Get current user information
551
- * 获取当前的用户信息
552
- */
553
- getUser() {
554
- return this.__user;
555
- }
556
- /**
557
- * Set current user information
558
- * 设置当前的用户信息
559
- */
560
- setUser(user) {
561
- if ((0, import_utils4.isObject)(user) && Object.keys(user).length <= 6) {
562
- this.__user = __spreadValues(__spreadValues({}, this.__user), user);
563
- return this.getUser();
564
- }
565
- this.__logger.warn(getErrorMessage(
566
- "setUser should be an object and have up to 6 attributes",
567
- user
568
- ));
569
- return void 0;
570
- }
571
- /**
572
- * Add metadata
573
- * 新增 metadata
574
- *
575
- * @param section
576
- * @param data
577
- */
578
- addMetadata(section, data) {
579
- return addMetadata(this.__metadata, section, data);
580
- }
581
- /**
582
- * Get metadata
583
- * 获取 metadata
584
- *
585
- * @param section
586
- */
587
- getMetadata(section) {
588
- return getMetadata(this.__metadata, section);
589
- }
590
- /**
591
- * Delete metadata
592
- * 删除 metadata
593
- *
594
- * @param section
595
- */
596
- deleteMetadata(section) {
597
- return deleteMetadata(this.__metadata, section);
598
- }
599
- };
600
-
601
- // src/extension.ts
602
- function defineExtension(extension) {
603
- if (!extension)
604
- return {};
605
- return extension;
606
- }
607
-
608
- // src/types.ts
609
- var EventTypes = /* @__PURE__ */ ((EventTypes2) => {
610
- EventTypes2["UNCAUGHT_ERROR"] = "uncaughtError";
611
- EventTypes2["RESOURCE_ERROR"] = "resourceError";
612
- EventTypes2["UNHANDLEDREJECTION_ERROR"] = "unhandledrejectionError";
613
- EventTypes2["AJAX_ERROR"] = "ajaxError";
614
- EventTypes2["FETCH_ERROR"] = "fetchError";
615
- EventTypes2["WEBSOCKET_ERROR"] = "websocketError";
616
- EventTypes2["UNKNOWN_ERROR"] = "unknownError";
617
- EventTypes2["MESSAGE"] = "message";
618
- EventTypes2["FEEDBACK"] = "feedback";
619
- EventTypes2["VIEW"] = "view";
620
- EventTypes2["REACT"] = "react";
621
- EventTypes2["VUE"] = "vue";
622
- EventTypes2["ANGULAR"] = "angular";
623
- EventTypes2["MINIAPP_ERROR"] = "miniappError";
624
- EventTypes2["MINIAPP_UNHANDLEDREJECTION_ERROR"] = "miniappUnhandledrejectionError";
625
- EventTypes2["MINIAPP_PAGENOTFOUND_ERROR"] = "miniappPagenotfoundError";
626
- EventTypes2["MINIAPP_MEMORYWARNING_ERROR"] = "miniappMemorywarningError";
627
- return EventTypes2;
628
- })(EventTypes || {});
629
- // Annotate the CommonJS export names for ESM import in node:
630
- 0 && (module.exports = {
631
- Client,
632
- EventTypes,
633
- defineExtension,
634
- isEvent
635
- });