wenay-common2 1.0.45 → 1.0.48

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.
Files changed (95) hide show
  1. package/lib/Common/Color.d.ts +3 -0
  2. package/lib/Common/Color.js +11 -3
  3. package/lib/Common/ObserveAll2/reactive2.d.ts +32 -0
  4. package/lib/Common/ObserveAll2/reactive2.js +249 -0
  5. package/lib/Common/Time.d.ts +8 -0
  6. package/lib/Common/Time.js +41 -14
  7. package/lib/Common/async/PromiseArrayListen.d.ts +3 -3
  8. package/lib/Common/async/PromiseArrayListen.js +10 -14
  9. package/lib/Common/async/createIterableObject.js +2 -2
  10. package/lib/Common/async/waitRun.d.ts +12 -5
  11. package/lib/Common/async/waitRun.js +75 -45
  12. package/lib/Common/core/Decorator.d.ts +3 -1
  13. package/lib/Common/core/Decorator.js +7 -3
  14. package/lib/Common/core/DeepCompareKeys.js +4 -0
  15. package/lib/Common/core/MemoFunc.js +2 -2
  16. package/lib/Common/core/common.d.ts +25 -7
  17. package/lib/Common/core/common.js +118 -38
  18. package/lib/Common/data/ByteStream.d.ts +1 -1
  19. package/lib/Common/data/ByteStream.js +31 -27
  20. package/lib/Common/data/List.d.ts +6 -1
  21. package/lib/Common/data/List.js +28 -6
  22. package/lib/Common/data/ListNodeAnd.js +3 -3
  23. package/lib/Common/data/objectPath.d.ts +4 -0
  24. package/lib/Common/data/objectPath.js +8 -3
  25. package/lib/Common/events/Listen.d.ts +38 -5
  26. package/lib/Common/events/Listen.js +89 -54
  27. package/lib/Common/events/SocketBuffer.d.ts +9 -4
  28. package/lib/Common/events/SocketBuffer.js +1 -0
  29. package/lib/Common/events/SocketServerHook.d.ts +20 -7
  30. package/lib/Common/events/SocketServerHook.js +2 -1
  31. package/lib/Common/events/UseListenTransform.d.ts +8 -3
  32. package/lib/Common/events/event.d.ts +12 -0
  33. package/lib/Common/events/event.js +27 -12
  34. package/lib/Common/events/joinListens.d.ts +2 -0
  35. package/lib/Common/events/joinListens.js +20 -12
  36. package/lib/Common/funcTimeWait.d.ts +28 -2
  37. package/lib/Common/funcTimeWait.js +20 -21
  38. package/lib/Common/id-pool.js +12 -2
  39. package/lib/Common/inputAutoStep.js +2 -2
  40. package/lib/Common/isProxy.d.ts +1 -0
  41. package/lib/Common/isProxy.js +2 -0
  42. package/lib/Common/math/Math.d.ts +1 -0
  43. package/lib/Common/math/Math.js +7 -1
  44. package/lib/Common/math/other.js +2 -1
  45. package/lib/Common/math/scoreLana.js +3 -2
  46. package/lib/Common/node_console.d.ts +2 -0
  47. package/lib/Common/node_console.js +3 -76
  48. package/lib/Common/rcp/createRpcServerAutoWithProtocolDetection.d.ts +2 -0
  49. package/lib/Common/rcp/createRpcServerAutoWithProtocolDetection.js +63 -30
  50. package/lib/Common/rcp/listen-deep.d.ts +13 -5
  51. package/lib/Common/rcp/listen-deep.js +1 -6
  52. package/lib/Common/rcp/listen-socket.d.ts +21 -3
  53. package/lib/Common/rcp/listen-socket.js +97 -6
  54. package/lib/Common/rcp/oldCommonsServer.d.ts +1 -1
  55. package/lib/Common/rcp/oldCommonsServer.js +15 -1
  56. package/lib/Common/rcp/old/320/241ommonsServerMini.js +1 -0
  57. package/lib/Common/rcp/rpc-caps.d.ts +10 -0
  58. package/lib/Common/rcp/rpc-caps.js +16 -0
  59. package/lib/Common/rcp/rpc-client.d.ts +23 -1
  60. package/lib/Common/rcp/rpc-client.js +306 -25
  61. package/lib/Common/rcp/rpc-clientHub.d.ts +7 -1
  62. package/lib/Common/rcp/rpc-clientHub.js +25 -2
  63. package/lib/Common/rcp/rpc-index.d.ts +3 -0
  64. package/lib/Common/rcp/rpc-index.js +3 -0
  65. package/lib/Common/rcp/rpc-inproc.d.ts +17 -0
  66. package/lib/Common/rcp/rpc-inproc.js +30 -0
  67. package/lib/Common/rcp/rpc-off.d.ts +10 -0
  68. package/lib/Common/rcp/rpc-off.js +22 -0
  69. package/lib/Common/rcp/rpc-protocol.d.ts +6 -0
  70. package/lib/Common/rcp/rpc-protocol.js +4 -2
  71. package/lib/Common/rcp/rpc-server-auto.d.ts +14 -3
  72. package/lib/Common/rcp/rpc-server-auto.js +81 -6
  73. package/lib/Common/rcp/rpc-server.d.ts +17 -2
  74. package/lib/Common/rcp/rpc-server.js +127 -31
  75. package/lib/Common/rcp/rpc-shape.d.ts +17 -0
  76. package/lib/Common/rcp/rpc-shape.js +42 -0
  77. package/lib/Common/rcp/rpc-walk.js +29 -11
  78. package/lib/Common/rcp/test.d.ts +1 -0
  79. package/lib/Common/rcp/test.js +78 -0
  80. package/lib/Exchange/Bars.d.ts +3 -0
  81. package/lib/Exchange/Bars.js +9 -4
  82. package/lib/Exchange/CParams.d.ts +2 -0
  83. package/lib/Exchange/CParams.js +22 -15
  84. package/lib/Exchange/MarketData.d.ts +6 -0
  85. package/lib/Exchange/MarketData.js +5 -1
  86. package/lib/index.d.ts +1 -0
  87. package/lib/index.js +2 -1
  88. package/lib/server/WebHook3.d.ts +1 -0
  89. package/lib/server/WebHook3.js +45 -16
  90. package/lib/server/fsKeyVolume.js +20 -3
  91. package/lib/toError/myThrow.d.ts +20 -1
  92. package/lib/toError/myThrow.js +32 -19
  93. package/package.json +2 -1
  94. package/lib/Common/Error/myThrow.d.ts +0 -5
  95. package/lib/Common/Error/myThrow.js +0 -23
@@ -36,7 +36,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
36
36
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.CTimeSeries = exports.CTimeSeriesBase = exports.CBarsMutableExt = exports.CBarsMutable = exports.CBarsMutableBase = exports.CBars = exports.CBarsBase = exports.IBars = exports.CTick = exports.CBar = exports.CBarBase = exports.OHLC = void 0;
39
+ exports.CTimeSeries = exports.CTimeSeriesBase = exports.createRandomBars = exports.CBarsMutableExt = exports.CBarsMutable = exports.CBarsMutableBase = exports.CBars = exports.CBarsBase = exports.IBars = exports.CTick = exports.CBar = exports.CBarBase = exports.OHLC = void 0;
40
40
  exports.CreateRandomBars = CreateRandomBars;
41
41
  exports.findBarsShallow = findBarsShallow;
42
42
  const lib = __importStar(require("../Common/core/common"));
@@ -159,7 +159,7 @@ class IBars {
159
159
  return;
160
160
  let ibar = timeStart ? this.indexOf(timeStart, "greatOrEqual") : 0;
161
161
  timeEnd ??= this.lastTime;
162
- for (let i = ibar; this.data[i].time <= timeEnd; i++)
162
+ for (let i = ibar; i < this.length && this.data[i].time <= timeEnd; i++)
163
163
  yield this.data[i];
164
164
  }
165
165
  getArray(startTime, lastTime) {
@@ -193,7 +193,7 @@ class IBars {
193
193
  let ilast = 0;
194
194
  let n = 0;
195
195
  for (let i = 1; i <= count; i++) {
196
- let bartime = i < count ? src.time(i) : new Date(2100, 1, 1);
196
+ let bartime = i < count ? src.time(i) : new Date(2100, 0, 1);
197
197
  if (endDayTime_s && bartime.valueOf() % Time_1.D1_MS >= endDayTime_s * 1000 % Time_1.D1_MS)
198
198
  continue;
199
199
  if (bartime >= nextPeriodTime) {
@@ -350,11 +350,15 @@ class CBarsMutableBase extends CBarsBase {
350
350
  this._data = [];
351
351
  Object.freeze(bar);
352
352
  this.data[i] = bar;
353
+ if (this._tickSizeAuto)
354
+ this._ticksize = 0;
353
355
  return true;
354
356
  }
355
357
  AddTicks(ticks) { for (let tick of ticks)
356
358
  if (!this.AddTick(tick))
357
359
  return false; return true; }
360
+ addTick(tick) { return this.AddTick(tick); }
361
+ addTicks(ticks) { return this.AddTicks(ticks); }
358
362
  }
359
363
  exports.CBarsMutableBase = CBarsMutableBase;
360
364
  class CBarsMutable extends CBarsMutableBase {
@@ -370,7 +374,7 @@ function CreateRandomBars(tf, startTime, endTimeOrCount, startPrice = 100, volat
370
374
  if (!tf || tf.msec == 0)
371
375
  return null;
372
376
  console.log("Creating bars with parameters: ", ...([...arguments].map(arg => arg instanceof Time_1.TF ? arg.name : arg)));
373
- const tickSizeNum = tickSize ?? 10 ** Math.min(Math.round(Math.log10(startPrice) - 4), 0);
377
+ const tickSizeNum = tickSize ?? 10 ** Math.min(Math.round(Math.log10(startPrice > 0 ? startPrice : 1) - 4), 0);
374
378
  let period = new Time_1.Period(tf);
375
379
  let count;
376
380
  if (typeof endTimeOrCount == "number")
@@ -401,6 +405,7 @@ function CreateRandomBars(tf, startTime, endTimeOrCount, startPrice = 100, volat
401
405
  }
402
406
  return new CBars(tf, bars);
403
407
  }
408
+ exports.createRandomBars = CreateRandomBars;
404
409
  class CTimeSeriesBase {
405
410
  time(i) { return this.points[i]?.time ?? (() => { throw "Wrong index i=" + i + " of " + this.length; })(); }
406
411
  value(i) { return this.points[i]?.value ?? (() => { throw "Wrong index i=" + i + " of " + this.length; })(); }
@@ -218,5 +218,7 @@ export type SimpleParamsMutable<T> = T extends const_Date ? const_Date : Mutable
218
218
  };
219
219
  export type SimpleParams<T = IParams> = ReadonlyFull<SimpleParamsMutable<T>>;
220
220
  export declare function GetSimpleParams<T extends ReadonlyFull<IParams>>(params: T): SimpleParamsMutable<T>;
221
+ export declare const toValues: typeof GetSimpleParams;
221
222
  export declare function mergeParamValuesToInfos<TParams extends IParamsReadonly | IParams, TParams2 extends IParamsReadonly | IParams>(srcObj: TParams, valuesObj: SimpleParams<TParams2> | TParams2): TParams;
223
+ export declare const fromValues: typeof mergeParamValuesToInfos;
222
224
  export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CParamsReadonly = exports.CParams = void 0;
3
+ exports.fromValues = exports.toValues = exports.CParamsReadonly = exports.CParams = void 0;
4
4
  exports.isParamBase = isParamBase;
5
5
  exports.isParamGroupOrArray = isParamGroupOrArray;
6
6
  exports.isParamGroup = isParamGroup;
@@ -11,12 +11,11 @@ exports.enableAllParams = enableAllParams;
11
11
  exports.GetSimpleParams = GetSimpleParams;
12
12
  exports.mergeParamValuesToInfos = mergeParamValuesToInfos;
13
13
  const common_1 = require("../Common/core/common");
14
- {
14
+ function _typeCheck_DateTimeStr() {
15
15
  let ts = "2025-06-01 16:25:25";
16
+ return ts;
16
17
  }
17
- {
18
- let x = { value: 5, range: [5, 6] };
19
- }
18
+ function _typeCheck_IParamEnum2() { let x = { value: 5, range: [5, 6] }; return x; }
20
19
  let dd;
21
20
  function isParamBase(param) {
22
21
  return typeof param == "object" && !Array.isArray(param) && !(param instanceof Date);
@@ -37,7 +36,7 @@ function isSimpleParams2(params) {
37
36
  let t = false;
38
37
  for (let key in params) {
39
38
  const tr = params[key]["value"];
40
- if (!tr)
39
+ if (tr == null)
41
40
  return true;
42
41
  else {
43
42
  if (typeof tr == "object") {
@@ -89,11 +88,14 @@ function enableAllParams(params, enabled = true) {
89
88
  }
90
89
  return paramsInfoClone;
91
90
  }
92
- class C extends CParams {
93
- lastBar = { name: "Last_Bar", value: 0, range: { defaultMin: -10000, max: 0, step: 1 } };
91
+ function _typeCheck_CParamsReadonly() {
92
+ class C extends CParams {
93
+ lastBar = { name: "Last_Bar", value: 0, range: { defaultMin: -10000, max: 0, step: 1 } };
94
+ }
95
+ let xxx = {};
96
+ let bbb = xxx;
97
+ return bbb;
94
98
  }
95
- let xxx = {};
96
- let bbb = xxx;
97
99
  const param = {
98
100
  p0: { name: "MA0", value: [10, 20], range: [10, 20, 30] },
99
101
  p1: { name: "MA1", commentary: ["fgf"], value: 20, range: { min: 10, max: 20, step: 2 } },
@@ -178,11 +180,15 @@ function GetSimpleParams(params) {
178
180
  }
179
181
  return simpleParams;
180
182
  }
181
- let p = GetSimpleParams(new Test());
182
- let p0 = p.p1;
183
- let p3 = p.p3;
184
- let p4 = p.p4;
185
- let p5 = p.p5?.p1;
183
+ exports.toValues = GetSimpleParams;
184
+ function _typeCheck_GetSimpleParams() {
185
+ let p = GetSimpleParams(new Test());
186
+ let p0 = p.p1;
187
+ let p3 = p.p3;
188
+ let p4 = p.p4;
189
+ let p5 = p.p5?.p1;
190
+ return [p0, p3, p4, p5];
191
+ }
186
192
  function convert_(valuesObj, srcObj) {
187
193
  let resObj = {};
188
194
  if (srcObj instanceof Array)
@@ -232,6 +238,7 @@ function convert_(valuesObj, srcObj) {
232
238
  function mergeParamValuesToInfos(srcObj, valuesObj) {
233
239
  return convert_(isSimpleParams(valuesObj) ? valuesObj : GetSimpleParams(valuesObj), srcObj);
234
240
  }
241
+ exports.fromValues = mergeParamValuesToInfos;
235
242
  function test() {
236
243
  {
237
244
  const p = new Test();
@@ -45,6 +45,7 @@ export declare class CQuotesHistory {
45
45
  private _Bars;
46
46
  protected _GetBars(tf: TF): IBars | null;
47
47
  Bars(tf: TF): IBarsImmutable | null;
48
+ get(tf: TF): IBarsImmutable | null;
48
49
  }
49
50
  export declare class CQuotesHistoryMutable extends CQuotesHistory {
50
51
  private _endTickTime?;
@@ -52,12 +53,17 @@ export declare class CQuotesHistoryMutable extends CQuotesHistory {
52
53
  constructor(name?: string);
53
54
  AddEndBars(bars: IBars): boolean;
54
55
  AddEndBars(bars: readonly CBar[] | CBar, tf: TF): boolean;
56
+ append(bars: IBars): boolean;
57
+ append(bars: readonly CBar[] | CBar, tf: TF): boolean;
55
58
  AddStartBars(bars: IBars): boolean;
56
59
  AddStartBars(bars: readonly CBar[] | CBar, tf: TF): boolean;
60
+ prepend(bars: IBars): boolean;
61
+ prepend(bars: readonly CBar[] | CBar, tf: TF): boolean;
57
62
  private checkBars;
58
63
  protected _AddBarsExt(Bars: readonly CBar[] | CBar | IBars, tf: TF | undefined, toEnd: boolean): boolean;
59
64
  AddTicks(ticks: readonly ITick[]): boolean;
60
65
  AddTick(tick: ITick): boolean;
66
+ addTicks(ticks: readonly ITick[]): boolean;
61
67
  private getOrSetMutableBars;
62
68
  AddNewTicks(ticks: readonly ITick[]): void;
63
69
  AddNewTick(tick: ITick): void;
@@ -189,6 +189,7 @@ class CQuotesHistory {
189
189
  bars.Mutable = false;
190
190
  return bars;
191
191
  }
192
+ get(tf) { return this.Bars(tf); }
192
193
  }
193
194
  exports.CQuotesHistory = CQuotesHistory;
194
195
  class CQuotesHistoryMutable extends CQuotesHistory {
@@ -198,7 +199,9 @@ class CQuotesHistoryMutable extends CQuotesHistory {
198
199
  super([], name);
199
200
  }
200
201
  AddEndBars(bars, tf) { return this._AddBarsExt(bars, tf, true); }
202
+ append(bars, tf) { return this._AddBarsExt(bars, tf, true); }
201
203
  AddStartBars(bars, tf) { return this._AddBarsExt(bars, tf, false); }
204
+ prepend(bars, tf) { return this._AddBarsExt(bars, tf, false); }
202
205
  checkBars(bars, tf) {
203
206
  let period = new Bars_1.Period(tf);
204
207
  for (let i = 1; i < bars.length; i++)
@@ -256,7 +259,7 @@ class CQuotesHistoryMutable extends CQuotesHistory {
256
259
  let tf = Bars_1.TF.S1;
257
260
  let oldBars = this._GetBars(tf);
258
261
  let newbarsArr;
259
- if (oldBars && oldBars.count > 0 && Bars_1.Period.StartTime(tf, time) == oldBars.lastTime)
262
+ if (oldBars && oldBars.count > 0 && Bars_1.Period.StartTime(tf, time).valueOf() == oldBars.lastTime.valueOf())
260
263
  newbarsArr = [oldBars.last];
261
264
  let newbars = new Bars_1.CBarsMutable(tf, newbarsArr);
262
265
  if (!newbars.AddTicks(ticks))
@@ -265,6 +268,7 @@ class CQuotesHistoryMutable extends CQuotesHistory {
265
268
  return this.AddEndBars(newbars);
266
269
  }
267
270
  AddTick(tick) { return this.AddTicks([tick]); }
271
+ addTicks(ticks) { return this.AddTicks(ticks); }
268
272
  getOrSetMutableBars(tf) {
269
273
  let bars = this._GetBars(tf) ?? new CBarsInternal(tf);
270
274
  let mutableBars;
package/lib/index.d.ts CHANGED
@@ -31,3 +31,4 @@ export * as Bars from "./Exchange/Bars";
31
31
  export * as Params from "./Exchange/CParams";
32
32
  export * as Time from "./Common/Time";
33
33
  export * as Color from "./Common/Color";
34
+ export * as ObserveAll2 from "./Common/ObserveAll2/reactive2";
package/lib/index.js CHANGED
@@ -36,7 +36,7 @@ var __importStar = (this && this.__importStar) || (function () {
36
36
  };
37
37
  })();
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.Color = exports.Time = exports.Params = exports.Bars = exports.Math = void 0;
39
+ exports.ObserveAll2 = exports.Color = exports.Time = exports.Params = exports.Bars = exports.Math = void 0;
40
40
  __exportStar(require("./Common/node_console"), exports);
41
41
  __exportStar(require("./Common/core/Decorator"), exports);
42
42
  __exportStar(require("./Common/core/BaseTypes"), exports);
@@ -70,3 +70,4 @@ exports.Bars = __importStar(require("./Exchange/Bars"));
70
70
  exports.Params = __importStar(require("./Exchange/CParams"));
71
71
  exports.Time = __importStar(require("./Common/Time"));
72
72
  exports.Color = __importStar(require("./Common/Color"));
73
+ exports.ObserveAll2 = __importStar(require("./Common/ObserveAll2/reactive2"));
@@ -12,6 +12,7 @@ interface WebhookClientOptions {
12
12
  renewIntervalMs?: number;
13
13
  app?: Express;
14
14
  }
15
+ export declare const buildSelfWebhookUrl: (clientIp: string, raw: unknown) => string | null;
15
16
  export declare const apiSaveData: {
16
17
  loadSubscribers: () => Map<string, Subscriber>;
17
18
  saveSubscribers: (subs: Map<string, Subscriber>) => void;
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.createWebhookClient = exports.createWebhookServer = exports.apiSaveData = void 0;
39
+ exports.createWebhookClient = exports.createWebhookServer = exports.apiSaveData = exports.buildSelfWebhookUrl = void 0;
40
40
  const express_1 = __importDefault(require("express"));
41
41
  const axios_1 = __importDefault(require("axios"));
42
42
  const fs = __importStar(require("fs"));
@@ -56,11 +56,29 @@ const loadSubscribers = () => {
56
56
  }
57
57
  };
58
58
  const Queue = (0, waitRun_1.createAsyncQueue)(1);
59
+ let _tmpSeq = 0;
59
60
  const saveSubscribers = (subs) => {
60
61
  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
+ Queue.enqueue(async () => {
63
+ const tmp = `${SUBSCRIBERS_FILE}.${++_tmpSeq}.tmp`;
64
+ await fs.promises.writeFile(tmp, JSON.stringify(obj, null, 2), 'utf-8');
65
+ await fs.promises.rename(tmp, SUBSCRIBERS_FILE);
66
+ });
62
67
  };
63
68
  const normalizeIP = (ip) => ip?.startsWith('::ffff:') ? ip.slice(7) : ip;
69
+ const buildSelfWebhookUrl = (clientIp, raw) => {
70
+ if (typeof raw !== 'string' || !raw)
71
+ return null;
72
+ let u;
73
+ try {
74
+ u = new URL('http://' + clientIp + raw);
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ return u.hostname === clientIp ? u.toString() : null;
80
+ };
81
+ exports.buildSelfWebhookUrl = buildSelfWebhookUrl;
64
82
  exports.apiSaveData = { loadSubscribers, saveSubscribers };
65
83
  const createWebhookServer = (params) => {
66
84
  const app = params.app ?? (0, express_1.default)();
@@ -90,24 +108,23 @@ const createWebhookServer = (params) => {
90
108
  const renewExpiry = () => new Date(Date.now() + 3 * 24 * 3600_000);
91
109
  app.post('/webHook_subscribe', checkAuth, (req, res) => {
92
110
  const { tag } = req.body;
93
- if (!req.body.url || typeof req.body.url !== 'string' || typeof tag !== 'string') {
111
+ const url = (0, exports.buildSelfWebhookUrl)(normalizeIP(req.ip ?? '127.0.0.1'), req.body.url);
112
+ if (!url || typeof tag !== 'string') {
94
113
  res.status(400).json({ error: 'Неверный запрос' });
95
114
  return;
96
115
  }
97
116
  purgeExpired();
98
- const url = new URL(clientAddr(req) + req.body.url).toString();
99
117
  subscribers.set(url, { url, tag, expireAt: renewExpiry() });
100
118
  file.saveSubscribers(subscribers);
101
119
  res.json({ message: 'Подписка оформлена' });
102
120
  });
103
121
  app.get('/webHook_status', checkAuth, (req, res) => {
104
- const rawUrl = req.query['url'];
105
- if (!rawUrl || typeof rawUrl !== 'string') {
122
+ const url = (0, exports.buildSelfWebhookUrl)(normalizeIP(req.ip ?? '127.0.0.1'), req.query['url']);
123
+ if (!url) {
106
124
  res.status(400).json({ error: 'Неверный запрос' });
107
125
  return;
108
126
  }
109
127
  purgeExpired();
110
- const url = new URL(clientAddr(req) + rawUrl).toString();
111
128
  const subscriber = Array.from(subscribers.values()).find(s => s.url === url);
112
129
  if (!subscriber) {
113
130
  res.json({ subscribed: false });
@@ -118,7 +135,11 @@ const createWebhookServer = (params) => {
118
135
  res.json({ subscribed: true, expireAt: subscriber.expireAt });
119
136
  });
120
137
  app.delete('/webHook_unsubscribe', checkAuth, (req, res) => {
121
- const url = new URL(clientAddr(req) + req.body.url).toString();
138
+ const url = (0, exports.buildSelfWebhookUrl)(normalizeIP(req.ip ?? '127.0.0.1'), req.body.url);
139
+ if (!url) {
140
+ res.status(400).json({ error: 'Неверный запрос' });
141
+ return;
142
+ }
122
143
  const key = Array.from(subscribers.keys()).find(k => subscribers.get(k)?.url === url);
123
144
  if (key && subscribers.delete(key)) {
124
145
  file.saveSubscribers(subscribers);
@@ -159,6 +180,8 @@ const createWebhookClient = (options) => {
159
180
  app.use(express_1.default.json());
160
181
  const activeTags = new Set();
161
182
  const timers = new Map();
183
+ const handlers = new Map();
184
+ const registeredPaths = new Set();
162
185
  const headers = { authorization: authToken };
163
186
  const makeUrl = (tag) => `:${clientPort}/webHook_${tag}`;
164
187
  const connect = async (tag, handler) => {
@@ -167,7 +190,19 @@ const createWebhookClient = (options) => {
167
190
  return;
168
191
  }
169
192
  const path = `/webHook_${tag}`;
170
- app.post(path, (req, res) => { handler(req.body); res.end(); });
193
+ handlers.set(tag, handler);
194
+ if (!registeredPaths.has(path)) {
195
+ registeredPaths.add(path);
196
+ app.post(path, (req, res) => {
197
+ const h = handlers.get(tag);
198
+ if (!h) {
199
+ res.status(404).end();
200
+ return;
201
+ }
202
+ h(req.body);
203
+ res.end();
204
+ });
205
+ }
171
206
  await axios_1.default.post(`${serverUrl}/webHook_subscribe`, { url: makeUrl(tag), tag }, { headers });
172
207
  activeTags.add(tag);
173
208
  if (autoRenew) {
@@ -187,13 +222,7 @@ const createWebhookClient = (options) => {
187
222
  clearInterval(t);
188
223
  timers.delete(tag);
189
224
  }
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
- }
225
+ handlers.delete(tag);
197
226
  }));
198
227
  };
199
228
  const getMySubscriptions = async () => (await axios_1.default.get(`${serverUrl}/webHook_client_subscriptions`, { headers })).data;
@@ -57,20 +57,37 @@ function saveKeyValue({ dirDef = "", key: _key = "" }) {
57
57
  .then(() => true)
58
58
  .catch(() => false);
59
59
  }
60
+ let _tmpSeq = 0;
60
61
  async function set({ key = _key, obj, path = "" }) {
61
62
  const filePath = await resolvePath(path, key);
62
- await fs.promises.writeFile(filePath, obj);
63
+ const tmp = `${filePath}.${++_tmpSeq}.tmp`;
64
+ await fs.promises.writeFile(tmp, obj);
65
+ await fs.promises.rename(tmp, filePath);
63
66
  }
64
67
  async function setElMap({ key = _key, keyEl, valueEl, path = "" }) {
65
68
  const exists = await has({ key, path });
66
- const data = exists ? JSON.parse(await get({ key, path })) : {};
69
+ let data = {};
70
+ if (exists) {
71
+ try {
72
+ data = JSON.parse(await get({ key, path }));
73
+ }
74
+ catch {
75
+ data = {};
76
+ }
77
+ }
67
78
  data[keyEl] = valueEl;
68
79
  await set({ key, obj: JSON.stringify(data), path });
69
80
  }
70
81
  async function delEl({ key = _key, keyEl, path = "" }) {
71
82
  if (!(await has({ key, path })))
72
83
  throw new Error(`Файл не найден: ${path}${key}`);
73
- const data = JSON.parse(await get({ key, path }));
84
+ let data = {};
85
+ try {
86
+ data = JSON.parse(await get({ key, path }));
87
+ }
88
+ catch {
89
+ data = {};
90
+ }
74
91
  delete data[keyEl];
75
92
  await set({ key, obj: JSON.stringify(data), path });
76
93
  return true;
@@ -1,5 +1,24 @@
1
+ export declare class MyError<D = unknown> extends Error {
2
+ readonly code: string;
3
+ readonly data: D;
4
+ name: string;
5
+ constructor(message: string, code?: string, data?: D, cause?: unknown);
6
+ toJSON(): {
7
+ name: string;
8
+ message: string;
9
+ code: string;
10
+ data: D;
11
+ stack: string | undefined;
12
+ };
13
+ static wrap(e: unknown): Error;
14
+ static fromWire<D>(w: tWire<D>): MyError<D> & {
15
+ name: string;
16
+ stack: string | undefined;
17
+ };
18
+ }
19
+ export type tWire<D = unknown> = ReturnType<MyError<D>['toJSON']>;
1
20
  export declare const toError: {
2
21
  convert: any;
3
- throw(e: any): never;
22
+ throw(e: any): void;
4
23
  convertToMsg(e: any): any;
5
24
  };
@@ -1,23 +1,36 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toError = void 0;
4
- exports.toError = {
5
- set convert(e) {
6
- if (e instanceof Error) {
7
- throw e;
8
- }
9
- throw new Error(JSON.stringify(e));
10
- },
11
- throw(e) {
12
- if (e instanceof Error) {
13
- throw e;
14
- }
15
- throw new Error(JSON.stringify(e));
16
- },
17
- convertToMsg(e) {
18
- if (e instanceof Error) {
19
- return e;
20
- }
21
- return e;
3
+ exports.toError = exports.MyError = void 0;
4
+ class MyError extends Error {
5
+ code;
6
+ data;
7
+ name = 'MyError';
8
+ constructor(message, code = 'ERR', data = {}, cause) {
9
+ super(message);
10
+ this.code = code;
11
+ this.data = data;
12
+ if (cause != undefined)
13
+ this.cause = cause;
14
+ }
15
+ toJSON() {
16
+ const { name, message, code, data, stack } = this;
17
+ return { name, message, code, data, stack };
18
+ }
19
+ static wrap(e) {
20
+ return e instanceof Error ? e : new MyError(typeof e == 'string' ? e : JSON.stringify(e), 'ERR', { value: e });
22
21
  }
22
+ static fromWire(w) {
23
+ return Object.assign(new MyError(w.message, w.code, w.data), { name: w.name, stack: w.stack });
24
+ }
25
+ }
26
+ exports.MyError = MyError;
27
+ const legacyThrow = (e) => {
28
+ if (e instanceof Error)
29
+ throw e;
30
+ throw new Error(JSON.stringify(e));
31
+ };
32
+ exports.toError = {
33
+ set convert(e) { legacyThrow(e); },
34
+ throw(e) { legacyThrow(e); },
35
+ convertToMsg(e) { return e; },
23
36
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wenay-common2",
3
- "version": "1.0.45",
3
+ "version": "1.0.48",
4
4
  "description": "Common library",
5
5
  "strict": true,
6
6
  "main": "lib/index.js",
@@ -23,6 +23,7 @@
23
23
  },
24
24
  "exports": {
25
25
  ".": "./lib/index.js",
26
+ "./observe-all2": "./lib/Common/ObserveAll2/reactive2.js",
26
27
  "./lib/client": "./lib/client.js",
27
28
  "./lib/server": "./lib/server.js",
28
29
  "./client": "./lib/client.js",
@@ -1,5 +0,0 @@
1
- export declare const toError: {
2
- convert: any;
3
- throw(e: any): never;
4
- convertToMsg(e: any): any;
5
- };
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toError = void 0;
4
- exports.toError = {
5
- set convert(e) {
6
- if (e instanceof Error) {
7
- throw e;
8
- }
9
- throw new Error(JSON.stringify(e));
10
- },
11
- throw(e) {
12
- if (e instanceof Error) {
13
- throw e;
14
- }
15
- throw new Error(JSON.stringify(e));
16
- },
17
- convertToMsg(e) {
18
- if (e instanceof Error) {
19
- return e;
20
- }
21
- return e;
22
- }
23
- };