wenay-common2 1.0.1
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/lib/Common/Color.d.ts +31 -0
- package/lib/Common/Color.js +115 -0
- package/lib/Common/Time.d.ts +206 -0
- package/lib/Common/Time.js +393 -0
- package/lib/Common/WebHook2.d.ts +0 -0
- package/lib/Common/WebHook2.js +1 -0
- package/lib/Common/WebHook3.d.ts +39 -0
- package/lib/Common/WebHook3.js +211 -0
- package/lib/Common/async/PromiseArrayListen.d.ts +14 -0
- package/lib/Common/async/PromiseArrayListen.js +41 -0
- package/lib/Common/async/createIterableObject.d.ts +6 -0
- package/lib/Common/async/createIterableObject.js +66 -0
- package/lib/Common/async/waitRun.d.ts +31 -0
- package/lib/Common/async/waitRun.js +104 -0
- package/lib/Common/core/BaseTypes.d.ts +38 -0
- package/lib/Common/core/BaseTypes.js +2 -0
- package/lib/Common/core/Decorator.d.ts +24 -0
- package/lib/Common/core/Decorator.js +50 -0
- package/lib/Common/core/MemoFunc.d.ts +19 -0
- package/lib/Common/core/MemoFunc.js +99 -0
- package/lib/Common/core/common.d.ts +253 -0
- package/lib/Common/core/common.js +773 -0
- package/lib/Common/data/ByteStream.d.ts +96 -0
- package/lib/Common/data/ByteStream.js +440 -0
- package/lib/Common/data/List.d.ts +64 -0
- package/lib/Common/data/List.js +193 -0
- package/lib/Common/data/ListNodeAnd.d.ts +46 -0
- package/lib/Common/data/ListNodeAnd.js +89 -0
- package/lib/Common/data/objectPath.d.ts +11 -0
- package/lib/Common/data/objectPath.js +59 -0
- package/lib/Common/events/Listen.d.ts +55 -0
- package/lib/Common/events/Listen.js +124 -0
- package/lib/Common/events/SocketBuffer.d.ts +41 -0
- package/lib/Common/events/SocketBuffer.js +43 -0
- package/lib/Common/events/SocketServerHook.d.ts +47 -0
- package/lib/Common/events/SocketServerHook.js +38 -0
- package/lib/Common/events/event.d.ts +34 -0
- package/lib/Common/events/event.js +77 -0
- package/lib/Common/events/joinListens.d.ts +17 -0
- package/lib/Common/events/joinListens.js +40 -0
- package/lib/Common/fsKeyVolume.d.ts +34 -0
- package/lib/Common/fsKeyVolume.js +92 -0
- package/lib/Common/funcTimeWait.d.ts +29 -0
- package/lib/Common/funcTimeWait.js +116 -0
- package/lib/Common/id-pool.d.ts +5 -0
- package/lib/Common/id-pool.js +12 -0
- package/lib/Common/inputAutoStep.d.ts +14 -0
- package/lib/Common/inputAutoStep.js +65 -0
- package/lib/Common/isProxy.d.ts +2 -0
- package/lib/Common/isProxy.js +40 -0
- package/lib/Common/math/Math.d.ts +12 -0
- package/lib/Common/math/Math.js +73 -0
- package/lib/Common/math/other.d.ts +23 -0
- package/lib/Common/math/other.js +70 -0
- package/lib/Common/math/scoreLana.d.ts +22 -0
- package/lib/Common/math/scoreLana.js +67 -0
- package/lib/Common/node_console.d.ts +6 -0
- package/lib/Common/node_console.js +170 -0
- package/lib/Common/rcp/listen-deep.d.ts +20 -0
- package/lib/Common/rcp/listen-deep.js +49 -0
- package/lib/Common/rcp/listen-socket.d.ts +25 -0
- package/lib/Common/rcp/listen-socket.js +105 -0
- package/lib/Common/rcp/rpc-client-auto.d.ts +12 -0
- package/lib/Common/rcp/rpc-client-auto.js +20 -0
- package/lib/Common/rcp/rpc-client.d.ts +30 -0
- package/lib/Common/rcp/rpc-client.js +169 -0
- package/lib/Common/rcp/rpc-dynamic.d.ts +2 -0
- package/lib/Common/rcp/rpc-dynamic.js +12 -0
- package/lib/Common/rcp/rpc-index.d.ts +8 -0
- package/lib/Common/rcp/rpc-index.js +24 -0
- package/lib/Common/rcp/rpc-limits.d.ts +14 -0
- package/lib/Common/rcp/rpc-limits.js +24 -0
- package/lib/Common/rcp/rpc-protocol.d.ts +12 -0
- package/lib/Common/rcp/rpc-protocol.js +4 -0
- package/lib/Common/rcp/rpc-server-auto.d.ts +15 -0
- package/lib/Common/rcp/rpc-server-auto.js +28 -0
- package/lib/Common/rcp/rpc-server.d.ts +27 -0
- package/lib/Common/rcp/rpc-server.js +175 -0
- package/lib/Common/rcp/rpc-walk.d.ts +8 -0
- package/lib/Common/rcp/rpc-walk.js +82 -0
- package/lib/Exchange/Bars.d.ts +181 -0
- package/lib/Exchange/Bars.js +475 -0
- package/lib/Exchange/CParams.d.ts +225 -0
- package/lib/Exchange/CParams.js +244 -0
- package/lib/client.d.ts +31 -0
- package/lib/client.js +70 -0
- package/lib/index.d.ts +31 -0
- package/lib/index.js +70 -0
- package/lib/server.d.ts +3 -0
- package/lib/server.js +19 -0
- package/lib/toError/myThrow.d.ts +5 -0
- package/lib/toError/myThrow.js +23 -0
- package/lib/tsconfig.json +6 -0
- package/package.json +32 -0
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CDelayer = exports.Period = exports.PeriodSpan = exports.TF = exports.TIME_UNIT = exports.M1_MS = exports.H1_MS = exports.D1_MS = exports.W1_MS = exports.W1_S = exports.D1_S = exports.H1_S = void 0;
|
|
4
|
+
exports.timeToStr_hhmmss_ms = timeToStr_hhmmss_ms;
|
|
5
|
+
exports.timeToStr_hhmmss = timeToStr_hhmmss;
|
|
6
|
+
exports.timeToStr_yyyymmdd_hhmm = timeToStr_yyyymmdd_hhmm;
|
|
7
|
+
exports.timeToStr_yyyymmdd_hhmmss = timeToStr_yyyymmdd_hhmmss;
|
|
8
|
+
exports.timeToStr_yyyymmdd_hhmmss_ms = timeToStr_yyyymmdd_hhmmss_ms;
|
|
9
|
+
exports.timeLocalToStr_hhmmss = timeLocalToStr_hhmmss;
|
|
10
|
+
exports.timeLocalToStr_hhmmss_ms = timeLocalToStr_hhmmss_ms;
|
|
11
|
+
exports.timeLocalToStr_yyyymmdd = timeLocalToStr_yyyymmdd;
|
|
12
|
+
exports.timeLocalToStr_yyyymmdd_hhmm = timeLocalToStr_yyyymmdd_hhmm;
|
|
13
|
+
exports.timeLocalToStr_yyyymmdd_hhmmss = timeLocalToStr_yyyymmdd_hhmmss;
|
|
14
|
+
exports.timeLocalToStr_yyyymmdd_hhmmss_ms = timeLocalToStr_yyyymmdd_hhmmss_ms;
|
|
15
|
+
exports.timeToString_yyyymmdd_hhmm_offset = timeToString_yyyymmdd_hhmm_offset;
|
|
16
|
+
exports.timeToString_yyyymmdd_hhmmss_offset = timeToString_yyyymmdd_hhmmss_offset;
|
|
17
|
+
exports.convertDatesToStrings = convertDatesToStrings;
|
|
18
|
+
exports.toPrintObject = toPrintObject;
|
|
19
|
+
exports.durationToStr = durationToStr;
|
|
20
|
+
exports.durationToStrNullable = durationToStrNullable;
|
|
21
|
+
exports.durationToStr_h_mm_ss = durationToStr_h_mm_ss;
|
|
22
|
+
exports.durationToStr_h_mm_ss_ms = durationToStr_h_mm_ss_ms;
|
|
23
|
+
exports.MinTime = MinTime;
|
|
24
|
+
exports.MaxTime = MaxTime;
|
|
25
|
+
const common_1 = require("./core/common");
|
|
26
|
+
function GetEnumKeys(T) { return Object.keys(T).filter(k => isNaN(k)); }
|
|
27
|
+
{
|
|
28
|
+
let t1 = "2022-05-01";
|
|
29
|
+
let t2 = "2022-05-01 01:01";
|
|
30
|
+
let t3 = "2022-05-01 01:01:10";
|
|
31
|
+
}
|
|
32
|
+
exports.H1_S = 3600;
|
|
33
|
+
exports.D1_S = 3600 * 24;
|
|
34
|
+
exports.W1_S = exports.D1_S * 7;
|
|
35
|
+
exports.W1_MS = exports.W1_S * 1000;
|
|
36
|
+
exports.D1_MS = exports.D1_S * 1000;
|
|
37
|
+
exports.H1_MS = exports.H1_S * 1000;
|
|
38
|
+
exports.M1_MS = 60 * 1000;
|
|
39
|
+
var __E_TF;
|
|
40
|
+
(function (__E_TF) {
|
|
41
|
+
__E_TF[__E_TF["S1"] = 1] = "S1";
|
|
42
|
+
__E_TF[__E_TF["S2"] = 2] = "S2";
|
|
43
|
+
__E_TF[__E_TF["S3"] = 3] = "S3";
|
|
44
|
+
__E_TF[__E_TF["S4"] = 4] = "S4";
|
|
45
|
+
__E_TF[__E_TF["S5"] = 5] = "S5";
|
|
46
|
+
__E_TF[__E_TF["S6"] = 6] = "S6";
|
|
47
|
+
__E_TF[__E_TF["S10"] = 7] = "S10";
|
|
48
|
+
__E_TF[__E_TF["S12"] = 8] = "S12";
|
|
49
|
+
__E_TF[__E_TF["S15"] = 9] = "S15";
|
|
50
|
+
__E_TF[__E_TF["S20"] = 10] = "S20";
|
|
51
|
+
__E_TF[__E_TF["S30"] = 11] = "S30";
|
|
52
|
+
__E_TF[__E_TF["M1"] = 12] = "M1";
|
|
53
|
+
__E_TF[__E_TF["M2"] = 13] = "M2";
|
|
54
|
+
__E_TF[__E_TF["M3"] = 14] = "M3";
|
|
55
|
+
__E_TF[__E_TF["M4"] = 15] = "M4";
|
|
56
|
+
__E_TF[__E_TF["M5"] = 16] = "M5";
|
|
57
|
+
__E_TF[__E_TF["M6"] = 17] = "M6";
|
|
58
|
+
__E_TF[__E_TF["M10"] = 18] = "M10";
|
|
59
|
+
__E_TF[__E_TF["M12"] = 19] = "M12";
|
|
60
|
+
__E_TF[__E_TF["M15"] = 20] = "M15";
|
|
61
|
+
__E_TF[__E_TF["M20"] = 21] = "M20";
|
|
62
|
+
__E_TF[__E_TF["M30"] = 22] = "M30";
|
|
63
|
+
__E_TF[__E_TF["H1"] = 23] = "H1";
|
|
64
|
+
__E_TF[__E_TF["H2"] = 24] = "H2";
|
|
65
|
+
__E_TF[__E_TF["H3"] = 25] = "H3";
|
|
66
|
+
__E_TF[__E_TF["H4"] = 26] = "H4";
|
|
67
|
+
__E_TF[__E_TF["H6"] = 27] = "H6";
|
|
68
|
+
__E_TF[__E_TF["H8"] = 28] = "H8";
|
|
69
|
+
__E_TF[__E_TF["H12"] = 29] = "H12";
|
|
70
|
+
__E_TF[__E_TF["D1"] = 30] = "D1";
|
|
71
|
+
__E_TF[__E_TF["W1"] = 31] = "W1";
|
|
72
|
+
__E_TF[__E_TF["MN1"] = 32] = "MN1";
|
|
73
|
+
__E_TF[__E_TF["MN2"] = 33] = "MN2";
|
|
74
|
+
__E_TF[__E_TF["MN3"] = 34] = "MN3";
|
|
75
|
+
__E_TF[__E_TF["MN4"] = 35] = "MN4";
|
|
76
|
+
__E_TF[__E_TF["MN6"] = 36] = "MN6";
|
|
77
|
+
__E_TF[__E_TF["Y1"] = 37] = "Y1";
|
|
78
|
+
})(__E_TF || (__E_TF = {}));
|
|
79
|
+
;
|
|
80
|
+
const __Tf_S = [0, 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60, 120, 180, 240, 300, 360, 600, 720, 900, 1200, 1800, exports.H1_S, 2 * exports.H1_S, 3 * exports.H1_S, 4 * exports.H1_S, 6 * exports.H1_S, 8 * exports.H1_S, 12 * exports.H1_S, exports.D1_S, exports.W1_S, 30 * exports.D1_S, 60 * exports.D1_S, 90 * exports.D1_S, 120 * exports.D1_S, 180 * exports.D1_S, 365 * exports.D1_S];
|
|
81
|
+
class TIME_UNIT {
|
|
82
|
+
index;
|
|
83
|
+
msec;
|
|
84
|
+
sec;
|
|
85
|
+
name;
|
|
86
|
+
sign;
|
|
87
|
+
static _lastIndex = 0;
|
|
88
|
+
constructor(msec, name, shortName) {
|
|
89
|
+
this.index = ++TIME_UNIT._lastIndex;
|
|
90
|
+
this.msec = msec;
|
|
91
|
+
this.sec = Math.floor(msec / 1000);
|
|
92
|
+
this.name = name;
|
|
93
|
+
this.sign = shortName;
|
|
94
|
+
}
|
|
95
|
+
static MSecond = new TIME_UNIT(1, "millisecond", "MS");
|
|
96
|
+
static Second = new TIME_UNIT(1000, "second", "S");
|
|
97
|
+
static Minute = new TIME_UNIT(60 * 1000, "minute", "M");
|
|
98
|
+
static Hour = new TIME_UNIT(exports.H1_S * 1000, "hour", "H");
|
|
99
|
+
static Day = new TIME_UNIT(exports.D1_S * 1000, "day", "D");
|
|
100
|
+
static Week = new TIME_UNIT(7 * exports.D1_S * 1000, "week", "W");
|
|
101
|
+
static Month = new TIME_UNIT(30 * exports.D1_S * 1000, "month", "MN");
|
|
102
|
+
static Year = new TIME_UNIT(365 * exports.D1_S * 1000, "year", "Y");
|
|
103
|
+
}
|
|
104
|
+
exports.TIME_UNIT = TIME_UNIT;
|
|
105
|
+
class TF {
|
|
106
|
+
sec;
|
|
107
|
+
msec;
|
|
108
|
+
name;
|
|
109
|
+
unit;
|
|
110
|
+
unitCount;
|
|
111
|
+
index;
|
|
112
|
+
valueOf() { return this.msec; }
|
|
113
|
+
toString() { return this.name; }
|
|
114
|
+
constructor(unit, unitCount, index, msec, name) {
|
|
115
|
+
this.unit = unit;
|
|
116
|
+
this.unitCount = unitCount;
|
|
117
|
+
this.msec = msec ?? unit.msec * unitCount;
|
|
118
|
+
this.sec = Math.floor(this.msec / 1000);
|
|
119
|
+
this.index = index;
|
|
120
|
+
this.name = name ?? (unit.sign + unitCount);
|
|
121
|
+
}
|
|
122
|
+
static constructFromSec(sec, name) {
|
|
123
|
+
let msec = sec * 1000;
|
|
124
|
+
let index = __Tf_S.indexOf(sec);
|
|
125
|
+
let units = [TIME_UNIT.Year, TIME_UNIT.Month, TIME_UNIT.Week, TIME_UNIT.Day, TIME_UNIT.Hour, TIME_UNIT.Minute, TIME_UNIT.Second, TIME_UNIT.MSecond];
|
|
126
|
+
let unit = units.find((u) => Math.floor(sec % u.sec) == 0);
|
|
127
|
+
let unitCount = Math.floor(sec / unit.sec);
|
|
128
|
+
return new TF(unit, unitCount, index, msec, name);
|
|
129
|
+
}
|
|
130
|
+
static get(name) {
|
|
131
|
+
let key = __E_TF[name];
|
|
132
|
+
if (key)
|
|
133
|
+
return this.all[key];
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
static getAsserted(name) { return TF.get(name) ?? (() => { throw "Unknown timeframe: " + name; })(); }
|
|
137
|
+
static fromName(name) { return this.get(name); }
|
|
138
|
+
static fromSec(value) { return this._mapBySec[value]; }
|
|
139
|
+
static createCustomFromSec(sec) { return TF.constructFromSec(sec); }
|
|
140
|
+
static createCustom(unit, unitCount) { return new TF(unit, unitCount, -1); }
|
|
141
|
+
static all = function () {
|
|
142
|
+
let i = 1;
|
|
143
|
+
let arr = [];
|
|
144
|
+
for (let key of GetEnumKeys(__E_TF)) {
|
|
145
|
+
arr[__E_TF[key]] = TF.constructFromSec(__Tf_S[i], key);
|
|
146
|
+
i++;
|
|
147
|
+
}
|
|
148
|
+
return arr;
|
|
149
|
+
}();
|
|
150
|
+
static _mapBySec = function () {
|
|
151
|
+
let map = {};
|
|
152
|
+
for (let i of __Tf_S.keys())
|
|
153
|
+
map[__Tf_S[i]] = TF.all[i];
|
|
154
|
+
return map;
|
|
155
|
+
}();
|
|
156
|
+
static S1 = TF.get("S1");
|
|
157
|
+
static S2 = TF.get("S2");
|
|
158
|
+
static S3 = TF.get("S3");
|
|
159
|
+
static S4 = TF.get("S4");
|
|
160
|
+
static S5 = TF.get("S5");
|
|
161
|
+
static S6 = TF.get("S6");
|
|
162
|
+
static S10 = TF.get("S10");
|
|
163
|
+
static S12 = TF.get("S12");
|
|
164
|
+
static S15 = TF.get("S15");
|
|
165
|
+
static S20 = TF.get("S20");
|
|
166
|
+
static S30 = TF.get("S30");
|
|
167
|
+
static M1 = TF.get("M1");
|
|
168
|
+
static M2 = TF.get("M2");
|
|
169
|
+
static M3 = TF.get("M3");
|
|
170
|
+
static M4 = TF.get("M4");
|
|
171
|
+
static M5 = TF.get("M5");
|
|
172
|
+
static M6 = TF.get("M6");
|
|
173
|
+
static M10 = TF.get("M10");
|
|
174
|
+
static M12 = TF.get("M12");
|
|
175
|
+
static M15 = TF.get("M15");
|
|
176
|
+
static M20 = TF.get("M20");
|
|
177
|
+
static M30 = TF.get("M30");
|
|
178
|
+
static H1 = TF.get("H1");
|
|
179
|
+
static H2 = TF.get("H2");
|
|
180
|
+
static H3 = TF.get("H3");
|
|
181
|
+
static H4 = TF.get("H4");
|
|
182
|
+
static H6 = TF.get("H6");
|
|
183
|
+
static H8 = TF.get("H8");
|
|
184
|
+
static H12 = TF.get("H12");
|
|
185
|
+
static D1 = TF.get("D1");
|
|
186
|
+
static W1 = TF.get("W1");
|
|
187
|
+
static MN1 = TF.get("MN1");
|
|
188
|
+
static MN2 = TF.get("MN2");
|
|
189
|
+
static MN3 = TF.get("MN3");
|
|
190
|
+
static MN4 = TF.get("MN4");
|
|
191
|
+
static MN6 = TF.get("MN6");
|
|
192
|
+
static Y1 = TF.get("Y1");
|
|
193
|
+
static min(...args) {
|
|
194
|
+
let tfs = ((args[0] && !(args[0] instanceof TF)) ? args[0] : args);
|
|
195
|
+
let index = 999;
|
|
196
|
+
for (let tf of tfs)
|
|
197
|
+
if (tf)
|
|
198
|
+
index = Math.min(tf.index, index);
|
|
199
|
+
return index != 999 ? this.all[index] : null;
|
|
200
|
+
}
|
|
201
|
+
static max(...args) {
|
|
202
|
+
let tfs = ((args[0] && !(args[0] instanceof TF)) ? args[0] : args);
|
|
203
|
+
let index = -1;
|
|
204
|
+
for (let tf of tfs)
|
|
205
|
+
if (tf)
|
|
206
|
+
index = Math.max(tf.index, index);
|
|
207
|
+
return index != -1 ? this.all[index] : null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
exports.TF = TF;
|
|
211
|
+
function TimeAddMilliseconds(time, shift) { return new Date(time.valueOf() + shift); }
|
|
212
|
+
class MyDate extends Date {
|
|
213
|
+
ToShiftedMsTime(shiftMs) { return TimeAddMilliseconds(this, shiftMs); }
|
|
214
|
+
}
|
|
215
|
+
class PeriodSpan {
|
|
216
|
+
period;
|
|
217
|
+
index;
|
|
218
|
+
constructor(period, indexOrTime) {
|
|
219
|
+
this.period = period instanceof Period ? period : new Period(period);
|
|
220
|
+
this.index = indexOrTime instanceof Date ? this.period.IndexFromTime(indexOrTime) : indexOrTime;
|
|
221
|
+
}
|
|
222
|
+
next() { return new PeriodSpan(this.period, this.index + 1); }
|
|
223
|
+
prev() { return new PeriodSpan(this.period, this.index - 1); }
|
|
224
|
+
get startTime() { return Period.StartTimeForIndex(this.period.tf, this.index); }
|
|
225
|
+
get endTime() { return Period.StartTimeForIndex(this.period.tf, this.index + 1).ToShiftedMsTime(-1); }
|
|
226
|
+
}
|
|
227
|
+
exports.PeriodSpan = PeriodSpan;
|
|
228
|
+
class Period {
|
|
229
|
+
tf;
|
|
230
|
+
get sec() { return this.tf.sec; }
|
|
231
|
+
get msec() { return this.tf.msec; }
|
|
232
|
+
get name() { return this.tf.name; }
|
|
233
|
+
valueOf() { return this.msec; }
|
|
234
|
+
span(time) { return new PeriodSpan(this.tf, time); }
|
|
235
|
+
constructor(tf) { this.tf = tf; return (0, common_1.CreateArrayProxy)(this, (i) => new PeriodSpan(tf, i)); }
|
|
236
|
+
static Seconds(tf) { return tf.sec; }
|
|
237
|
+
static Name(tf) { return tf.name; }
|
|
238
|
+
IndexFromTime(time) {
|
|
239
|
+
return Period.IndexFromTime(this.tf, time);
|
|
240
|
+
}
|
|
241
|
+
getStartTime(currentTime) { return Period.StartTime(this.tf, currentTime); }
|
|
242
|
+
static getW1Shift_ms() {
|
|
243
|
+
const day0 = new Date(0).getUTCDay();
|
|
244
|
+
const tshift = exports.D1_MS * Math.trunc((day0 + 6) % 7);
|
|
245
|
+
return tshift;
|
|
246
|
+
}
|
|
247
|
+
static W1Shift_ms = this.getW1Shift_ms();
|
|
248
|
+
static year0 = new Date(0).getUTCFullYear();
|
|
249
|
+
static IndexFromTime(tf, time) {
|
|
250
|
+
const tf_msec = tf.msec;
|
|
251
|
+
if (tf.unit == TIME_UNIT.Week) {
|
|
252
|
+
return Math.floor((time.valueOf() + Period.W1Shift_ms) / tf_msec);
|
|
253
|
+
}
|
|
254
|
+
if (tf.unit == TIME_UNIT.Month) {
|
|
255
|
+
return Math.floor(((time.getFullYear() - Period.year0) * 12 + time.getMonth()) / tf.unitCount);
|
|
256
|
+
}
|
|
257
|
+
if (tf.unit == TIME_UNIT.Year) {
|
|
258
|
+
return time.getFullYear() - Period.year0;
|
|
259
|
+
}
|
|
260
|
+
return Math.floor(time.valueOf() / tf_msec);
|
|
261
|
+
}
|
|
262
|
+
static StartTimeForIndex(tf, index) {
|
|
263
|
+
const tf_msec = tf.msec;
|
|
264
|
+
if (tf.unit == TIME_UNIT.Week) {
|
|
265
|
+
return new MyDate(index * tf_msec - this.getW1Shift_ms());
|
|
266
|
+
}
|
|
267
|
+
if (tf.unit == TIME_UNIT.Month) {
|
|
268
|
+
return new MyDate(Period.year0 + Math.floor(index * tf.unitCount / 12), Math.floor(index * tf.unitCount % 12), 1);
|
|
269
|
+
}
|
|
270
|
+
if (tf.unit == TIME_UNIT.Year)
|
|
271
|
+
return new MyDate(Period.year0 + index, 0, 1);
|
|
272
|
+
return new MyDate(index * tf_msec);
|
|
273
|
+
}
|
|
274
|
+
static StartTime(tf, currentTime, shiftPeriods = 0) {
|
|
275
|
+
let index = this.IndexFromTime(tf, currentTime) + shiftPeriods;
|
|
276
|
+
return this.StartTimeForIndex(tf, index);
|
|
277
|
+
}
|
|
278
|
+
static EndTime(tf, currentTime) { return this.StartTime(tf, currentTime, +1).ToShiftedMsTime(-1); }
|
|
279
|
+
}
|
|
280
|
+
exports.Period = Period;
|
|
281
|
+
function str2(n) { return n <= 9 ? '0' + n : '' + n; }
|
|
282
|
+
function str3(n) { return (n <= 9 ? '00' : n <= 99 ? '0' : '') + n; }
|
|
283
|
+
function timeToStr_hhmmss_ms(date) { return str2(date.getUTCHours()) + ":" + str2(date.getUTCMinutes()) + ":" + str2(date.getUTCSeconds()) + "." + str3(date.getUTCMilliseconds()); }
|
|
284
|
+
function timeToStr_hhmmss(date) { return str2(date.getUTCHours()) + ":" + str2(date.getUTCMinutes()) + ":" + str2(date.getUTCSeconds()); }
|
|
285
|
+
function timeToStr_yyyymmdd_hhmm(date, dateDelim = "-") { return date.getUTCFullYear() + dateDelim + str2(date.getUTCMonth() + 1) + dateDelim + str2(date.getUTCDate()) + " " + str2(date.getUTCHours()) + ":" + str2(date.getUTCMinutes()); }
|
|
286
|
+
function timeToStr_yyyymmdd_hhmmss(date, dateDelim = "-") { return timeToStr_yyyymmdd_hhmm(date, dateDelim) + ":" + str2(date.getUTCSeconds()); }
|
|
287
|
+
function timeToStr_yyyymmdd_hhmmss_ms(date, dateDelim = "-") { return timeToStr_yyyymmdd_hhmmss(date, dateDelim) + "." + str3(date.getUTCMilliseconds()); }
|
|
288
|
+
function timeLocalToStr_hhmmss(date) { return str2(date.getHours()) + ":" + str2(date.getMinutes()) + ":" + str2(date.getSeconds()); }
|
|
289
|
+
function timeLocalToStr_hhmmss_ms(date) { return timeLocalToStr_hhmmss(date) + str3(date.getMilliseconds()); }
|
|
290
|
+
function timeLocalToStr_yyyymmdd(date, dateDelim = "-") { return date.getFullYear() + dateDelim + str2(date.getMonth() + 1) + dateDelim + str2(date.getDate()); }
|
|
291
|
+
function timeLocalToStr_yyyymmdd_hhmm(date, dateDelim = "-") { return timeLocalToStr_yyyymmdd(date, dateDelim) + " " + str2(date.getHours()) + ":" + str2(date.getMinutes()); }
|
|
292
|
+
function timeLocalToStr_yyyymmdd_hhmmss(date, dateDelim = "-") { return timeLocalToStr_yyyymmdd_hhmm(date, dateDelim) + ":" + str2(date.getSeconds()); }
|
|
293
|
+
function timeLocalToStr_yyyymmdd_hhmmss_ms(date, dateDelim = "-") { return timeLocalToStr_yyyymmdd_hhmmss(date, dateDelim) + "." + str3(date.getMilliseconds()); }
|
|
294
|
+
function timeToString_yyyymmdd_hhmm_offset(date) { let offset = date.getTimezoneOffset(); return timeLocalToStr_yyyymmdd_hhmm(date) + " GMT" + (offset < 0 ? '+' : '') + (-offset / 60); }
|
|
295
|
+
function timeToString_yyyymmdd_hhmmss_offset(date) { let offset = date.getTimezoneOffset(); return timeLocalToStr_yyyymmdd_hhmmss(date) + " GMT" + (offset < 0 ? '+' : '') + (-offset / 60); }
|
|
296
|
+
Date.prototype.toString = function () { return timeToString_yyyymmdd_hhmmss_offset(this); };
|
|
297
|
+
Date.prototype.toDateString = function () { return timeLocalToStr_yyyymmdd(this); };
|
|
298
|
+
Date.prototype.toTimeString = function () { let offset = this.getTimezoneOffset(); return timeLocalToStr_hhmmss(this) + " GMT" + (offset < 0 ? '+' : '') + (-offset / 60); };
|
|
299
|
+
function _getStructCopyWithTimeStrings(arg, objectsMap) {
|
|
300
|
+
if (!arg)
|
|
301
|
+
return arg;
|
|
302
|
+
if (arg instanceof Date)
|
|
303
|
+
return arg.toString();
|
|
304
|
+
let clone;
|
|
305
|
+
if (Object.getPrototypeOf(arg) == Object.prototype)
|
|
306
|
+
clone = {};
|
|
307
|
+
else if (Object.getPrototypeOf(arg) == Array.prototype) {
|
|
308
|
+
clone = [];
|
|
309
|
+
}
|
|
310
|
+
else
|
|
311
|
+
return arg;
|
|
312
|
+
let mapVal = objectsMap?.get(arg);
|
|
313
|
+
if (mapVal)
|
|
314
|
+
return mapVal;
|
|
315
|
+
objectsMap ??= new Map();
|
|
316
|
+
objectsMap.set(arg, clone);
|
|
317
|
+
for (let key in arg)
|
|
318
|
+
clone[key] = _getStructCopyWithTimeStrings(arg[key], objectsMap);
|
|
319
|
+
return clone;
|
|
320
|
+
}
|
|
321
|
+
function convertDatesToStrings(arg) { return _getStructCopyWithTimeStrings(arg); }
|
|
322
|
+
function toPrintObject(arg) { return convertDatesToStrings(arg); }
|
|
323
|
+
function replaceConsoleCommands() {
|
|
324
|
+
const consoleLog = console.log;
|
|
325
|
+
const consoleWarn = console.warn;
|
|
326
|
+
const consoleError = console.error;
|
|
327
|
+
function replaceArgs(args) { return args.map(arg => convertDatesToStrings(arg)); }
|
|
328
|
+
console.log = (...args) => { consoleLog(...replaceArgs(args)); };
|
|
329
|
+
console.warn = (...args) => { consoleWarn(...replaceArgs(args)); };
|
|
330
|
+
console.error = (...args) => { consoleError(...replaceArgs(args)); };
|
|
331
|
+
}
|
|
332
|
+
function durationToStr(duration_ms) {
|
|
333
|
+
let units = [[exports.D1_MS, "д"], [exports.H1_MS, "ч"], [exports.M1_MS, "м"], [1000, "c"], [1, "мс"]];
|
|
334
|
+
let lastUnit = null;
|
|
335
|
+
let str = "";
|
|
336
|
+
for (let unit of units) {
|
|
337
|
+
let unitCountFloat = duration_ms / unit[0];
|
|
338
|
+
if (unitCountFloat < 1.1 && lastUnit == null)
|
|
339
|
+
continue;
|
|
340
|
+
let unitCount;
|
|
341
|
+
if (lastUnit || unitCountFloat > 10) {
|
|
342
|
+
unitCount = Math.round(unitCountFloat);
|
|
343
|
+
lastUnit = unit;
|
|
344
|
+
}
|
|
345
|
+
else
|
|
346
|
+
unitCount = Math.floor(unitCountFloat);
|
|
347
|
+
str += unitCount + unit[1] + " ";
|
|
348
|
+
if (lastUnit)
|
|
349
|
+
break;
|
|
350
|
+
duration_ms %= unit[0];
|
|
351
|
+
lastUnit = unit;
|
|
352
|
+
}
|
|
353
|
+
return str;
|
|
354
|
+
}
|
|
355
|
+
function durationToStrNullable(duration_ms) { return duration_ms == null ? null : durationToStr(duration_ms); }
|
|
356
|
+
function durationToStr_h_mm_ss(duration_ms) {
|
|
357
|
+
let time = new Date(duration_ms);
|
|
358
|
+
return Math.trunc(duration_ms / exports.H1_MS) + ":" + str2(time.getUTCMinutes()) + ":" + str2(time.getUTCSeconds());
|
|
359
|
+
}
|
|
360
|
+
function durationToStr_h_mm_ss_ms(duration_ms) { return durationToStr_h_mm_ss(duration_ms) + "." + str3(Math.trunc(duration_ms % 1000)); }
|
|
361
|
+
async function sleepAsync(msec) {
|
|
362
|
+
return new Promise((resolve, reject) => { setTimeout(resolve, msec); });
|
|
363
|
+
}
|
|
364
|
+
class CDelayer {
|
|
365
|
+
remainPause = 0;
|
|
366
|
+
async sleepAsync(pause_ms_getter) {
|
|
367
|
+
let passed_ms = 0;
|
|
368
|
+
let startRemainPause = this.remainPause;
|
|
369
|
+
while (true) {
|
|
370
|
+
let pause = pause_ms_getter();
|
|
371
|
+
if (pause == null || pause < 0)
|
|
372
|
+
return;
|
|
373
|
+
this.remainPause = Math.max(startRemainPause + pause - passed_ms, 0);
|
|
374
|
+
pause = Math.min(this.remainPause, 100);
|
|
375
|
+
if (pause > 15) {
|
|
376
|
+
let oldTime = Date.now();
|
|
377
|
+
await sleepAsync(pause);
|
|
378
|
+
let duration = Date.now() - oldTime;
|
|
379
|
+
passed_ms += duration;
|
|
380
|
+
this.remainPause -= duration;
|
|
381
|
+
}
|
|
382
|
+
else
|
|
383
|
+
break;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
exports.CDelayer = CDelayer;
|
|
388
|
+
function MinTime(time1, time2) {
|
|
389
|
+
return time1 && time2 && time1.valueOf() <= time2.valueOf() ? time1 : time2 ?? time1;
|
|
390
|
+
}
|
|
391
|
+
function MaxTime(time1, time2) {
|
|
392
|
+
return time1 && time2 && time1.valueOf() >= time2.valueOf() ? time1 : time2 ?? time1;
|
|
393
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Express } from 'express';
|
|
2
|
+
interface Subscriber {
|
|
3
|
+
url: string;
|
|
4
|
+
tag: string;
|
|
5
|
+
expireAt: Date;
|
|
6
|
+
}
|
|
7
|
+
interface WebhookClientOptions {
|
|
8
|
+
serverUrl: string;
|
|
9
|
+
clientPort: number;
|
|
10
|
+
authToken: string;
|
|
11
|
+
autoRenew?: boolean;
|
|
12
|
+
renewIntervalMs?: number;
|
|
13
|
+
app?: Express;
|
|
14
|
+
}
|
|
15
|
+
export declare const apiSaveData: {
|
|
16
|
+
loadSubscribers: () => Map<string, Subscriber>;
|
|
17
|
+
saveSubscribers: (subs: Map<string, Subscriber>) => void;
|
|
18
|
+
};
|
|
19
|
+
type params = {
|
|
20
|
+
authToken: string;
|
|
21
|
+
port: number | string;
|
|
22
|
+
file?: typeof apiSaveData;
|
|
23
|
+
app?: Express;
|
|
24
|
+
};
|
|
25
|
+
export declare const createWebhookServer: (params: params) => {
|
|
26
|
+
emit: (tag: string, payload: any) => Promise<void>;
|
|
27
|
+
appServerReady: Promise<void>;
|
|
28
|
+
};
|
|
29
|
+
export declare const createWebhookClient: (options: WebhookClientOptions) => {
|
|
30
|
+
connect: (tag: string, handler: (payload: any) => void) => Promise<void>;
|
|
31
|
+
unsubscribe: (...tags: string[]) => Promise<void>;
|
|
32
|
+
status: (tag: string) => Promise<import("axios").AxiosResponse<any, any, {}>>;
|
|
33
|
+
tags: () => string[];
|
|
34
|
+
getMySubscriptions: () => Promise<Subscriber[]>;
|
|
35
|
+
getAvailableTags: () => Promise<string[]>;
|
|
36
|
+
Provider: (tag: string, payload: any) => Promise<void>;
|
|
37
|
+
appServerReady: Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.createWebhookClient = exports.createWebhookServer = exports.apiSaveData = void 0;
|
|
40
|
+
const express_1 = __importDefault(require("express"));
|
|
41
|
+
const axios_1 = __importDefault(require("axios"));
|
|
42
|
+
const fs = __importStar(require("fs"));
|
|
43
|
+
const waitRun_1 = require("./async/waitRun");
|
|
44
|
+
const SUBSCRIBERS_FILE = './subscribers.json';
|
|
45
|
+
const loadSubscribers = () => {
|
|
46
|
+
try {
|
|
47
|
+
if (!fs.existsSync(SUBSCRIBERS_FILE))
|
|
48
|
+
fs.writeFileSync(SUBSCRIBERS_FILE, '{}', 'utf-8');
|
|
49
|
+
const data = JSON.parse(fs.readFileSync(SUBSCRIBERS_FILE, 'utf-8'));
|
|
50
|
+
return new Map(Object.entries(data).map(([k, s]) => [k, { url: s.url, tag: s.tag ?? s.tags, expireAt: new Date(s.expireAt) }]));
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
console.error('Ошибка загрузки подписчиков, файл сброшен:', e);
|
|
54
|
+
fs.writeFileSync(SUBSCRIBERS_FILE, '{}', 'utf-8');
|
|
55
|
+
return new Map();
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
const Queue = (0, waitRun_1.createAsyncQueue)(1);
|
|
59
|
+
const saveSubscribers = (subs) => {
|
|
60
|
+
const obj = Object.fromEntries([...subs].map(([k, s]) => [k, { url: s.url, tag: s.tag, expireAt: s.expireAt }]));
|
|
61
|
+
Queue.enqueue(() => fs.promises.writeFile(SUBSCRIBERS_FILE, JSON.stringify(obj, null, 2), 'utf-8'));
|
|
62
|
+
};
|
|
63
|
+
const normalizeIP = (ip) => ip?.startsWith('::ffff:') ? ip.slice(7) : ip;
|
|
64
|
+
exports.apiSaveData = { loadSubscribers, saveSubscribers };
|
|
65
|
+
const createWebhookServer = (params) => {
|
|
66
|
+
const app = params.app ?? (0, express_1.default)();
|
|
67
|
+
if (!params.app)
|
|
68
|
+
app.use(express_1.default.json());
|
|
69
|
+
const file = params.file ?? exports.apiSaveData;
|
|
70
|
+
const { authToken, port } = params;
|
|
71
|
+
const subscribers = file.loadSubscribers();
|
|
72
|
+
const checkAuth = (req, res, next) => {
|
|
73
|
+
if (req.headers.authorization !== authToken) {
|
|
74
|
+
res.status(403).json({ error: 'Недействительный токен авторизации' });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
next();
|
|
78
|
+
};
|
|
79
|
+
const clientAddr = (req) => 'http://' + normalizeIP(req.ip ?? '127.0.0.1');
|
|
80
|
+
const purgeExpired = () => {
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
let changed = false;
|
|
83
|
+
subscribers.forEach((s, k) => { if (s.expireAt.getTime() <= now) {
|
|
84
|
+
subscribers.delete(k);
|
|
85
|
+
changed = true;
|
|
86
|
+
} });
|
|
87
|
+
if (changed)
|
|
88
|
+
file.saveSubscribers(subscribers);
|
|
89
|
+
};
|
|
90
|
+
const renewExpiry = () => new Date(Date.now() + 3 * 24 * 3600_000);
|
|
91
|
+
app.post('/webHook_subscribe', checkAuth, (req, res) => {
|
|
92
|
+
const { tag } = req.body;
|
|
93
|
+
if (!req.body.url || typeof req.body.url !== 'string' || typeof tag !== 'string') {
|
|
94
|
+
res.status(400).json({ error: 'Неверный запрос' });
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
purgeExpired();
|
|
98
|
+
const url = new URL(clientAddr(req) + req.body.url).toString();
|
|
99
|
+
subscribers.set(url, { url, tag, expireAt: renewExpiry() });
|
|
100
|
+
file.saveSubscribers(subscribers);
|
|
101
|
+
res.json({ message: 'Подписка оформлена' });
|
|
102
|
+
});
|
|
103
|
+
app.get('/webHook_status', checkAuth, (req, res) => {
|
|
104
|
+
const rawUrl = req.query['url'];
|
|
105
|
+
if (!rawUrl || typeof rawUrl !== 'string') {
|
|
106
|
+
res.status(400).json({ error: 'Неверный запрос' });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
purgeExpired();
|
|
110
|
+
const url = new URL(clientAddr(req) + rawUrl).toString();
|
|
111
|
+
const subscriber = Array.from(subscribers.values()).find(s => s.url === url);
|
|
112
|
+
if (!subscriber) {
|
|
113
|
+
res.json({ subscribed: false });
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
subscriber.expireAt = renewExpiry();
|
|
117
|
+
file.saveSubscribers(subscribers);
|
|
118
|
+
res.json({ subscribed: true, expireAt: subscriber.expireAt });
|
|
119
|
+
});
|
|
120
|
+
app.delete('/webHook_unsubscribe', checkAuth, (req, res) => {
|
|
121
|
+
const url = new URL(clientAddr(req) + req.body.url).toString();
|
|
122
|
+
const key = Array.from(subscribers.keys()).find(k => subscribers.get(k)?.url === url);
|
|
123
|
+
if (key && subscribers.delete(key)) {
|
|
124
|
+
file.saveSubscribers(subscribers);
|
|
125
|
+
res.json({ message: 'Подписка удалена' });
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
res.status(404).json({ error: 'Подписчик не найден' });
|
|
129
|
+
});
|
|
130
|
+
const emit = async (tag, payload) => {
|
|
131
|
+
purgeExpired();
|
|
132
|
+
const valid = Array.from(subscribers.values()).filter(s => s.tag === tag);
|
|
133
|
+
await Promise.all(valid.map(s => axios_1.default.post(s.url, payload).catch(() => console.error("emit fail:", s.url))));
|
|
134
|
+
};
|
|
135
|
+
app.post('/webHook_notify', checkAuth, async (req, res) => {
|
|
136
|
+
await emit(req.body.tag, req.body.payload);
|
|
137
|
+
res.json({ message: 'Webhook отправлен активным подписчикам' });
|
|
138
|
+
});
|
|
139
|
+
app.get('/webHook_client_subscriptions', checkAuth, (req, res) => {
|
|
140
|
+
purgeExpired();
|
|
141
|
+
const addr = clientAddr(req);
|
|
142
|
+
res.json(Array.from(subscribers.values()).filter(s => s.url.startsWith(addr)));
|
|
143
|
+
});
|
|
144
|
+
app.get('/webHook_all_tags', checkAuth, (_req, res) => {
|
|
145
|
+
purgeExpired();
|
|
146
|
+
res.json({ tags: [...new Set(Array.from(subscribers.values()).map(s => s.tag))] });
|
|
147
|
+
});
|
|
148
|
+
const appServerReady = new Promise(r => { if (!params.app)
|
|
149
|
+
app.listen(port, () => r());
|
|
150
|
+
else
|
|
151
|
+
r(); });
|
|
152
|
+
return { emit, appServerReady };
|
|
153
|
+
};
|
|
154
|
+
exports.createWebhookServer = createWebhookServer;
|
|
155
|
+
const createWebhookClient = (options) => {
|
|
156
|
+
const { app: app_, serverUrl, clientPort, authToken, autoRenew = false, renewIntervalMs = 86400000 } = options;
|
|
157
|
+
const app = app_ ?? (0, express_1.default)();
|
|
158
|
+
if (!app_)
|
|
159
|
+
app.use(express_1.default.json());
|
|
160
|
+
const activeTags = new Set();
|
|
161
|
+
const timers = new Map();
|
|
162
|
+
const headers = { authorization: authToken };
|
|
163
|
+
const makeUrl = (tag) => `:${clientPort}/webHook_${tag}`;
|
|
164
|
+
const connect = async (tag, handler) => {
|
|
165
|
+
if (activeTags.has(tag)) {
|
|
166
|
+
console.warn(`Тег ${tag} уже подписан`);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const path = `/webHook_${tag}`;
|
|
170
|
+
app.post(path, (req, res) => { handler(req.body); res.end(); });
|
|
171
|
+
await axios_1.default.post(`${serverUrl}/webHook_subscribe`, { url: makeUrl(tag), tag }, { headers });
|
|
172
|
+
activeTags.add(tag);
|
|
173
|
+
if (autoRenew) {
|
|
174
|
+
timers.set(tag, setInterval(() => {
|
|
175
|
+
axios_1.default.get(`${serverUrl}/webHook_status`, { params: { url: makeUrl(tag) }, headers }).catch(() => console.error("renew fail:", tag));
|
|
176
|
+
}, renewIntervalMs));
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
const status = async (tag) => axios_1.default.get(`${serverUrl}/webHook_status`, { params: { url: makeUrl(tag) }, headers });
|
|
180
|
+
const unsubscribe = async (...tags) => {
|
|
181
|
+
const arr = tags.length ? tags : [...activeTags];
|
|
182
|
+
await Promise.all(arr.map(async (tag) => {
|
|
183
|
+
await axios_1.default.delete(`${serverUrl}/webHook_unsubscribe`, { data: { url: makeUrl(tag) }, headers }).catch(e => console.error("unsub fail:", tag, e.message));
|
|
184
|
+
activeTags.delete(tag);
|
|
185
|
+
const t = timers.get(tag);
|
|
186
|
+
if (t) {
|
|
187
|
+
clearInterval(t);
|
|
188
|
+
timers.delete(tag);
|
|
189
|
+
}
|
|
190
|
+
const stack = app._router?.stack;
|
|
191
|
+
if (stack) {
|
|
192
|
+
const path = `/webHook_${tag}`;
|
|
193
|
+
const idx = stack.findIndex((layer) => layer.route?.path === path);
|
|
194
|
+
if (idx !== -1)
|
|
195
|
+
stack.splice(idx, 1);
|
|
196
|
+
}
|
|
197
|
+
}));
|
|
198
|
+
};
|
|
199
|
+
const getMySubscriptions = async () => (await axios_1.default.get(`${serverUrl}/webHook_client_subscriptions`, { headers })).data;
|
|
200
|
+
const getAvailableTags = async () => (await axios_1.default.get(`${serverUrl}/webHook_all_tags`, { headers })).data.tags;
|
|
201
|
+
const tags = () => [...activeTags];
|
|
202
|
+
const Provider = async (tag, payload) => {
|
|
203
|
+
await axios_1.default.post(`${serverUrl}/webHook_notify`, { tag, payload }, { headers });
|
|
204
|
+
};
|
|
205
|
+
const appServerReady = new Promise(r => { if (!app_)
|
|
206
|
+
app.listen(clientPort, () => r());
|
|
207
|
+
else
|
|
208
|
+
r(); });
|
|
209
|
+
return { connect, unsubscribe, status, tags, getMySubscriptions, getAvailableTags, Provider, appServerReady };
|
|
210
|
+
};
|
|
211
|
+
exports.createWebhookClient = createWebhookClient;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function PromiseArrayListen<T extends any = unknown>(array: ((() => Promise<T>) | (() => any) | Promise<T>)[]): {
|
|
2
|
+
listenOk: (a: (...d: [data: T, i: number, countOk: number, countError: number, count: number]) => any) => () => void;
|
|
3
|
+
listenError: (a: (...d: [error: any, i: number, countOk: number, countError: number, count: number]) => any) => () => void;
|
|
4
|
+
promise: {
|
|
5
|
+
all: () => Promise<(void | (() => Promise<void>))[]>;
|
|
6
|
+
allSettled: () => Promise<PromiseSettledResult<void | (() => Promise<void>)>[]>;
|
|
7
|
+
};
|
|
8
|
+
getData(): (Promise<void> | (() => Promise<void>))[];
|
|
9
|
+
status(): {
|
|
10
|
+
ok: number;
|
|
11
|
+
error: number;
|
|
12
|
+
count: number;
|
|
13
|
+
};
|
|
14
|
+
};
|