@lightsoft/js-sdk 1.2.2 → 1.2.4

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.d.ts CHANGED
@@ -259,7 +259,7 @@ declare class Tour {
259
259
  close(): void;
260
260
  }
261
261
 
262
- type WebSocketState = 'CONNECTING' | 'OPEN' | 'CLOSING' | 'CLOSED';
262
+ type WebSocketState = "CONNECTING" | "OPEN" | "CLOSING" | "CLOSED";
263
263
  interface WebSocketConfig {
264
264
  heartbeat?: boolean;
265
265
  heartbeatTime?: number;
@@ -287,6 +287,69 @@ declare function addURLParams(params: Record<string, any>, url?: string): TAddUR
287
287
  declare function getURLParams(url?: string): Record<string, any>;
288
288
  declare function deleteURLParams(keys: string[], url?: string): URL;
289
289
 
290
+ interface StreamRequestConfig extends RequestInit {
291
+ parseResponse?: boolean;
292
+ }
293
+ declare class StreamRequest {
294
+ private url;
295
+ private options;
296
+ private beforeCallback?;
297
+ private messageCallback?;
298
+ private errorCallback?;
299
+ private parseResponse?;
300
+ private beforeResponse?;
301
+ constructor(url: string, config?: StreamRequestConfig);
302
+ private onBefore;
303
+ private send;
304
+ onBeforeResponse(beforeResponse: () => void): void;
305
+ private onMessage;
306
+ private onError;
307
+ }
308
+
309
+ interface AudioRecorderOptions {
310
+ media: MediaStreamConstraints;
311
+ mediaRecorder?: MediaRecorderOptions;
312
+ maxTime?: number;
313
+ }
314
+ interface TimerOptions {
315
+ next?: () => void;
316
+ end?: () => void;
317
+ }
318
+ interface AudioInfo {
319
+ sampleRate: number;
320
+ channels: number;
321
+ format: string | null;
322
+ bitDepth: number;
323
+ }
324
+ declare class AudioRecorder {
325
+ private options;
326
+ private stream;
327
+ private mediaRecorder;
328
+ private audioChunks;
329
+ private audioInfo;
330
+ private timer;
331
+ private timerCount;
332
+ private stopCallback;
333
+ private timerCallback;
334
+ private timerEndCallback;
335
+ constructor(options: AudioRecorderOptions);
336
+ start(): Promise<void>;
337
+ stop(): void;
338
+ reset(): void;
339
+ onStop(callback: (audioChunks: Blob[]) => void): void;
340
+ startTimer(options?: TimerOptions): void;
341
+ clearTimer(): void;
342
+ onTimer(callback: (count: number) => void): void;
343
+ onTimerEnd(callback: () => void): void;
344
+ getAudioBlob(): Blob | null;
345
+ getAudioUrl(): string;
346
+ getAudioBase64(blob: Blob): Promise<string>;
347
+ getAudioInfo(): Promise<unknown>;
348
+ getWavBitDepth(blob: Blob): Promise<number>;
349
+ getExtension(mimeType: string): string;
350
+ upload(url: string, options?: RequestInit): Promise<any>;
351
+ }
352
+
290
353
  /**
291
354
  * 匹配中文字母数字
292
355
  */
@@ -312,5 +375,5 @@ declare const email: RegExp;
312
375
  */
313
376
  declare const url: RegExp;
314
377
 
315
- export { HAS_FEILD, InputLegalityValidate, InputLengthValidate, LENGTH_LIMIT, LOGIN_TYPE, Mask, RecordType, Request, RequestChain, Tour, addURLParams, countUp, createWebSocket, dataHandler, debounce, deepMerge, deleteURLParams, download, email, findTreeDataNode, findTreeDataNodeName, getState, getURLParams, hasRepeatArray, idCard, ip, isMobileDevice, isNull, objectArrayToString, phone, throttle, uniqueByProperty, url, useClose, useCountDown, useDownload, useOnMessage, useSendMessage, zhLetterNumber };
316
- export type { ISectoralTable, Tag, typeIsNull };
378
+ export { AudioRecorder, HAS_FEILD, InputLegalityValidate, InputLengthValidate, LENGTH_LIMIT, LOGIN_TYPE, Mask, RecordType, Request, RequestChain, StreamRequest, Tour, addURLParams, countUp, createWebSocket, dataHandler, debounce, deepMerge, deleteURLParams, download, email, findTreeDataNode, findTreeDataNodeName, getState, getURLParams, hasRepeatArray, idCard, ip, isMobileDevice, isNull, objectArrayToString, phone, throttle, uniqueByProperty, url, useClose, useCountDown, useDownload, useOnMessage, useSendMessage, zhLetterNumber };
379
+ export type { AudioInfo, AudioRecorderOptions, ISectoralTable, Tag, typeIsNull };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as __assign, a as __awaiter, b as __generator } from './ws-DGDUMiR9.js';
2
- export { c as createWebSocket, g as getState, e as useClose, d as useOnMessage, u as useSendMessage } from './ws-DGDUMiR9.js';
1
+ import { _ as __assign, a as __awaiter, b as __generator, c as __rest } from './ws-Dvvmk4pM.js';
2
+ export { d as createWebSocket, g as getState, f as useClose, e as useOnMessage, u as useSendMessage } from './ws-Dvvmk4pM.js';
3
3
 
4
4
  var READY_STATE;
5
5
  (function (READY_STATE) {
@@ -2866,9 +2866,8 @@ function hasRepeatArray(arr, keys) {
2866
2866
  var map = new Map();
2867
2867
  var _loop_1 = function (item) {
2868
2868
  var val = (keys === null || keys === void 0 ? void 0 : keys.map(function (key) { return item[key]; }).join(',')) || item;
2869
- if (map.has(val)) {
2869
+ if (map.has(val))
2870
2870
  return { value: [true, val.split(',')] };
2871
- }
2872
2871
  map.set(val, item);
2873
2872
  };
2874
2873
  for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) {
@@ -2905,6 +2904,312 @@ function deleteURLParams(keys, url) {
2905
2904
  return newUrl;
2906
2905
  }
2907
2906
 
2907
+ var StreamRequest = /** @class */ (function () {
2908
+ function StreamRequest(url, config) {
2909
+ var _a = config, parseResponse = _a.parseResponse, options = __rest(_a, ["parseResponse"]);
2910
+ this.url = url;
2911
+ this.options = options || {};
2912
+ this.parseResponse = parseResponse;
2913
+ }
2914
+ StreamRequest.prototype.onBefore = function (callback) {
2915
+ this.beforeCallback = callback;
2916
+ };
2917
+ StreamRequest.prototype.send = function (params) {
2918
+ return __awaiter(this, void 0, void 0, function () {
2919
+ var _a, url, options, parseResponse, res, reader, _b, done, value, data, newData, error_1;
2920
+ var _this = this;
2921
+ var _c, _d;
2922
+ return __generator(this, function (_e) {
2923
+ switch (_e.label) {
2924
+ case 0:
2925
+ _a = this, url = _a.url, options = _a.options, parseResponse = _a.parseResponse;
2926
+ _e.label = 1;
2927
+ case 1:
2928
+ _e.trys.push([1, 6, , 7]);
2929
+ if (typeof this.beforeCallback === 'function')
2930
+ this.beforeCallback(params);
2931
+ return [4 /*yield*/, window.fetch(url, __assign(__assign({}, options), { body: JSON.stringify(params) }))];
2932
+ case 2:
2933
+ res = _e.sent();
2934
+ reader = (_c = res.body) === null || _c === void 0 ? void 0 : _c.getReader();
2935
+ if (!reader)
2936
+ return [2 /*return*/];
2937
+ _e.label = 3;
2938
+ case 3:
2939
+ return [4 /*yield*/, reader.read()];
2940
+ case 4:
2941
+ _b = _e.sent(), done = _b.done, value = _b.value;
2942
+ if (done)
2943
+ return [3 /*break*/, 5];
2944
+ data = new TextDecoder().decode(value);
2945
+ newData = data.split('\n');
2946
+ if (typeof this.beforeResponse === 'function') {
2947
+ this.beforeResponse(data, this.messageCallback);
2948
+ }
2949
+ else {
2950
+ newData.forEach(function (message) {
2951
+ var _a;
2952
+ if (message.trim()) {
2953
+ (_a = _this.messageCallback) === null || _a === void 0 ? void 0 : _a.call(_this, parseResponse ? JSON.parse(message || '{}') : message);
2954
+ }
2955
+ });
2956
+ }
2957
+ return [3 /*break*/, 3];
2958
+ case 5: return [3 /*break*/, 7];
2959
+ case 6:
2960
+ error_1 = _e.sent();
2961
+ (_d = this.errorCallback) === null || _d === void 0 ? void 0 : _d.call(this, error_1);
2962
+ return [3 /*break*/, 7];
2963
+ case 7: return [2 /*return*/];
2964
+ }
2965
+ });
2966
+ });
2967
+ };
2968
+ StreamRequest.prototype.onBeforeResponse = function (beforeResponse) {
2969
+ this.beforeResponse = beforeResponse;
2970
+ };
2971
+ StreamRequest.prototype.onMessage = function (callback) {
2972
+ this.messageCallback = callback;
2973
+ };
2974
+ StreamRequest.prototype.onError = function (callback) {
2975
+ this.errorCallback = callback;
2976
+ };
2977
+ return StreamRequest;
2978
+ }());
2979
+
2980
+ var AudioRecorder = /** @class */ (function () {
2981
+ function AudioRecorder(options) {
2982
+ this.options = {
2983
+ media: {
2984
+ audio: {
2985
+ channelCount: { ideal: 2 },
2986
+ sampleRate: { ideal: 44100 },
2987
+ echoCancellation: true,
2988
+ }
2989
+ },
2990
+ mediaRecorder: {
2991
+ mimeType: 'audio/mp4;codecs=mp4a.40.2',
2992
+ },
2993
+ maxTime: 0,
2994
+ };
2995
+ this.stream = null;
2996
+ this.mediaRecorder = null;
2997
+ this.audioChunks = [];
2998
+ this.audioInfo = {
2999
+ sampleRate: 0,
3000
+ channels: 0,
3001
+ format: null,
3002
+ bitDepth: 0,
3003
+ };
3004
+ this.timer = null;
3005
+ this.timerCount = 0;
3006
+ this.stopCallback = null;
3007
+ this.timerCallback = null;
3008
+ this.timerEndCallback = null;
3009
+ this.audioChunks = [];
3010
+ this.options = options;
3011
+ }
3012
+ // 开始录音
3013
+ AudioRecorder.prototype.start = function () {
3014
+ return __awaiter(this, void 0, void 0, function () {
3015
+ var _a, media, mediaRecorder, _b, maxTime, _c, error_1;
3016
+ var _this = this;
3017
+ return __generator(this, function (_d) {
3018
+ switch (_d.label) {
3019
+ case 0:
3020
+ _d.trys.push([0, 2, , 3]);
3021
+ _a = this.options, media = _a.media, mediaRecorder = _a.mediaRecorder, _b = _a.maxTime, maxTime = _b === void 0 ? 0 : _b;
3022
+ _c = this;
3023
+ return [4 /*yield*/, navigator.mediaDevices.getUserMedia({ audio: media.audio })];
3024
+ case 1:
3025
+ _c.stream = _d.sent();
3026
+ this.mediaRecorder = new MediaRecorder(this.stream, mediaRecorder);
3027
+ this.mediaRecorder.ondataavailable = function (event) {
3028
+ _this.audioInfo.format = event.data.type;
3029
+ _this.audioChunks.push(event.data);
3030
+ };
3031
+ this.mediaRecorder.onstop = function () {
3032
+ var _a;
3033
+ (_a = _this.stopCallback) === null || _a === void 0 ? void 0 : _a.call(_this, _this.audioChunks);
3034
+ _this.reset();
3035
+ };
3036
+ this.mediaRecorder.start();
3037
+ if (maxTime > 0) {
3038
+ this.startTimer({
3039
+ end: function () {
3040
+ _this.stop();
3041
+ }
3042
+ });
3043
+ }
3044
+ return [3 /*break*/, 3];
3045
+ case 2:
3046
+ error_1 = _d.sent();
3047
+ throw new Error(error_1);
3048
+ case 3: return [2 /*return*/];
3049
+ }
3050
+ });
3051
+ });
3052
+ };
3053
+ // 停止录音
3054
+ AudioRecorder.prototype.stop = function () {
3055
+ if (this.mediaRecorder) {
3056
+ this.audioChunks = [];
3057
+ this.mediaRecorder.stop();
3058
+ }
3059
+ };
3060
+ AudioRecorder.prototype.reset = function () {
3061
+ var _a, _b;
3062
+ this.audioChunks = [];
3063
+ (_b = (_a = this.stream) === null || _a === void 0 ? void 0 : _a.getTracks()) === null || _b === void 0 ? void 0 : _b.forEach(function (track) { return track.stop(); });
3064
+ };
3065
+ AudioRecorder.prototype.onStop = function (callback) {
3066
+ this.stopCallback = callback;
3067
+ };
3068
+ AudioRecorder.prototype.startTimer = function (options) {
3069
+ var _this = this;
3070
+ var _a = options || {}, next = _a.next, end = _a.end;
3071
+ this.timer = setInterval(function () {
3072
+ var _a, _b;
3073
+ next === null || next === void 0 ? void 0 : next();
3074
+ (_a = _this.timerCallback) === null || _a === void 0 ? void 0 : _a.call(_this, _this.timerCount);
3075
+ console.log('this.timerCount2: ', _this.timerCount);
3076
+ if (_this.timerCount === _this.options.maxTime) {
3077
+ _this.clearTimer();
3078
+ end === null || end === void 0 ? void 0 : end();
3079
+ (_b = _this.timerEndCallback) === null || _b === void 0 ? void 0 : _b.call(_this);
3080
+ }
3081
+ _this.timerCount++;
3082
+ }, 1000);
3083
+ };
3084
+ // 清除定时器
3085
+ AudioRecorder.prototype.clearTimer = function () {
3086
+ if (this.timer)
3087
+ clearInterval(this.timer);
3088
+ this.timer = null;
3089
+ this.timerCount = 0;
3090
+ };
3091
+ AudioRecorder.prototype.onTimer = function (callback) {
3092
+ this.timerCallback = callback;
3093
+ };
3094
+ AudioRecorder.prototype.onTimerEnd = function (callback) {
3095
+ this.timerEndCallback = callback;
3096
+ };
3097
+ AudioRecorder.prototype.getAudioBlob = function () {
3098
+ if (!this.mediaRecorder)
3099
+ return null;
3100
+ var type = this.getExtension(this.mediaRecorder.mimeType);
3101
+ return new Blob(this.audioChunks, { type: "audio/".concat(type) });
3102
+ };
3103
+ AudioRecorder.prototype.getAudioUrl = function () {
3104
+ var blob = this.getAudioBlob();
3105
+ if (!blob)
3106
+ return '';
3107
+ return URL.createObjectURL(blob);
3108
+ };
3109
+ AudioRecorder.prototype.getAudioBase64 = function (blob) {
3110
+ return new Promise(function (resolve, reject) {
3111
+ var reader = new FileReader();
3112
+ reader.onerror = reject;
3113
+ reader.onload = function () { return resolve(reader.result); };
3114
+ reader.readAsDataURL(blob);
3115
+ });
3116
+ };
3117
+ AudioRecorder.prototype.getAudioInfo = function () {
3118
+ var _this = this;
3119
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
3120
+ var audioContext, source, analyser, sampleRate, channels, bitDepth, error_2;
3121
+ var _a;
3122
+ return __generator(this, function (_b) {
3123
+ switch (_b.label) {
3124
+ case 0:
3125
+ _b.trys.push([0, 2, , 3]);
3126
+ audioContext = new (window.AudioContext || window.webkitAudioContext)();
3127
+ source = audioContext.createMediaStreamSource(this.stream);
3128
+ analyser = audioContext.createAnalyser();
3129
+ source.connect(analyser);
3130
+ sampleRate = audioContext.sampleRate;
3131
+ channels = ((_a = this.stream) === null || _a === void 0 ? void 0 : _a.getAudioTracks()[0].getSettings().channelCount) || 0;
3132
+ return [4 /*yield*/, this.getWavBitDepth(this.getAudioBlob())];
3133
+ case 1:
3134
+ bitDepth = _b.sent();
3135
+ resolve(__assign({ sampleRate: sampleRate, channels: channels, bitDepth: bitDepth }, this.audioInfo));
3136
+ return [3 /*break*/, 3];
3137
+ case 2:
3138
+ error_2 = _b.sent();
3139
+ reject(error_2);
3140
+ return [3 /*break*/, 3];
3141
+ case 3: return [2 /*return*/];
3142
+ }
3143
+ });
3144
+ }); });
3145
+ };
3146
+ AudioRecorder.prototype.getWavBitDepth = function (blob) {
3147
+ return new Promise(function (resolve, reject) {
3148
+ var reader = new FileReader();
3149
+ reader.onload = function (event) {
3150
+ var _a;
3151
+ var arrayBuffer = (_a = event.target) === null || _a === void 0 ? void 0 : _a.result;
3152
+ if (!arrayBuffer) {
3153
+ reject();
3154
+ throw new Error('未能读取 Blob 数据');
3155
+ }
3156
+ var data = new DataView(arrayBuffer);
3157
+ // 检查 "fmt " 区域,WAV文件的音频格式信息通常在此
3158
+ var fmtChunkOffset = 20; // "fmt " chunk 在 WAV 文件头的位置
3159
+ var bitDepth = data.getUint16(fmtChunkOffset + 14, true); // 16位表示小端存储
3160
+ resolve(bitDepth);
3161
+ };
3162
+ reader.readAsArrayBuffer(blob);
3163
+ });
3164
+ };
3165
+ AudioRecorder.prototype.getExtension = function (mimeType) {
3166
+ var mimeToExt = {
3167
+ 'audio/webm': 'webm',
3168
+ 'audio/webm;codecs=opus': 'webm',
3169
+ 'audio/ogg': 'ogg',
3170
+ 'audio/ogg;codecs=opus': 'ogg',
3171
+ 'audio/mp4': 'mp4',
3172
+ 'audio/mpeg': 'mp3',
3173
+ 'audio/wav': 'wav',
3174
+ };
3175
+ if (mimeToExt[mimeType])
3176
+ return mimeToExt[mimeType];
3177
+ var mainType = mimeType.split(';')[0];
3178
+ return mimeToExt[mainType] || 'audio';
3179
+ };
3180
+ // 上传音频到服务器
3181
+ AudioRecorder.prototype.upload = function (url, options) {
3182
+ return __awaiter(this, void 0, void 0, function () {
3183
+ var audioBlob, formData, response, data, error_3;
3184
+ return __generator(this, function (_a) {
3185
+ switch (_a.label) {
3186
+ case 0:
3187
+ audioBlob = this.getAudioBlob();
3188
+ if (!audioBlob)
3189
+ return [2 /*return*/, null];
3190
+ formData = new FormData();
3191
+ formData.append('audio', audioBlob, 'recording.mp4');
3192
+ _a.label = 1;
3193
+ case 1:
3194
+ _a.trys.push([1, 4, , 5]);
3195
+ return [4 /*yield*/, fetch(url, options)];
3196
+ case 2:
3197
+ response = _a.sent();
3198
+ return [4 /*yield*/, response.json()];
3199
+ case 3:
3200
+ data = _a.sent();
3201
+ return [2 /*return*/, data];
3202
+ case 4:
3203
+ error_3 = _a.sent();
3204
+ throw new Error(error_3);
3205
+ case 5: return [2 /*return*/];
3206
+ }
3207
+ });
3208
+ });
3209
+ };
3210
+ return AudioRecorder;
3211
+ }());
3212
+
2908
3213
  /**
2909
3214
  * 匹配中文字母数字
2910
3215
  */
@@ -2930,4 +3235,4 @@ var email = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$
2930
3235
  */
2931
3236
  var url = /^https?:\/\/[^\s/$.?#].[^\s]*$/;
2932
3237
 
2933
- export { HAS_FEILD, InputLegalityValidate, InputLengthValidate, LENGTH_LIMIT, LOGIN_TYPE, Mask, RecordType, Request, RequestChain, Tour, addURLParams, countUp, dataHandler, debounce, deepMerge, deleteURLParams, download, email, findTreeDataNode, findTreeDataNodeName, getURLParams, hasRepeatArray, idCard, ip, isMobileDevice, isNull, objectArrayToString, phone, throttle, uniqueByProperty, url, useCountDown, useDownload, zhLetterNumber };
3238
+ export { AudioRecorder, HAS_FEILD, InputLegalityValidate, InputLengthValidate, LENGTH_LIMIT, LOGIN_TYPE, Mask, RecordType, Request, RequestChain, StreamRequest, Tour, addURLParams, countUp, dataHandler, debounce, deepMerge, deleteURLParams, download, email, findTreeDataNode, findTreeDataNodeName, getURLParams, hasRepeatArray, idCard, ip, isMobileDevice, isNull, objectArrayToString, phone, throttle, uniqueByProperty, url, useCountDown, useDownload, zhLetterNumber };
package/dist/index.umd.js CHANGED
@@ -32,6 +32,18 @@
32
32
  return __assign.apply(this, arguments);
33
33
  };
34
34
 
35
+ function __rest(s, e) {
36
+ var t = {};
37
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
38
+ t[p] = s[p];
39
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
40
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
41
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
42
+ t[p[i]] = s[p[i]];
43
+ }
44
+ return t;
45
+ }
46
+
35
47
  function __awaiter(thisArg, _arguments, P, generator) {
36
48
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
49
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -947,8 +959,9 @@
947
959
  var reconnectNumber = 0;
948
960
  var open = function (ws, config, callback) {
949
961
  var reconnectTime = config.reconnectTime, _a = config.maxReconnectNumber, maxReconnectNumber = _a === void 0 ? 1 : _a;
950
- var isOpen = getState(ws, 'OPEN');
951
- if (isOpen || (reconnectTimeout && reconnectNumber >= maxReconnectNumber)) {
962
+ var isOpen = getState(ws, "OPEN");
963
+ if (isOpen ||
964
+ (reconnectTimeout && reconnectNumber >= maxReconnectNumber)) {
952
965
  clearTimeout(reconnectTimeout);
953
966
  reconnectTimeout = null;
954
967
  reconnectNumber = null;
@@ -966,12 +979,12 @@
966
979
  var heartbeatTime = config.heartbeatTime;
967
980
  var timer = null;
968
981
  timer = setInterval(function () {
969
- var isOpen = getState(ws, 'OPEN');
970
- var isConnected = getState(ws, 'CONNECTING');
982
+ var isOpen = getState(ws, "OPEN");
983
+ var isConnected = getState(ws, "CONNECTING");
971
984
  if (isOpen) {
972
985
  useSendMessage(ws, {
973
- type: 'heartbeat',
974
- timestamp: Date.now()
986
+ type: "heartbeat",
987
+ timestamp: Date.now(),
975
988
  });
976
989
  }
977
990
  else if (!isConnected) {
@@ -984,7 +997,7 @@
984
997
  }, heartbeatTime);
985
998
  }
986
999
  function useSendMessage(ws, data) {
987
- var isOpen = getState(ws, 'OPEN');
1000
+ var isOpen = getState(ws, "OPEN");
988
1001
  if (isOpen)
989
1002
  ws.send(JSON.stringify(data));
990
1003
  }
@@ -1001,7 +1014,7 @@
1001
1014
  }
1002
1015
  function useClose(ws, code, message) {
1003
1016
  code = code || 1000;
1004
- message = message || 'connection closed by client';
1017
+ message = message || "connection closed by client";
1005
1018
  ws.close(code, message);
1006
1019
  }
1007
1020
 
@@ -1060,9 +1073,8 @@
1060
1073
  var map = new Map();
1061
1074
  var _loop_1 = function (item) {
1062
1075
  var val = (keys === null || keys === void 0 ? void 0 : keys.map(function (key) { return item[key]; }).join(',')) || item;
1063
- if (map.has(val)) {
1076
+ if (map.has(val))
1064
1077
  return { value: [true, val.split(',')] };
1065
- }
1066
1078
  map.set(val, item);
1067
1079
  };
1068
1080
  for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) {
@@ -1099,6 +1111,312 @@
1099
1111
  return newUrl;
1100
1112
  }
1101
1113
 
1114
+ var StreamRequest = /** @class */ (function () {
1115
+ function StreamRequest(url, config) {
1116
+ var _a = config, parseResponse = _a.parseResponse, options = __rest(_a, ["parseResponse"]);
1117
+ this.url = url;
1118
+ this.options = options || {};
1119
+ this.parseResponse = parseResponse;
1120
+ }
1121
+ StreamRequest.prototype.onBefore = function (callback) {
1122
+ this.beforeCallback = callback;
1123
+ };
1124
+ StreamRequest.prototype.send = function (params) {
1125
+ return __awaiter(this, void 0, void 0, function () {
1126
+ var _a, url, options, parseResponse, res, reader, _b, done, value, data, newData, error_1;
1127
+ var _this = this;
1128
+ var _c, _d;
1129
+ return __generator(this, function (_e) {
1130
+ switch (_e.label) {
1131
+ case 0:
1132
+ _a = this, url = _a.url, options = _a.options, parseResponse = _a.parseResponse;
1133
+ _e.label = 1;
1134
+ case 1:
1135
+ _e.trys.push([1, 6, , 7]);
1136
+ if (typeof this.beforeCallback === 'function')
1137
+ this.beforeCallback(params);
1138
+ return [4 /*yield*/, window.fetch(url, __assign(__assign({}, options), { body: JSON.stringify(params) }))];
1139
+ case 2:
1140
+ res = _e.sent();
1141
+ reader = (_c = res.body) === null || _c === void 0 ? void 0 : _c.getReader();
1142
+ if (!reader)
1143
+ return [2 /*return*/];
1144
+ _e.label = 3;
1145
+ case 3:
1146
+ return [4 /*yield*/, reader.read()];
1147
+ case 4:
1148
+ _b = _e.sent(), done = _b.done, value = _b.value;
1149
+ if (done)
1150
+ return [3 /*break*/, 5];
1151
+ data = new TextDecoder().decode(value);
1152
+ newData = data.split('\n');
1153
+ if (typeof this.beforeResponse === 'function') {
1154
+ this.beforeResponse(data, this.messageCallback);
1155
+ }
1156
+ else {
1157
+ newData.forEach(function (message) {
1158
+ var _a;
1159
+ if (message.trim()) {
1160
+ (_a = _this.messageCallback) === null || _a === void 0 ? void 0 : _a.call(_this, parseResponse ? JSON.parse(message || '{}') : message);
1161
+ }
1162
+ });
1163
+ }
1164
+ return [3 /*break*/, 3];
1165
+ case 5: return [3 /*break*/, 7];
1166
+ case 6:
1167
+ error_1 = _e.sent();
1168
+ (_d = this.errorCallback) === null || _d === void 0 ? void 0 : _d.call(this, error_1);
1169
+ return [3 /*break*/, 7];
1170
+ case 7: return [2 /*return*/];
1171
+ }
1172
+ });
1173
+ });
1174
+ };
1175
+ StreamRequest.prototype.onBeforeResponse = function (beforeResponse) {
1176
+ this.beforeResponse = beforeResponse;
1177
+ };
1178
+ StreamRequest.prototype.onMessage = function (callback) {
1179
+ this.messageCallback = callback;
1180
+ };
1181
+ StreamRequest.prototype.onError = function (callback) {
1182
+ this.errorCallback = callback;
1183
+ };
1184
+ return StreamRequest;
1185
+ }());
1186
+
1187
+ var AudioRecorder = /** @class */ (function () {
1188
+ function AudioRecorder(options) {
1189
+ this.options = {
1190
+ media: {
1191
+ audio: {
1192
+ channelCount: { ideal: 2 },
1193
+ sampleRate: { ideal: 44100 },
1194
+ echoCancellation: true,
1195
+ }
1196
+ },
1197
+ mediaRecorder: {
1198
+ mimeType: 'audio/mp4;codecs=mp4a.40.2',
1199
+ },
1200
+ maxTime: 0,
1201
+ };
1202
+ this.stream = null;
1203
+ this.mediaRecorder = null;
1204
+ this.audioChunks = [];
1205
+ this.audioInfo = {
1206
+ sampleRate: 0,
1207
+ channels: 0,
1208
+ format: null,
1209
+ bitDepth: 0,
1210
+ };
1211
+ this.timer = null;
1212
+ this.timerCount = 0;
1213
+ this.stopCallback = null;
1214
+ this.timerCallback = null;
1215
+ this.timerEndCallback = null;
1216
+ this.audioChunks = [];
1217
+ this.options = options;
1218
+ }
1219
+ // 开始录音
1220
+ AudioRecorder.prototype.start = function () {
1221
+ return __awaiter(this, void 0, void 0, function () {
1222
+ var _a, media, mediaRecorder, _b, maxTime, _c, error_1;
1223
+ var _this = this;
1224
+ return __generator(this, function (_d) {
1225
+ switch (_d.label) {
1226
+ case 0:
1227
+ _d.trys.push([0, 2, , 3]);
1228
+ _a = this.options, media = _a.media, mediaRecorder = _a.mediaRecorder, _b = _a.maxTime, maxTime = _b === void 0 ? 0 : _b;
1229
+ _c = this;
1230
+ return [4 /*yield*/, navigator.mediaDevices.getUserMedia({ audio: media.audio })];
1231
+ case 1:
1232
+ _c.stream = _d.sent();
1233
+ this.mediaRecorder = new MediaRecorder(this.stream, mediaRecorder);
1234
+ this.mediaRecorder.ondataavailable = function (event) {
1235
+ _this.audioInfo.format = event.data.type;
1236
+ _this.audioChunks.push(event.data);
1237
+ };
1238
+ this.mediaRecorder.onstop = function () {
1239
+ var _a;
1240
+ (_a = _this.stopCallback) === null || _a === void 0 ? void 0 : _a.call(_this, _this.audioChunks);
1241
+ _this.reset();
1242
+ };
1243
+ this.mediaRecorder.start();
1244
+ if (maxTime > 0) {
1245
+ this.startTimer({
1246
+ end: function () {
1247
+ _this.stop();
1248
+ }
1249
+ });
1250
+ }
1251
+ return [3 /*break*/, 3];
1252
+ case 2:
1253
+ error_1 = _d.sent();
1254
+ throw new Error(error_1);
1255
+ case 3: return [2 /*return*/];
1256
+ }
1257
+ });
1258
+ });
1259
+ };
1260
+ // 停止录音
1261
+ AudioRecorder.prototype.stop = function () {
1262
+ if (this.mediaRecorder) {
1263
+ this.audioChunks = [];
1264
+ this.mediaRecorder.stop();
1265
+ }
1266
+ };
1267
+ AudioRecorder.prototype.reset = function () {
1268
+ var _a, _b;
1269
+ this.audioChunks = [];
1270
+ (_b = (_a = this.stream) === null || _a === void 0 ? void 0 : _a.getTracks()) === null || _b === void 0 ? void 0 : _b.forEach(function (track) { return track.stop(); });
1271
+ };
1272
+ AudioRecorder.prototype.onStop = function (callback) {
1273
+ this.stopCallback = callback;
1274
+ };
1275
+ AudioRecorder.prototype.startTimer = function (options) {
1276
+ var _this = this;
1277
+ var _a = options || {}, next = _a.next, end = _a.end;
1278
+ this.timer = setInterval(function () {
1279
+ var _a, _b;
1280
+ next === null || next === void 0 ? void 0 : next();
1281
+ (_a = _this.timerCallback) === null || _a === void 0 ? void 0 : _a.call(_this, _this.timerCount);
1282
+ console.log('this.timerCount2: ', _this.timerCount);
1283
+ if (_this.timerCount === _this.options.maxTime) {
1284
+ _this.clearTimer();
1285
+ end === null || end === void 0 ? void 0 : end();
1286
+ (_b = _this.timerEndCallback) === null || _b === void 0 ? void 0 : _b.call(_this);
1287
+ }
1288
+ _this.timerCount++;
1289
+ }, 1000);
1290
+ };
1291
+ // 清除定时器
1292
+ AudioRecorder.prototype.clearTimer = function () {
1293
+ if (this.timer)
1294
+ clearInterval(this.timer);
1295
+ this.timer = null;
1296
+ this.timerCount = 0;
1297
+ };
1298
+ AudioRecorder.prototype.onTimer = function (callback) {
1299
+ this.timerCallback = callback;
1300
+ };
1301
+ AudioRecorder.prototype.onTimerEnd = function (callback) {
1302
+ this.timerEndCallback = callback;
1303
+ };
1304
+ AudioRecorder.prototype.getAudioBlob = function () {
1305
+ if (!this.mediaRecorder)
1306
+ return null;
1307
+ var type = this.getExtension(this.mediaRecorder.mimeType);
1308
+ return new Blob(this.audioChunks, { type: "audio/".concat(type) });
1309
+ };
1310
+ AudioRecorder.prototype.getAudioUrl = function () {
1311
+ var blob = this.getAudioBlob();
1312
+ if (!blob)
1313
+ return '';
1314
+ return URL.createObjectURL(blob);
1315
+ };
1316
+ AudioRecorder.prototype.getAudioBase64 = function (blob) {
1317
+ return new Promise(function (resolve, reject) {
1318
+ var reader = new FileReader();
1319
+ reader.onerror = reject;
1320
+ reader.onload = function () { return resolve(reader.result); };
1321
+ reader.readAsDataURL(blob);
1322
+ });
1323
+ };
1324
+ AudioRecorder.prototype.getAudioInfo = function () {
1325
+ var _this = this;
1326
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1327
+ var audioContext, source, analyser, sampleRate, channels, bitDepth, error_2;
1328
+ var _a;
1329
+ return __generator(this, function (_b) {
1330
+ switch (_b.label) {
1331
+ case 0:
1332
+ _b.trys.push([0, 2, , 3]);
1333
+ audioContext = new (window.AudioContext || window.webkitAudioContext)();
1334
+ source = audioContext.createMediaStreamSource(this.stream);
1335
+ analyser = audioContext.createAnalyser();
1336
+ source.connect(analyser);
1337
+ sampleRate = audioContext.sampleRate;
1338
+ channels = ((_a = this.stream) === null || _a === void 0 ? void 0 : _a.getAudioTracks()[0].getSettings().channelCount) || 0;
1339
+ return [4 /*yield*/, this.getWavBitDepth(this.getAudioBlob())];
1340
+ case 1:
1341
+ bitDepth = _b.sent();
1342
+ resolve(__assign({ sampleRate: sampleRate, channels: channels, bitDepth: bitDepth }, this.audioInfo));
1343
+ return [3 /*break*/, 3];
1344
+ case 2:
1345
+ error_2 = _b.sent();
1346
+ reject(error_2);
1347
+ return [3 /*break*/, 3];
1348
+ case 3: return [2 /*return*/];
1349
+ }
1350
+ });
1351
+ }); });
1352
+ };
1353
+ AudioRecorder.prototype.getWavBitDepth = function (blob) {
1354
+ return new Promise(function (resolve, reject) {
1355
+ var reader = new FileReader();
1356
+ reader.onload = function (event) {
1357
+ var _a;
1358
+ var arrayBuffer = (_a = event.target) === null || _a === void 0 ? void 0 : _a.result;
1359
+ if (!arrayBuffer) {
1360
+ reject();
1361
+ throw new Error('未能读取 Blob 数据');
1362
+ }
1363
+ var data = new DataView(arrayBuffer);
1364
+ // 检查 "fmt " 区域,WAV文件的音频格式信息通常在此
1365
+ var fmtChunkOffset = 20; // "fmt " chunk 在 WAV 文件头的位置
1366
+ var bitDepth = data.getUint16(fmtChunkOffset + 14, true); // 16位表示小端存储
1367
+ resolve(bitDepth);
1368
+ };
1369
+ reader.readAsArrayBuffer(blob);
1370
+ });
1371
+ };
1372
+ AudioRecorder.prototype.getExtension = function (mimeType) {
1373
+ var mimeToExt = {
1374
+ 'audio/webm': 'webm',
1375
+ 'audio/webm;codecs=opus': 'webm',
1376
+ 'audio/ogg': 'ogg',
1377
+ 'audio/ogg;codecs=opus': 'ogg',
1378
+ 'audio/mp4': 'mp4',
1379
+ 'audio/mpeg': 'mp3',
1380
+ 'audio/wav': 'wav',
1381
+ };
1382
+ if (mimeToExt[mimeType])
1383
+ return mimeToExt[mimeType];
1384
+ var mainType = mimeType.split(';')[0];
1385
+ return mimeToExt[mainType] || 'audio';
1386
+ };
1387
+ // 上传音频到服务器
1388
+ AudioRecorder.prototype.upload = function (url, options) {
1389
+ return __awaiter(this, void 0, void 0, function () {
1390
+ var audioBlob, formData, response, data, error_3;
1391
+ return __generator(this, function (_a) {
1392
+ switch (_a.label) {
1393
+ case 0:
1394
+ audioBlob = this.getAudioBlob();
1395
+ if (!audioBlob)
1396
+ return [2 /*return*/, null];
1397
+ formData = new FormData();
1398
+ formData.append('audio', audioBlob, 'recording.mp4');
1399
+ _a.label = 1;
1400
+ case 1:
1401
+ _a.trys.push([1, 4, , 5]);
1402
+ return [4 /*yield*/, fetch(url, options)];
1403
+ case 2:
1404
+ response = _a.sent();
1405
+ return [4 /*yield*/, response.json()];
1406
+ case 3:
1407
+ data = _a.sent();
1408
+ return [2 /*return*/, data];
1409
+ case 4:
1410
+ error_3 = _a.sent();
1411
+ throw new Error(error_3);
1412
+ case 5: return [2 /*return*/];
1413
+ }
1414
+ });
1415
+ });
1416
+ };
1417
+ return AudioRecorder;
1418
+ }());
1419
+
1102
1420
  /**
1103
1421
  * 匹配中文字母数字
1104
1422
  */
@@ -1124,11 +1442,13 @@
1124
1442
  */
1125
1443
  var url = /^https?:\/\/[^\s/$.?#].[^\s]*$/;
1126
1444
 
1445
+ exports.AudioRecorder = AudioRecorder;
1127
1446
  exports.InputLegalityValidate = InputLegalityValidate;
1128
1447
  exports.InputLengthValidate = InputLengthValidate;
1129
1448
  exports.Mask = Mask;
1130
1449
  exports.Request = Request;
1131
1450
  exports.RequestChain = RequestChain;
1451
+ exports.StreamRequest = StreamRequest;
1132
1452
  exports.Tour = Tour;
1133
1453
  exports.addURLParams = addURLParams;
1134
1454
  exports.countUp = countUp;
@@ -0,0 +1,42 @@
1
+ interface AudioRecorderOptions {
2
+ media: MediaStreamConstraints;
3
+ mediaRecorder?: MediaRecorderOptions;
4
+ maxTime?: number;
5
+ }
6
+ interface TimerOptions {
7
+ next?: () => void;
8
+ end?: () => void;
9
+ }
10
+ interface AudioInfo {
11
+ sampleRate: number;
12
+ channels: number;
13
+ format: string | null;
14
+ bitDepth: number;
15
+ }
16
+ declare class AudioRecorder {
17
+ private options;
18
+ private stream;
19
+ private mediaRecorder;
20
+ private audioChunks;
21
+ private audioInfo;
22
+ private timer;
23
+ private timerCount;
24
+ private timerCallback;
25
+ private timerEndCallback;
26
+ constructor(options: AudioRecorderOptions);
27
+ start(): Promise<void>;
28
+ stop(): void;
29
+ reset(): void;
30
+ onStop(): void;
31
+ startTimer(options?: TimerOptions): void;
32
+ clearTimer(): void;
33
+ onTimer(callback: () => void): void;
34
+ onTimerEnd(callback: () => void): void;
35
+ getAudioBlob(): Blob | null;
36
+ getAudioUrl(): string;
37
+ getAudioBase64(blob: Blob): Promise<string>;
38
+ getAudioInfo(): Promise<unknown>;
39
+ getWavBitDepth(blob: Blob): Promise<number>;
40
+ getExtension(mimeType: string): string;
41
+ upload(url: string, options?: RequestInit): Promise<any>;
42
+ }
@@ -8,3 +8,5 @@ export * from './download';
8
8
  export * from './number';
9
9
  export * from './array';
10
10
  export * from './url';
11
+ export * from './sse';
12
+ export * from './recorder';
@@ -0,0 +1,44 @@
1
+ export interface AudioRecorderOptions {
2
+ media: MediaStreamConstraints;
3
+ mediaRecorder?: MediaRecorderOptions;
4
+ maxTime?: number;
5
+ }
6
+ interface TimerOptions {
7
+ next?: () => void;
8
+ end?: () => void;
9
+ }
10
+ export interface AudioInfo {
11
+ sampleRate: number;
12
+ channels: number;
13
+ format: string | null;
14
+ bitDepth: number;
15
+ }
16
+ export declare class AudioRecorder {
17
+ private options;
18
+ private stream;
19
+ private mediaRecorder;
20
+ private audioChunks;
21
+ private audioInfo;
22
+ private timer;
23
+ private timerCount;
24
+ private stopCallback;
25
+ private timerCallback;
26
+ private timerEndCallback;
27
+ constructor(options: AudioRecorderOptions);
28
+ start(): Promise<void>;
29
+ stop(): void;
30
+ reset(): void;
31
+ onStop(callback: (audioChunks: Blob[]) => void): void;
32
+ startTimer(options?: TimerOptions): void;
33
+ clearTimer(): void;
34
+ onTimer(callback: (count: number) => void): void;
35
+ onTimerEnd(callback: () => void): void;
36
+ getAudioBlob(): Blob | null;
37
+ getAudioUrl(): string;
38
+ getAudioBase64(blob: Blob): Promise<string>;
39
+ getAudioInfo(): Promise<unknown>;
40
+ getWavBitDepth(blob: Blob): Promise<number>;
41
+ getExtension(mimeType: string): string;
42
+ upload(url: string, options?: RequestInit): Promise<any>;
43
+ }
44
+ export {};
@@ -0,0 +1,19 @@
1
+ interface StreamRequestConfig extends RequestInit {
2
+ parseResponse?: boolean;
3
+ }
4
+ export declare class StreamRequest {
5
+ private url;
6
+ private options;
7
+ private beforeCallback?;
8
+ private messageCallback?;
9
+ private errorCallback?;
10
+ private parseResponse?;
11
+ private beforeResponse?;
12
+ constructor(url: string, config?: StreamRequestConfig);
13
+ private onBefore;
14
+ private send;
15
+ onBeforeResponse(beforeResponse: () => void): void;
16
+ private onMessage;
17
+ private onError;
18
+ }
19
+ export {};
@@ -1,4 +1,4 @@
1
- type WebSocketState = 'CONNECTING' | 'OPEN' | 'CLOSING' | 'CLOSED';
1
+ type WebSocketState = "CONNECTING" | "OPEN" | "CLOSING" | "CLOSED";
2
2
  interface WebSocketConfig {
3
3
  heartbeat?: boolean;
4
4
  heartbeatTime?: number;
@@ -0,0 +1,181 @@
1
+ /******************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */
15
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
16
+
17
+
18
+ var __assign = function() {
19
+ __assign = Object.assign || function __assign(t) {
20
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
21
+ s = arguments[i];
22
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
23
+ }
24
+ return t;
25
+ };
26
+ return __assign.apply(this, arguments);
27
+ };
28
+
29
+ function __rest(s, e) {
30
+ var t = {};
31
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
32
+ t[p] = s[p];
33
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
34
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
35
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
36
+ t[p[i]] = s[p[i]];
37
+ }
38
+ return t;
39
+ }
40
+
41
+ function __awaiter(thisArg, _arguments, P, generator) {
42
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
43
+ return new (P || (P = Promise))(function (resolve, reject) {
44
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
45
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
46
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
47
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
48
+ });
49
+ }
50
+
51
+ function __generator(thisArg, body) {
52
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
53
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
54
+ function verb(n) { return function (v) { return step([n, v]); }; }
55
+ function step(op) {
56
+ if (f) throw new TypeError("Generator is already executing.");
57
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
58
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
59
+ if (y = 0, t) op = [op[0] & 2, t.value];
60
+ switch (op[0]) {
61
+ case 0: case 1: t = op; break;
62
+ case 4: _.label++; return { value: op[1], done: false };
63
+ case 5: _.label++; y = op[1]; op = [0]; continue;
64
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
65
+ default:
66
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
67
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
68
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
69
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
70
+ if (t[2]) _.ops.pop();
71
+ _.trys.pop(); continue;
72
+ }
73
+ op = body.call(thisArg, _);
74
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
75
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
76
+ }
77
+ }
78
+
79
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
80
+ var e = new Error(message);
81
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
82
+ };
83
+
84
+ var defaultWebSocketConfig = {
85
+ heartbeat: false,
86
+ heartbeatTime: 15000,
87
+ reconnect: false,
88
+ reconnectTime: 1000,
89
+ maxReconnectNumber: 3,
90
+ };
91
+ function createWebSocket(url, config, onOpen) {
92
+ config = __assign(__assign({}, defaultWebSocketConfig), config);
93
+ var open = reconnectWebSocket();
94
+ var init = function () {
95
+ var ws = new WebSocket(url);
96
+ ws.onopen = function () {
97
+ if (config === null || config === void 0 ? void 0 : config.heartbeat)
98
+ heartbeat(ws, config);
99
+ onOpen === null || onOpen === void 0 ? void 0 : onOpen();
100
+ };
101
+ ws.onerror = function () {
102
+ if ((config === null || config === void 0 ? void 0 : config.reconnect) && open) {
103
+ open(ws, config, init);
104
+ }
105
+ else {
106
+ open = null;
107
+ config = null;
108
+ }
109
+ };
110
+ return ws;
111
+ };
112
+ return init();
113
+ }
114
+ function getState(ws, type) {
115
+ return ws.readyState === WebSocket[type];
116
+ }
117
+ function reconnectWebSocket() {
118
+ var reconnectTimeout;
119
+ var reconnectNumber = 0;
120
+ var open = function (ws, config, callback) {
121
+ var reconnectTime = config.reconnectTime, _a = config.maxReconnectNumber, maxReconnectNumber = _a === void 0 ? 1 : _a;
122
+ var isOpen = getState(ws, "OPEN");
123
+ if (isOpen ||
124
+ (reconnectTimeout && reconnectNumber >= maxReconnectNumber)) {
125
+ clearTimeout(reconnectTimeout);
126
+ reconnectTimeout = null;
127
+ reconnectNumber = null;
128
+ config.reconnect = false;
129
+ return;
130
+ }
131
+ reconnectTimeout = setTimeout(function () {
132
+ reconnectNumber += 1;
133
+ callback();
134
+ }, reconnectTime);
135
+ };
136
+ return open;
137
+ }
138
+ function heartbeat(ws, config) {
139
+ var heartbeatTime = config.heartbeatTime;
140
+ var timer = null;
141
+ timer = setInterval(function () {
142
+ var isOpen = getState(ws, "OPEN");
143
+ var isConnected = getState(ws, "CONNECTING");
144
+ if (isOpen) {
145
+ useSendMessage(ws, {
146
+ type: "heartbeat",
147
+ timestamp: Date.now(),
148
+ });
149
+ }
150
+ else if (!isConnected) {
151
+ var open_1 = reconnectWebSocket();
152
+ open_1(ws, config, function () {
153
+ timer && clearInterval(timer);
154
+ heartbeat(ws, config);
155
+ });
156
+ }
157
+ }, heartbeatTime);
158
+ }
159
+ function useSendMessage(ws, data) {
160
+ var isOpen = getState(ws, "OPEN");
161
+ if (isOpen)
162
+ ws.send(JSON.stringify(data));
163
+ }
164
+ function useOnMessage(ws, callback) {
165
+ try {
166
+ ws.onmessage = function (e) {
167
+ var data = JSON.parse(e.data);
168
+ callback(data, e);
169
+ };
170
+ }
171
+ catch (error) {
172
+ console.error(error);
173
+ }
174
+ }
175
+ function useClose(ws, code, message) {
176
+ code = code || 1000;
177
+ message = message || "connection closed by client";
178
+ ws.close(code, message);
179
+ }
180
+
181
+ export { __assign as _, __awaiter as a, __generator as b, __rest as c, createWebSocket as d, useOnMessage as e, useClose as f, getState as g, useSendMessage as u };
package/dist/ws.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- type WebSocketState = 'CONNECTING' | 'OPEN' | 'CLOSING' | 'CLOSED';
1
+ type WebSocketState = "CONNECTING" | "OPEN" | "CLOSING" | "CLOSED";
2
2
  interface WebSocketConfig {
3
3
  heartbeat?: boolean;
4
4
  heartbeatTime?: number;
package/dist/ws.js CHANGED
@@ -1 +1 @@
1
- export { c as createWebSocket, g as getState, e as useClose, d as useOnMessage, u as useSendMessage } from './ws-DGDUMiR9.js';
1
+ export { d as createWebSocket, g as getState, f as useClose, e as useOnMessage, u as useSendMessage } from './ws-Dvvmk4pM.js';
package/dist/ws.umd.js CHANGED
@@ -75,8 +75,9 @@
75
75
  var reconnectNumber = 0;
76
76
  var open = function (ws, config, callback) {
77
77
  var reconnectTime = config.reconnectTime, _a = config.maxReconnectNumber, maxReconnectNumber = _a === void 0 ? 1 : _a;
78
- var isOpen = getState(ws, 'OPEN');
79
- if (isOpen || (reconnectTimeout && reconnectNumber >= maxReconnectNumber)) {
78
+ var isOpen = getState(ws, "OPEN");
79
+ if (isOpen ||
80
+ (reconnectTimeout && reconnectNumber >= maxReconnectNumber)) {
80
81
  clearTimeout(reconnectTimeout);
81
82
  reconnectTimeout = null;
82
83
  reconnectNumber = null;
@@ -94,12 +95,12 @@
94
95
  var heartbeatTime = config.heartbeatTime;
95
96
  var timer = null;
96
97
  timer = setInterval(function () {
97
- var isOpen = getState(ws, 'OPEN');
98
- var isConnected = getState(ws, 'CONNECTING');
98
+ var isOpen = getState(ws, "OPEN");
99
+ var isConnected = getState(ws, "CONNECTING");
99
100
  if (isOpen) {
100
101
  useSendMessage(ws, {
101
- type: 'heartbeat',
102
- timestamp: Date.now()
102
+ type: "heartbeat",
103
+ timestamp: Date.now(),
103
104
  });
104
105
  }
105
106
  else if (!isConnected) {
@@ -112,7 +113,7 @@
112
113
  }, heartbeatTime);
113
114
  }
114
115
  function useSendMessage(ws, data) {
115
- var isOpen = getState(ws, 'OPEN');
116
+ var isOpen = getState(ws, "OPEN");
116
117
  if (isOpen)
117
118
  ws.send(JSON.stringify(data));
118
119
  }
@@ -129,7 +130,7 @@
129
130
  }
130
131
  function useClose(ws, code, message) {
131
132
  code = code || 1000;
132
- message = message || 'connection closed by client';
133
+ message = message || "connection closed by client";
133
134
  ws.close(code, message);
134
135
  }
135
136
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightsoft/js-sdk",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
4
4
  "description": "",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.js",