@pisell/core 1.0.8 → 1.0.10

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.
@@ -52,8 +52,6 @@ var LoggerManager = class {
52
52
  retentionDays;
53
53
  // 日志保留天数
54
54
  metadataFunction;
55
- status = "running";
56
- // 日志管理器状态
57
55
  /**
58
56
  * 构造函数
59
57
  * @param prefix 日志前缀
@@ -68,7 +66,6 @@ var LoggerManager = class {
68
66
  this.initDB();
69
67
  }
70
68
  init() {
71
- this.setStatus("running");
72
69
  this.initTimer();
73
70
  this.cleanupOldLogs();
74
71
  }
@@ -100,34 +97,19 @@ var LoggerManager = class {
100
97
  }
101
98
  }, this.checkInterval);
102
99
  }
103
- setStatus(status) {
104
- this.status = status;
105
- }
106
- stop() {
107
- this.setStatus("stop");
108
- if (this.timer) {
109
- clearInterval(this.timer);
110
- }
111
- }
112
100
  /**
113
101
  * 添加日志
114
102
  * @param log 日志项
115
103
  */
116
104
  addLog(log) {
117
- if (this.status === "stop") {
118
- return;
119
- }
120
- const { feishu, ...restLog } = log || {};
121
105
  const logItem = {
122
- ...restLog,
106
+ ...log,
123
107
  date: log.date || (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss"),
124
- metadata: JSON.stringify(log.metadata || {}),
125
- // 以时间戳生成logId
126
- logId: (0, import_dayjs.default)().valueOf()
108
+ metadata: JSON.stringify(log.metadata || "{}")
127
109
  };
128
110
  console.log("---- 行为日志", logItem);
129
111
  if (log.type === "error") {
130
- this.sendFeishuNotification({ ...logItem || {}, feishu });
112
+ this.sendFeishuNotification(logItem);
131
113
  }
132
114
  this.logBuffer.push(logItem);
133
115
  }
@@ -139,19 +121,14 @@ var LoggerManager = class {
139
121
  var _a;
140
122
  if (this.feishuConfig) {
141
123
  const _metadata = ((_a = this.metadataFunction) == null ? void 0 : _a.call(this)) || {};
142
- const content = [
143
- { key: "日志类型", value: log.type },
144
- { key: "日志时间", value: log.date || (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss") },
145
- { key: "日志来源", value: JSON.stringify({ ...this.metadata || {}, ..._metadata }) }
146
- ];
147
- if (log.feishu) {
148
- content.push({ key: "日志内容", value: JSON.stringify(log.feishu || {}) });
149
- } else {
150
- content.push({ key: "日志内容", value: JSON.stringify(log.metadata || {}) });
151
- }
152
124
  (0, import_feishu.sendWarningLog)({
153
125
  title: log.title,
154
- content,
126
+ content: [
127
+ { key: "日志类型", value: log.type },
128
+ { key: "日志时间", value: log.date || (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss") },
129
+ { key: "日志来源", value: JSON.stringify({ ...this.metadata || {}, ..._metadata }) },
130
+ { key: "日志内容", value: JSON.stringify(log.metadata) }
131
+ ],
155
132
  webhook: this.feishuConfig.webhook
156
133
  });
157
134
  console.log("-------- 发送飞书通知", log);
@@ -166,29 +143,6 @@ var LoggerManager = class {
166
143
  const fileName = `${this.prefix}_${_date}.log`;
167
144
  return fileName;
168
145
  }
169
- /**
170
- * 创建AWS日志文件名
171
- * @param isManual 是否手动上传
172
- * @returns 日志文件名
173
- */
174
- async createAWSFileName(isManual) {
175
- var _a, _b, _c, _d, _e;
176
- const _date = (0, import_dayjs.default)().format("YYYY-MM-DD");
177
- const _hour = (0, import_dayjs.default)().format("HH:mm");
178
- const shopId = (_b = (_a = JSON.parse(this.app.storage.getStorage("shopInfo") || "{}")) == null ? void 0 : _a.shop) == null ? void 0 : _b.id;
179
- let deviceId = "";
180
- if (!shopId) {
181
- const language = ((_d = (_c = this.app) == null ? void 0 : _c.locales) == null ? void 0 : _d.getLocale()) || "en";
182
- const deviceRes = await ((_e = this.app) == null ? void 0 : _e.getPlugin("device").getDeviceInfo({ language }));
183
- const device = (deviceRes == null ? void 0 : deviceRes.data) || null;
184
- deviceId = (device == null ? void 0 : device.number) || "";
185
- }
186
- let fileName = `logs/kds/${shopId || deviceId || "pisell"}/${_date}/${_hour}`;
187
- if (isManual) {
188
- fileName += "-manual";
189
- }
190
- return `${fileName}.json`;
191
- }
192
146
  /**
193
147
  * 创建日志文件
194
148
  * @param _fileName 文件名
@@ -210,48 +164,26 @@ var LoggerManager = class {
210
164
  * 存储日志到持久化存储
211
165
  */
212
166
  async storeLog() {
213
- var _a;
214
167
  if (this.logBuffer.length === 0 || !this.db) {
215
168
  return;
216
169
  }
170
+ const fileName = this.createFileName();
217
171
  try {
218
- const fileName = await this.createAWSFileName();
219
- console.log("-------- 存储日志到AWS 开始", fileName);
220
- const buffer = (_a = this.logBuffer) == null ? void 0 : _a.map((item) => {
221
- item.metadata = JSON.parse(item.metadata || "{}");
222
- return item;
223
- });
224
- const logs = JSON.stringify(buffer, null, 2);
225
- await this.app.aws.upload({ Bucket: "", Key: fileName, Body: logs });
226
- console.log("-------- 存储日志到AWS 成功");
227
- this.logBuffer = [];
228
- } catch (error) {
229
- console.error("存储日志上传AWS失败:", error);
230
- try {
231
- await this.storeLogToIndexDB();
232
- } catch (indexDBError) {
233
- console.error("存储日志到IndexDB也失败:", indexDBError);
234
- }
235
- }
236
- }
237
- async storeLogToIndexDB() {
238
- var _a, _b, _c;
239
- try {
240
- const fileName = this.createFileName();
241
- console.log("storeLog", fileName);
242
- let logFile = await ((_a = this.db) == null ? void 0 : _a.get("logs", fileName));
172
+ let logFile = await this.db.get("logs", fileName);
243
173
  if (!logFile) {
244
174
  logFile = this.createFile(fileName);
245
- await ((_b = this.db) == null ? void 0 : _b.add("logs", logFile));
175
+ await this.db.add("logs", logFile);
246
176
  }
247
177
  logFile.fileContent.logs = [...logFile.fileContent.logs, ...this.logBuffer];
248
- await ((_c = this.db) == null ? void 0 : _c.update("logs", logFile));
249
- console.log("-------- 存储日志到IndexDB", { fileName, logFile });
250
- this.logBuffer = [];
178
+ await this.db.update("logs", logFile);
179
+ console.log("-------- 存储日志", {
180
+ fileName,
181
+ logFile
182
+ });
251
183
  } catch (error) {
252
- console.log("-------- 存储日志到IndexDB 失败", error);
253
- throw error;
184
+ console.error("存储日志到IndexDB失败:", error);
254
185
  }
186
+ this.logBuffer = [];
255
187
  }
256
188
  /**
257
189
  * 清理旧日志,只保留最近指定天数的日志
@@ -11,7 +11,7 @@ export interface SocketHistoryItem {
11
11
  /** 消息方向(发送/接收) */
12
12
  direction: 'in' | 'out';
13
13
  /** 消息内容 */
14
- message: SocketMessage;
14
+ message: SocketMessage | Partial<SocketMessage>;
15
15
  /** 消息大小(字节) */
16
16
  size?: number;
17
17
  }
@@ -1,4 +1,4 @@
1
- import { ReconnectOptions } from "./types";
1
+ import { ReconnectOptions } from './types';
2
2
  /**
3
3
  * Socket重连管理器
4
4
  * 处理断线重连逻辑
@@ -143,7 +143,10 @@ var ReconnectManager = class {
143
143
  const { delay, delayMax, jitter } = this.options;
144
144
  let calculatedDelay = delay;
145
145
  if (this.attempts > 0) {
146
- calculatedDelay = Math.min(delayMax || Infinity, delay * Math.pow(1.5, this.attempts - 1));
146
+ calculatedDelay = Math.min(
147
+ delayMax || Infinity,
148
+ delay * Math.pow(1.5, this.attempts - 1)
149
+ );
147
150
  }
148
151
  if (jitter) {
149
152
  calculatedDelay = Math.random() * calculatedDelay;
@@ -25,9 +25,8 @@ export declare class Socket {
25
25
  connect(): Promise<void>;
26
26
  /**
27
27
  * 关闭WebSocket连接
28
- * @param isManual 是否手动关闭
29
28
  */
30
- disconnect(isManual?: boolean): void;
29
+ disconnect(): void;
31
30
  /**
32
31
  * 发送消息到服务器
33
32
  * @param event 事件名称
@@ -28,7 +28,6 @@ var import_events = require("./events");
28
28
  var import_heartbeat = require("./heartbeat");
29
29
  var import_reconnect = require("./reconnect");
30
30
  var import_monitor = require("./monitor");
31
- var import_app = require("../app");
32
31
  var Socket = class {
33
32
  ws = null;
34
33
  url;
@@ -53,26 +52,14 @@ var Socket = class {
53
52
  ...options
54
53
  };
55
54
  if (this.options.autoConnect) {
56
- this.connect().catch((error) => {
57
- console.warn("Socket connection failed:", error);
58
- });
55
+ this.connect();
59
56
  }
60
57
  }
61
58
  /**
62
59
  * 建立WebSocket连接
63
60
  */
64
61
  async connect() {
65
- const app = (0, import_app.getApp)();
66
- const isConnected = this.isConnected();
67
- if (isConnected || this.status === import_types.SocketStatus.CONNECTING) {
68
- app.logger.addLog({
69
- type: "info",
70
- title: "socket已连接或连接中",
71
- metadata: {
72
- isConnected,
73
- status: this.status
74
- }
75
- });
62
+ if (this.isConnected() || this.status === import_types.SocketStatus.CONNECTING) {
76
63
  return;
77
64
  }
78
65
  this.setStatus(import_types.SocketStatus.CONNECTING);
@@ -107,9 +94,8 @@ var Socket = class {
107
94
  }
108
95
  /**
109
96
  * 关闭WebSocket连接
110
- * @param isManual 是否手动关闭
111
97
  */
112
- disconnect(isManual = false) {
98
+ disconnect() {
113
99
  if (!this.ws || this.status === import_types.SocketStatus.CLOSED || this.status === import_types.SocketStatus.CLOSING) {
114
100
  return;
115
101
  }
@@ -127,7 +113,7 @@ var Socket = class {
127
113
  }
128
114
  this.setStatus(import_types.SocketStatus.CLOSED);
129
115
  this.ws = null;
130
- this.emit(import_events.SocketEvents.DISCONNECT, { isManual });
116
+ this.emit(import_events.SocketEvents.DISCONNECT);
131
117
  }
132
118
  /**
133
119
  * 发送消息到服务器
@@ -336,7 +322,7 @@ var Socket = class {
336
322
  attempts: this.options.reconnectionAttempts,
337
323
  delay: this.options.reconnectionDelay,
338
324
  delayMax: this.options.reconnectionDelayMax,
339
- jitter: false
325
+ jitter: true
340
326
  };
341
327
  this.reconnectManager = new import_reconnect.ReconnectManager(
342
328
  reconnectOptions,
@@ -410,7 +396,7 @@ var Socket = class {
410
396
  * 释放资源
411
397
  */
412
398
  destroy() {
413
- this.disconnect(true);
399
+ this.disconnect();
414
400
  if (this.monitor) {
415
401
  this.monitor.destroy();
416
402
  this.monitor = null;
@@ -45,6 +45,7 @@ export interface SocketMessage<T = any> {
45
45
  data?: T;
46
46
  /** 消息ID */
47
47
  id?: string;
48
+ event?: any;
48
49
  }
49
50
  /**
50
51
  * 心跳配置选项
@@ -10,7 +10,6 @@ export declare class TasksManager {
10
10
  tasks: TasksModule;
11
11
  };
12
12
  watchTaskCallback: (taskModule: TasksModule) => void;
13
- private timerIds;
14
13
  constructor(app: App);
15
14
  static getInstance(app?: App): TasksManager;
16
15
  addTaskFunction<T>(name: string, fun: T): void;
@@ -32,11 +31,6 @@ export declare class TasksManager {
32
31
  * @Date: 2024-09-26 13:53
33
32
  */
34
33
  private runTask;
35
- /**
36
- * @title: 清除任务定时器
37
- * @param {NodeJS.Timeout} timerId
38
- */
39
- private clearTaskTimer;
40
34
  /**
41
35
  * @title: 启动轮询
42
36
  * @description: 根据轮询间隔定期执行任务
@@ -44,7 +44,6 @@ var TasksManager = class _TasksManager {
44
44
  useTasks = import_useTasks.default;
45
45
  watchTaskCallback = () => {
46
46
  };
47
- timerIds = [];
48
47
  constructor(app) {
49
48
  if (!app) {
50
49
  throw new Error("app is required");
@@ -53,7 +52,6 @@ var TasksManager = class _TasksManager {
53
52
  this.taskFunctions = /* @__PURE__ */ new Map();
54
53
  this.tasks = {};
55
54
  this.db = app.dbManager;
56
- this.timerIds = [];
57
55
  }
58
56
  // 单例模式
59
57
  static getInstance(app) {
@@ -150,39 +148,16 @@ var TasksManager = class _TasksManager {
150
148
  }
151
149
  } catch (error) {
152
150
  this.app.logger.addLog({
153
- type: "info",
151
+ type: "error",
154
152
  title: `任务执行失败-${task.id}`,
155
153
  metadata: { error, taskPayload: task == null ? void 0 : task.payload }
156
154
  });
155
+ console.log("任务执行失败", error);
157
156
  actionRes = { status: "failure" };
158
157
  }
159
158
  console.log("Tasks--->", `任务执行成功: ${task.id}`);
160
159
  return actionRes;
161
160
  };
162
- /**
163
- * @title: 清除任务定时器
164
- * @param {NodeJS.Timeout} timerId
165
- */
166
- clearTaskTimer = (params) => {
167
- const { timerId, taskId } = params;
168
- const _timerIds = [];
169
- const needClearTimerIds = [];
170
- this.timerIds.forEach((id) => {
171
- const taskIdRult = taskId ? (id == null ? void 0 : id.taskId) === taskId : true;
172
- const timerIdRult = timerId ? (id == null ? void 0 : id.timerId) === timerId : true;
173
- if (taskIdRult && timerIdRult) {
174
- needClearTimerIds.push(id);
175
- } else {
176
- _timerIds.push(id);
177
- }
178
- });
179
- if (needClearTimerIds.length) {
180
- for (let id of needClearTimerIds) {
181
- clearTimeout(id.timerId);
182
- }
183
- }
184
- this.timerIds = [..._timerIds || []];
185
- };
186
161
  /**
187
162
  * @title: 启动轮询
188
163
  * @description: 根据轮询间隔定期执行任务
@@ -215,11 +190,10 @@ var TasksManager = class _TasksManager {
215
190
  }
216
191
  this.startPolling(newTask);
217
192
  } catch (error) {
218
- this.clearTaskTimer({ timerId });
193
+ clearTimeout(timerId);
219
194
  console.error("轮询任务异常", error);
220
195
  }
221
196
  }, task.polling.interval);
222
- this.timerIds.push({ taskId: task.id, timerId });
223
197
  };
224
198
  /**
225
199
  * @title: 创建任务数据
@@ -346,7 +320,7 @@ var TasksManager = class _TasksManager {
346
320
  this.tasks[module2][queueId].tasks = (_d = (_c = (_b = (_a = this.tasks) == null ? void 0 : _a[module2]) == null ? void 0 : _b[queueId]) == null ? void 0 : _c.tasks) == null ? void 0 : _d.filter((task) => {
347
321
  var _a2;
348
322
  if ((_a2 = task.pollingResult) == null ? void 0 : _a2.timerId) {
349
- this.clearTaskTimer({ timerId: task.pollingResult.timerId });
323
+ clearTimeout(task.pollingResult.timerId);
350
324
  }
351
325
  return task.id !== taskId;
352
326
  });
@@ -439,8 +413,11 @@ var TasksManager = class _TasksManager {
439
413
  this.tasks = newState;
440
414
  }
441
415
  clearAllTaskTimer(tasks) {
416
+ var _a;
442
417
  for (let task of tasks || []) {
443
- this.clearTaskTimer({ taskId: task.id });
418
+ if ((_a = task.pollingResult) == null ? void 0 : _a.timerId) {
419
+ clearTimeout(task.pollingResult.timerId);
420
+ }
444
421
  }
445
422
  }
446
423
  // 清空任务
@@ -455,12 +432,6 @@ var TasksManager = class _TasksManager {
455
432
  clearAllTasks() {
456
433
  this.tasks = {};
457
434
  this.saveTaskQueueToLocal(this.tasks);
458
- if (this.timerIds.length) {
459
- for (let timerId of this.timerIds) {
460
- clearTimeout(timerId);
461
- }
462
- this.timerIds = [];
463
- }
464
435
  console.log("Tasks--->", "清空全部任务");
465
436
  }
466
437
  watchTask(callback) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pisell/core",
3
- "version": "1.0.8",
3
+ "version": "1.0.10",
4
4
  "sideEffects": false,
5
5
  "main": "./lib/index.js",
6
6
  "module": "./es/index.js",
@@ -27,8 +27,7 @@
27
27
  "dva-core": "^2.0.4",
28
28
  "js-md5": "^0.8.3",
29
29
  "axios": "^1.7.2",
30
- "@aws-sdk/client-s3": "^3.456.0",
31
- "@pisell/utils": "1.0.42"
30
+ "@pisell/utils": "1.0.52"
32
31
  },
33
32
  "files": [
34
33
  "es",
package/es/aws/index.d.ts DELETED
@@ -1,16 +0,0 @@
1
- import { S3ClientConfig, PutObjectCommandInput } from '@aws-sdk/client-s3';
2
- import App from '../app';
3
- export interface AWSOptions extends S3ClientConfig {
4
- s3Config: S3ClientConfig;
5
- bucketName?: string;
6
- }
7
- export interface UploadParams extends PutObjectCommandInput {
8
- }
9
- declare class AWS {
10
- private s3Client?;
11
- private app;
12
- private config?;
13
- constructor(app: App, options?: AWSOptions);
14
- upload(params: UploadParams): Promise<any>;
15
- }
16
- export default AWS;
package/es/aws/index.js DELETED
@@ -1,76 +0,0 @@
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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
6
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
7
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8
- 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); } }
9
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
10
- 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; }
11
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
12
- 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); }
13
- import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
14
- ;
15
- var defaultUploadParams = {
16
- Bucket: '',
17
- Key: '',
18
- ContentType: 'application/json',
19
- ContentDisposition: 'inline',
20
- ACL: 'public-read' // 设置ACL权限为公共读取
21
- };
22
- var AWS = /*#__PURE__*/function () {
23
- function AWS(app, options) {
24
- _classCallCheck(this, AWS);
25
- _defineProperty(this, "s3Client", void 0);
26
- _defineProperty(this, "app", void 0);
27
- _defineProperty(this, "config", void 0);
28
- this.app = app;
29
- if (options) {
30
- // 配置S3客户端,支持自定义上传地址和CORS
31
- var clientConfig = _objectSpread({}, options.s3Config);
32
- this.s3Client = new S3Client(clientConfig);
33
- this.config = options;
34
- }
35
- }
36
- _createClass(AWS, [{
37
- key: "upload",
38
- value: function () {
39
- var _upload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(params) {
40
- var _this$config, _this$s3Client, _params, command, response;
41
- return _regeneratorRuntime().wrap(function _callee$(_context) {
42
- while (1) switch (_context.prev = _context.next) {
43
- case 0:
44
- _context.prev = 0;
45
- // Key: "logs/kds/9/2025-01-01/00:01.json",
46
- _params = _objectSpread(_objectSpread(_objectSpread({}, defaultUploadParams), params), {}, {
47
- Bucket: params.Bucket || ((_this$config = this.config) === null || _this$config === void 0 ? void 0 : _this$config.bucketName)
48
- });
49
- console.log("\u4E0A\u4F20\u53C2\u6570", _params);
50
- command = new PutObjectCommand(_params);
51
- _context.next = 6;
52
- return (_this$s3Client = this.s3Client) === null || _this$s3Client === void 0 ? void 0 : _this$s3Client.send(command);
53
- case 6:
54
- response = _context.sent;
55
- console.log("\u4E0A\u4F20\u6210\u529F");
56
- return _context.abrupt("return", response);
57
- case 11:
58
- _context.prev = 11;
59
- _context.t0 = _context["catch"](0);
60
- console.error("\u4E0A\u4F20\u5931\u8D25", _context.t0);
61
- throw _context.t0;
62
- case 15:
63
- case "end":
64
- return _context.stop();
65
- }
66
- }, _callee, this, [[0, 11]]);
67
- }));
68
- function upload(_x) {
69
- return _upload.apply(this, arguments);
70
- }
71
- return upload;
72
- }()
73
- }]);
74
- return AWS;
75
- }();
76
- export default AWS;
package/es/cmd/const.d.ts DELETED
@@ -1,11 +0,0 @@
1
- export declare enum CMDCoreEnum {
2
- CMD_CONNECT,
3
- CMD_DISCONNECT,
4
- CMD_RECONNECT,
5
- CMD_MESSAGE,
6
- CMD_ERROR
7
- }
8
- declare const _default: {
9
- CMDCoreEnum: typeof CMDCoreEnum;
10
- };
11
- export default _default;
package/es/cmd/const.js DELETED
@@ -1,13 +0,0 @@
1
- var prefix = 'cmd'; // 前缀
2
- // 定义枚举
3
- export var CMDCoreEnum = /*#__PURE__*/function (CMDCoreEnum) {
4
- CMDCoreEnum["CMD_CONNECT"] = "cmd.connect";
5
- CMDCoreEnum["CMD_DISCONNECT"] = "cmd.disconnect";
6
- CMDCoreEnum["CMD_RECONNECT"] = "cmd.reconnect";
7
- CMDCoreEnum["CMD_MESSAGE"] = "cmd.message";
8
- CMDCoreEnum["CMD_ERROR"] = "cmd.error";
9
- return CMDCoreEnum;
10
- }({});
11
- export default {
12
- CMDCoreEnum: CMDCoreEnum
13
- };
package/es/cmd/index.d.ts DELETED
@@ -1,13 +0,0 @@
1
- import App from "../app";
2
- import { CMDCoreEnum } from "./const";
3
- export interface CMDOptions {
4
- socketUrl?: string;
5
- }
6
- declare class CMD {
7
- private app;
8
- private options?;
9
- constructor(app: App, options?: CMDOptions);
10
- init(): void;
11
- }
12
- export { CMDCoreEnum };
13
- export default CMD;