vrack2-core 0.0.1 → 1.0.0

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 (148) hide show
  1. package/README.md +25 -4
  2. package/docs/Bootstrap.md +77 -0
  3. package/docs/Container.md +124 -0
  4. package/docs/Device.md +272 -0
  5. package/docs/FastStart.md +111 -0
  6. package/docs/Structure.md +148 -0
  7. package/lib/Bootstrap.d.ts +79 -0
  8. package/lib/Bootstrap.js +103 -0
  9. package/lib/Container.d.ts +202 -6
  10. package/lib/Container.js +295 -27
  11. package/lib/IServiceStructure.d.ts +8 -0
  12. package/lib/IStructureDevice.d.ts +5 -0
  13. package/lib/ImportManager.d.ts +85 -3
  14. package/lib/ImportManager.js +122 -16
  15. package/lib/MainProcess.d.ts +30 -3
  16. package/lib/MainProcess.js +28 -6
  17. package/lib/Utility.d.ts +15 -21
  18. package/lib/Utility.js +40 -40
  19. package/lib/actions/Action.d.ts +10 -0
  20. package/lib/actions/Action.js +10 -0
  21. package/lib/actions/BasicAction.d.ts +60 -0
  22. package/lib/actions/BasicAction.js +62 -0
  23. package/lib/actions/GlobalAction.d.ts +5 -0
  24. package/lib/actions/GlobalAction.js +5 -0
  25. package/lib/actions/IAction.d.ts +7 -0
  26. package/lib/actions/ILocalAction.d.ts +7 -0
  27. package/lib/boot/BootClass.d.ts +93 -0
  28. package/lib/boot/BootClass.js +101 -0
  29. package/lib/boot/DeviceFileStorage.d.ts +38 -0
  30. package/lib/boot/DeviceFileStorage.js +112 -0
  31. package/lib/boot/DeviceManager.d.ts +190 -0
  32. package/lib/boot/DeviceManager.js +306 -0
  33. package/lib/boot/DeviceMetrics.d.ts +82 -0
  34. package/lib/boot/DeviceMetrics.js +128 -0
  35. package/lib/boot/StructureStorage.d.ts +59 -0
  36. package/lib/boot/StructureStorage.js +125 -0
  37. package/lib/errors/CoreError.d.ts +42 -25
  38. package/lib/errors/CoreError.js +44 -24
  39. package/lib/errors/ErrorManager.d.ts +18 -20
  40. package/lib/errors/ErrorManager.js +23 -22
  41. package/lib/index.d.ts +20 -4
  42. package/lib/index.js +28 -4
  43. package/lib/metrics/BasicMetric.d.ts +49 -0
  44. package/lib/metrics/BasicMetric.js +79 -0
  45. package/lib/metrics/IMetricSettings.d.ts +32 -0
  46. package/lib/metrics/IMetricSettings.js +2 -0
  47. package/lib/metrics/IvMs.d.ts +9 -0
  48. package/lib/metrics/IvMs.js +22 -0
  49. package/lib/metrics/IvS.d.ts +9 -0
  50. package/lib/metrics/IvS.js +22 -0
  51. package/lib/metrics/IvUs.d.ts +9 -0
  52. package/lib/metrics/IvUs.js +22 -0
  53. package/lib/metrics/Metric.d.ts +17 -0
  54. package/lib/metrics/Metric.js +27 -0
  55. package/lib/ports/BasicPort.d.ts +39 -0
  56. package/lib/ports/BasicPort.js +39 -0
  57. package/lib/ports/ILocalPort.d.ts +7 -0
  58. package/lib/ports/IPort.d.ts +7 -0
  59. package/lib/ports/Port.d.ts +10 -0
  60. package/lib/ports/Port.js +10 -0
  61. package/lib/ports/ReturnPort.d.ts +5 -0
  62. package/lib/ports/ReturnPort.js +5 -0
  63. package/lib/service/Device.d.ts +213 -78
  64. package/lib/service/Device.js +185 -83
  65. package/lib/service/DeviceConnect.d.ts +4 -8
  66. package/lib/service/DeviceConnect.js +4 -8
  67. package/lib/service/DevicePort.d.ts +15 -6
  68. package/lib/service/DevicePort.js +29 -12
  69. package/lib/service/IDeviceEvent.d.ts +4 -1
  70. package/lib/validator/IValidationProblem.d.ts +7 -0
  71. package/lib/validator/IValidationRule.d.ts +12 -0
  72. package/lib/validator/IValidationSubrule.d.ts +2 -0
  73. package/lib/validator/Rule.d.ts +6 -2
  74. package/lib/validator/Rule.js +12 -2
  75. package/lib/validator/Validator.d.ts +48 -3
  76. package/lib/validator/Validator.js +70 -18
  77. package/lib/validator/types/AnyType.d.ts +17 -0
  78. package/lib/validator/types/AnyType.js +34 -0
  79. package/lib/validator/types/ArrayType.d.ts +37 -4
  80. package/lib/validator/types/ArrayType.js +42 -6
  81. package/lib/validator/types/BasicType.d.ts +67 -7
  82. package/lib/validator/types/BasicType.js +74 -8
  83. package/lib/validator/types/BooleanType.d.ts +23 -0
  84. package/lib/validator/types/BooleanType.js +47 -0
  85. package/lib/validator/types/FunctionType.d.ts +17 -0
  86. package/lib/validator/types/FunctionType.js +38 -0
  87. package/lib/validator/types/NumberType.d.ts +40 -5
  88. package/lib/validator/types/NumberType.js +53 -14
  89. package/lib/validator/types/ObjectType.d.ts +32 -5
  90. package/lib/validator/types/ObjectType.js +42 -8
  91. package/lib/validator/types/StringType.d.ts +30 -5
  92. package/lib/validator/types/StringType.js +33 -7
  93. package/package.json +10 -9
  94. package/src/Bootstrap.ts +122 -0
  95. package/src/Container.ts +411 -43
  96. package/src/IServiceStructure.ts +9 -0
  97. package/src/IStructureDevice.ts +5 -0
  98. package/src/ImportManager.ts +119 -11
  99. package/src/MainProcess.ts +53 -8
  100. package/src/Utility.ts +35 -36
  101. package/src/actions/Action.ts +12 -0
  102. package/src/actions/BasicAction.ts +63 -0
  103. package/src/actions/GlobalAction.ts +5 -0
  104. package/src/actions/IAction.ts +7 -0
  105. package/src/actions/ILocalAction.ts +7 -0
  106. package/src/boot/BootClass.ts +117 -0
  107. package/src/boot/DeviceFileStorage.ts +96 -0
  108. package/src/boot/DeviceManager.ts +339 -0
  109. package/src/boot/DeviceMetrics.ts +129 -0
  110. package/src/boot/StructureStorage.ts +108 -0
  111. package/src/errors/CoreError.ts +52 -26
  112. package/src/errors/ErrorManager.ts +46 -33
  113. package/src/index.ts +30 -6
  114. package/src/metrics/BasicMetric.ts +84 -0
  115. package/src/metrics/IMetricSettings.ts +38 -0
  116. package/src/metrics/IvMs.ts +18 -0
  117. package/src/metrics/IvS.ts +18 -0
  118. package/src/metrics/IvUs.ts +17 -0
  119. package/src/metrics/Metric.ts +25 -0
  120. package/src/ports/BasicPort.ts +39 -0
  121. package/src/ports/ILocalPort.ts +7 -0
  122. package/src/ports/IPort.ts +7 -0
  123. package/src/ports/Port.ts +11 -1
  124. package/src/ports/ReturnPort.ts +5 -0
  125. package/src/service/Device.ts +234 -103
  126. package/src/service/DeviceConnect.ts +4 -8
  127. package/src/service/DevicePort.ts +30 -11
  128. package/src/service/IDeviceEvent.ts +4 -1
  129. package/src/validator/IValidationProblem.ts +7 -0
  130. package/src/validator/IValidationRule.ts +12 -0
  131. package/src/validator/IValidationSubrule.ts +3 -0
  132. package/src/validator/Rule.ts +16 -2
  133. package/src/validator/Validator.ts +74 -23
  134. package/src/validator/types/AnyType.ts +32 -0
  135. package/src/validator/types/ArrayType.ts +43 -7
  136. package/src/validator/types/BasicType.ts +78 -9
  137. package/src/validator/types/BooleanType.ts +49 -0
  138. package/src/validator/types/FunctionType.ts +39 -0
  139. package/src/validator/types/NumberType.ts +53 -15
  140. package/src/validator/types/ObjectType.ts +52 -14
  141. package/src/validator/types/StringType.ts +34 -10
  142. package/docs/RU-README.md +0 -6
  143. package/lib/DeviceManager.d.ts +0 -32
  144. package/lib/DeviceManager.js +0 -143
  145. package/lib/test.d.ts +0 -1
  146. package/lib/test.js +0 -58
  147. package/src/DeviceManager.ts +0 -124
  148. package/src/test.ts +0 -82
@@ -3,30 +3,15 @@
3
3
  * Licensed under the Apache License, Version 2.0
4
4
  */
5
5
 
6
-
7
- // import DeviceError from "../errors/DeviceError";
8
- // import Rule from "../validator/ValidatorRule";
9
6
  import BasicType from "../validator/types/BasicType";
10
7
  import Container from '../Container';
11
8
  import BasicAction from "../actions/BasicAction";
12
9
  import BasicPort from "../ports/BasicPort";
13
10
  import DevicePort from "./DevicePort";
14
- import IDeviceEvent from "./IDeviceEvent";
15
-
16
-
17
- /**
18
- * Интерфейс списка исходящих портов устройства
19
- // */
20
- // export interface IDeviceOutputList {
21
- // [index: string]: OutputPort;
22
- // }
23
-
24
- // /**
25
- // * Интерфейс списка входящих портов устройства
26
- // */
27
- // export interface IDeviceInputList {
28
- // [index: string]: InputPort;
29
- // }
11
+ import IDeviceEvent from "./IDeviceEvent";
12
+ import CoreError from "../errors/CoreError";
13
+ import BasicMetric from "../metrics/BasicMetric";
14
+ import ImportManager from "../ImportManager";
30
15
 
31
16
  export enum EDeviceMessageTypes {
32
17
  terminal = "terminal",
@@ -37,26 +22,64 @@ export enum EDeviceMessageTypes {
37
22
  alert = "alert",
38
23
  }
39
24
 
40
- interface IDevicePorts {
41
- input: {[key:string]: DevicePort}
42
- output: {[key:string]: DevicePort}
25
+ interface IDeviceSettings {
26
+ /**
27
+ * List of broadcast channels
28
+ * Device channels list:
29
+ * - terminal
30
+ * - notify
31
+ * - event
32
+ * - action
33
+ * - alert
34
+ * - error
35
+ * - render
36
+ */
37
+ channels: Array<'terminal' | 'notify' | 'event' | 'action' | 'alert' | 'error' | 'render'>;
43
38
  }
44
39
 
45
40
  export default class Device {
46
- /** Идентификатор устройства */
41
+
42
+ /**
43
+ * Device unique for this container id
44
+ * the name usually begins with a capital letter
45
+ *
46
+ * @example 'DeviceName'
47
+ * */
47
48
  id: string;
49
+
50
+ /**
51
+ * Device type string
52
+ * Uses the vendor name and device name
53
+ * @example 'vrack.KeyManager'
54
+ */
48
55
  type: string;
49
-
50
56
 
51
- ports: IDevicePorts
57
+ /**
58
+ * Allows access to port management.
59
+ */
60
+ ports: {
61
+ input: { [key: string]: DevicePort }
62
+ output: { [key: string]: DevicePort }
63
+ }
52
64
 
53
- /** Экземпляр класса виртуальной стойки */
65
+ /**
66
+ * Active loader container
67
+ * */
54
68
  Container: Container;
55
69
 
56
- /** Входящие (назначаемые сверху) параметры устройства */
57
- options: {[key: string]: any} = {};
70
+ /**
71
+ * Device options
72
+ *
73
+ * @see checkOptions()
74
+ */
75
+ options: { [key: string]: any } = {};
58
76
 
59
- constructor(id: string, type: string, Container: Container){
77
+ /**
78
+ * @param id Unique ID
79
+ * @param type Device type string
80
+ * @param Container Active loader container
81
+ */
82
+ constructor(id: string, type: string, Container: Container) {
60
83
  this.id = id
61
84
  this.type = type
62
85
  this.Container = Container
@@ -66,37 +89,82 @@ export default class Device {
66
89
  }
67
90
  }
68
91
 
92
+ /**
93
+ * Device settings
94
+ *
95
+ * Needs to be finalized"
96
+ */
97
+ settings(): IDeviceSettings {
98
+ return {
99
+ channels: ['terminal', 'notify', 'event', 'action', 'alert', 'error', 'render']
100
+ }
101
+ }
102
+
69
103
  /**
70
- * Short device description
104
+ * Short device description. Can use markdown markup
71
105
  *
72
106
  * @return {string} Device description
73
107
  * */
74
- description(): string{
108
+ description(): string {
75
109
  return ''
76
110
  }
77
111
 
78
112
  /**
79
- * Shares данные устройства (обновляемые данные)
80
- * используется с методом `this.render`
113
+ * This is a fast updating data object - it will be sent
114
+ * to subscribers after the render() call
81
115
  *
82
116
  * @see render()
83
117
  * */
84
118
  shares: any = {};
85
119
 
86
120
  /**
121
+ * This data will be loaded for the specific instance of the device.
122
+ * The device itself determines this data and saves it at the right moment
87
123
  *
124
+ * The structure is determined by the device
88
125
  */
89
126
  storage: any = {}
90
127
 
91
- /** Список Action-методов устройства */
92
- actions() : { [key: string] : BasicAction} { return {} }
93
-
94
128
  /**
95
- * Определение списка параметров устройства
129
+ * Device action list
130
+ * Device actions can be called from the container.
131
+ * This is a way to interact with the device from the outside world
96
132
  *
97
- * @returns {Array<Rule>}
133
+ * @example
134
+ * ```
135
+ * return {
136
+ * 'test.action': Action.global().requirements({
137
+ * id: Rule.string().require().default('www').description('Some id')
138
+ * }).description('Test action')
139
+ * }
140
+ * ```
141
+ *
142
+ * A handler must be created for each action. For example, for `test.action` action `actionTestAction` must be created.
98
143
  * */
99
- checkOptions(): {[key:string]: BasicType} { return {} }
144
+ actions(): { [key: string]: BasicAction } { return {} }
145
+
146
+ /**
147
+ * Defining device metrics.
148
+ *
149
+ * @example
150
+ *
151
+ * ```
152
+ * return {
153
+ * 'test.metric': Metric.inS().retentions('1s:6h').description('Test metric')
154
+ * }
155
+ * ```
156
+ * @see BasicMetric
157
+ */
158
+ metrics(): { [key: string]: BasicMetric } { return {} }
159
+
160
+
161
+ /**
162
+ * Run before each device action
163
+ *
164
+ * @param action "device.action" like string
165
+ * @param data data for action
166
+ */
167
+ beforeAction(action: string, data: any) { return true }
100
168
 
101
169
  /**
102
170
  * Prepare options
@@ -105,121 +173,184 @@ export default class Device {
105
173
  */
106
174
  prepareOptions() { return }
107
175
 
176
+ /**
177
+ * Defining a list of device parameters
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * return {
182
+ * timeout: Rule.number().integer().min(0).description('Interval timeout').example(0)
183
+ * }
184
+ * ```
185
+ *
186
+ * @returns {Array<Rule>}
187
+ * */
188
+ checkOptions(): { [key: string]: BasicType } { return {} }
189
+
190
+ /**
191
+ * Device inputs list
192
+ *
193
+ * Use like this object:
194
+ * {
195
+ * 'group.portname': Port.standart(),
196
+ * 'group.portname': Port.standart()
197
+ * }
198
+ *
199
+ */
200
+ inputs(): { [key: string]: BasicPort } { return {} }
108
201
 
109
- inputs () : {[key:string]: BasicPort} { return {} }
110
- outputs () : {[key:string]: BasicPort} { return {} }
202
+ /**
203
+ * Device output list
204
+ *
205
+ * @see inputs
206
+ */
207
+ outputs(): { [key: string]: BasicPort } { return {} }
111
208
 
112
209
  /**
113
- * Метод является входной точкой для начала инициализации устройства
210
+ * The method is an input point to start device initialization
114
211
  *
115
- * Устройство пройдет только следующие этапы создания устройства:
212
+ * The device will only go through the following device creation steps:
116
213
  *
117
- * - Создания класса
118
- * - Назначение праметров устройства
214
+ * - Creating a class
215
+ * - Assigning device prameters
119
216
  *
120
- * Необходимо использовать для назначения функций вызова динамических портов
121
- * устройства.
217
+ * Must be used to assign functions to call dynamic ports
218
+ * of the device.
122
219
  */
123
220
  preProcess() { return }
124
221
 
125
222
  /**
126
- * Метод является входной точкой для начала работы устройства
223
+ * The method is an input point for the start of device operation
127
224
  *
128
- * Устройство пройдет следующие этапы создания устройства:
225
+ * The device will go through the following steps to create the device:
129
226
  *
130
- * - Создания класса
131
- * - Назначение праметров устройства
132
- * - Создание портов
133
- * - Назначение функций вызова
134
- * - Создание соединений между устройствами
135
- * - Линковка Shares устройства
227
+ * - Creating a class
228
+ * - Assigning device prameters
229
+ * - Creating ports
230
+ * - Assigning call functions
231
+ * - Creating connections between devices
232
+ * - Linking device Shares
136
233
  *
137
- * Необходимо использовать для осуществления начала основной работы устройства
138
- * например, инициализация подключений, создание таймеров и тп.
234
+ * Must be used to start basic operation of the device
235
+ * e.g. initialization of connections, creation of timers, etc.
139
236
  */
140
237
  process() { return }
141
238
 
142
239
  /**
143
- * По аналогии с `process` но асинхронный, загрузчик будет ждать выполнения всех
144
- * методов `processPromise` всех устройств.
240
+ * Similar to `process` but asynchronous, the loader will wait for the execution of all the
241
+ * `processPromise` methods of all devices.
145
242
  *
146
- * Используется, когда есть необходимость перед запуском стойки выполнить
147
- * и дождаться выполнения асинхронного кода (инициализация некоторых файловых баз данных и тп)
243
+ * Used when there is a need to execute before starting the rack
244
+ * and wait for asynchronous code to execute (initialization of some file databases, etc.)
148
245
  */
149
246
  async processPromise() { return }
150
247
 
151
- stop() { return }
152
-
153
- async stopPromise() { return }
154
-
155
248
  /**
156
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
157
- * к постановке в очередь устройства на обновление данных `Shares`
249
+ * Myby todo?
250
+ *
251
+ * stop() { return }
252
+ * async stopPromise() { return }
158
253
  */
159
- render() { return this.event('device.render', 'shares', this.shares) }
160
254
 
161
255
  /**
162
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
163
- * к сохранение в локальное файловое хранилище данных `Storage`
256
+ * Queues device shares data updates for external consumers
257
+ *
258
+ * @see shares
164
259
  */
165
- save() { return this.event('device.save', 'storage', this.storage) }
260
+ render() { return this.makeEvent('device.render', 'shares', this.shares, []) }
166
261
 
167
262
  /**
168
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
169
- * к отправке сообщению об ошибке
263
+ * Save device storage
170
264
  *
171
- * @param {string} data Сообщение об ошибке
172
- * @param {any} trace Непосредственно объект ошибки, или объект который поможет разобратся в случившейся ситуации
265
+ * @see storage
173
266
  */
174
- error(data: string, trace: any) { return this.event('device.error', data, trace) }
267
+ save() { return this.makeEvent('device.save', 'storage', this.storage, []) }
175
268
 
176
269
  /**
177
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
178
- * к отправке информационного сообщения
270
+ * Write metric value
179
271
  *
180
- * @param {string} data Сообщение об ошибке
181
- * @param {any} trace Дополнительная информация
272
+ * @param path Registered metric path
273
+ * @param value value record
274
+ * @param modify Write modify 'last' | 'first' | 'max' | 'min' | 'avg' | 'sum'
182
275
  */
183
- notify(data: string, trace: any) { return this.event('device.notify', data, trace) }
276
+ metric(path: string, value: number, modify: 'last' | 'first' | 'max' | 'min' | 'avg' | 'sum' = 'last') {
277
+ return this.makeEvent('device.metric', path, { value, modify }, [])
278
+ }
184
279
 
185
280
  /**
186
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
187
- * к отправке оповещения
188
- *
189
- * @param {string} data Сообщение об ошибке
190
- * @param {any} trace Дополнительная информация
281
+ * @param data Message
282
+ * @param trace Trace info (object needed)
283
+ */
284
+ terminal(data: string, trace: { [key: string]: any }, ...args: any[]) { return this.makeEvent('device.terminal', data, trace, args) }
285
+
286
+ /**
287
+ * @param data Message
288
+ * @param trace Trace info (object needed)
289
+ */
290
+ notify(data: string, trace: { [key: string]: any }, ...args: any[]) { return this.makeEvent('device.notify', data, trace, args) }
291
+
292
+ /**
293
+ * @param data Message
294
+ * @param trace Trace info (object needed)
295
+ */
296
+ event(data: string, trace: { [key: string]: any }, ...args: any[]) { return this.makeEvent('device.event', data, trace, args) }
297
+
298
+ /**
299
+ * @param data Message
300
+ * @param trace Trace info (object needed)
191
301
  */
192
- alert(data: string, trace: any) { return this.event('device.alert', data, trace) }
302
+ alert(data: string, trace: { [key: string]: any }, ...args: any[]) { return this.makeEvent('device.alert', data, trace, args) }
193
303
 
194
304
  /**
195
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
196
- * к отправке отладочной информации
305
+ * @param data Message
306
+ * @param trace Trace info (object needed)
307
+ */
308
+ error(data: string, trace: { [key: string]: any }, ...args: any[]) {
309
+ if (trace instanceof Error) trace = CoreError.objectify(trace)
310
+ return this.makeEvent('device.error', data, trace, args)
311
+ }
312
+
313
+ /**
314
+ * Make & emit device event
197
315
  *
198
- * @param {string} data Сообщение об ошибке
199
- * @param {any} trace Дополнительная информация
316
+ * @param type event type
317
+ * @param data event data string
318
+ * @param trace additional information
200
319
  */
201
- terminal(data: string, trace: any) { return this.event('device.terminal', data, trace) }
320
+ protected makeEvent(type: string, data: string, trace: { [key: string]: any }, args: any[]) {
321
+ const nEvent: IDeviceEvent = { device: this.id, data, trace }
322
+ return this.Container.emit(type, nEvent)
323
+ }
202
324
 
203
325
  /**
204
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
205
- * к отправке сообщения о событии
326
+ * Adding processing for the incoming port
206
327
  *
207
- * @param {string} data Сообщение об ошибке
208
- * @param {any} trace Дополнительная информация
328
+ * @param name Port name in 'port.name' format
329
+ * @param action CallBack function to execute
209
330
  */
210
- protected event(type:string, data: string, trace: any) {
211
- const nEvent: IDeviceEvent = {id: this.id, data, trace}
212
- return this.Container.emit(type, nEvent)
331
+ addInputHandler(name: string, action: (data: any) => any) {
332
+ name = ImportManager.camelize('input.' + name)
333
+ this[name as keyof Device] = action
213
334
  }
214
335
 
215
336
  /**
216
- * Сообщает стойке, о том, что устройство не может дальше работать
217
- * и произошла критическая ошибка
337
+ * Adding a handle for the action
218
338
  *
219
- * Требует создание ошибки устройства DeviceError
339
+ * @param name Action name in the format 'action.name'
340
+ * @param action CallBack function to execute
341
+ */
342
+ addActionHandler(name: string, action: (data: any) => any) {
343
+ name = ImportManager.camelize('action.' + name)
344
+ this[name as keyof Device] = action
345
+ }
346
+
347
+ /**
348
+ * Informs the rack that the unit cannot continue to operate.
349
+ * and a critical error has occurred
220
350
  *
351
+ * Requires DeviceError to be created
221
352
  */
222
353
  terminate(error: Error, action: string) {
223
- return this.event('device.terminate', action, error)
354
+ return this.makeEvent('device.terminate', action, error, [])
224
355
  }
225
356
  }
@@ -6,17 +6,14 @@
6
6
  import DevicePort from "./DevicePort"
7
7
 
8
8
  /**
9
- * Класс для соедиения портов устройств
10
- *
9
+ * Class for connecting device ports
10
+ * Using inside Container class
11
11
  */
12
12
  export default class {
13
13
  outputLink: DevicePort
14
14
  inputLink: DevicePort
15
15
 
16
16
  /**
17
- * Инициализация соединения, требует 2 порта которые привязаны
18
- * к устройствам
19
- *
20
17
  */
21
18
  constructor(output: DevicePort, input: DevicePort) {
22
19
  this.outputLink = output
@@ -26,9 +23,8 @@ export default class {
26
23
  }
27
24
 
28
25
  /**
29
- * Вызов входящего порта при вызове соединения
30
- *
31
- * @param {any} data Данные
26
+ * Handles communication between two device ports
27
+ * @param data Data sent by the device when the push port is invoked
32
28
  */
33
29
  push(data: any): any {
34
30
  return this.inputLink.push(data)
@@ -5,17 +5,34 @@
5
5
 
6
6
  import IPort from "../ports/IPort"
7
7
  import DeviceConnect from "./DeviceConnect"
8
+ import Utility from "../Utility"
8
9
 
9
10
  /**
10
- * Класс для реализации порта устройства
11
- * Порт может быть как входящий так и исходящий
11
+ * A class to implement a device port.
12
+ * The port can be either incoming or outgoing
12
13
  */
13
14
  export default class DevicePort {
15
+ /** Flag to determine if the port is connected */
14
16
  connected = false
17
+
18
+ /** Port connection list. One port can have multiple connections */
15
19
  connections: Array<DeviceConnect> = []
20
+
21
+ /** Port ID */
16
22
  id: string
23
+ /** Port type */
17
24
  type: string
25
+
26
+ /** Flag determines whether the port should be connected */
18
27
  required: boolean
28
+
29
+ /**
30
+ * Список слушателей порта
31
+ * Используется для захвата порта. Если какие либо данные будут проброшены
32
+ * в порт, они будут переданы для каждого вызнванного слушателя
33
+ */
34
+ listens = new Map<number, (data:any) => void>()
35
+
19
36
  constructor(id: string, port: IPort) {
20
37
  this.id = id
21
38
  this.type = port.type
@@ -23,7 +40,7 @@ export default class DevicePort {
23
40
  }
24
41
 
25
42
  /**
26
- * Добавление связи в порт
43
+ * Adding communication to a port
27
44
  */
28
45
  addConnection(connection: DeviceConnect) {
29
46
  this.connected = true
@@ -31,16 +48,18 @@ export default class DevicePort {
31
48
  }
32
49
 
33
50
  /**
34
- * Вызов входящего порта при вызове соединения
35
- *
36
- * @param {any} data Данные
51
+ * Calling the incoming port when calling a connection
37
52
  */
38
53
  push(data: any): any {
39
- if (this.connected){
40
- if (this.connections.length === 1) return this.connections[0].push(data)
41
- for (const conn of this.connections){
42
- conn.push(data)
43
- }
54
+ // Если у нас есть слушатели порта
55
+ // Передаем им данные и пересоздаем Map
56
+ if (this.listens.size) {
57
+ const res = Utility.prettyFormat(data)
58
+ for (const ls of this.listens.values()) ls(res)
59
+ this.listens = new Map()
44
60
  }
61
+ if (!this.connected) return
62
+ if (this.connections.length === 1) return this.connections[0].push(data)
63
+ for (const conn of this.connections) conn.push(data)
45
64
  }
46
65
  }
@@ -1,5 +1,8 @@
1
1
  export default interface IDeviceEvent {
2
- id: string;
2
+ /** Device ID */
3
+ device: string;
4
+ /** event data string */
3
5
  data: string;
6
+ /** additional information */
4
7
  trace: any;
5
8
  }
@@ -1,9 +1,16 @@
1
1
  import IValidationRule from "./IValidationRule";
2
2
 
3
3
  export default interface IValidationProblem {
4
+ /** VRack Error manager short code like a VS_ERROR_DATABASE_NF */
4
5
  type: string;
6
+ /** VRack Error manager error code like a random string */
5
7
  code: string;
8
+ /** Error string (description) */
6
9
  description: string;
10
+ /** Exported validation rule */
7
11
  rule: IValidationRule
12
+ /** Additional arguments for error */
8
13
  arg: any;
14
+ /** key for getting value from object */
15
+ fieldKey: string;
9
16
  }
@@ -1,10 +1,22 @@
1
1
  import IValidationSubrule from "./IValidationSubrule";
2
2
 
3
3
  export default interface IValidationRule {
4
+ /** VRack Error manager short code like a VS_ERROR_DATABASE_NF */
4
5
  type: string;
6
+ /** VRack Error manager error code like a random string */
5
7
  require: boolean;
8
+ /** Error string (description) */
6
9
  default: any;
10
+ /** Exported validation rule */
7
11
  rules: Array<IValidationSubrule>;
12
+ /** Additional arguments for error */
8
13
  example: any;
14
+ /** key for getting value from object */
9
15
  description: string;
16
+ /**
17
+ * Template for error message string
18
+ * Use like a "{description} field must by like a '123' number "
19
+ * You can use {description} {value} {default} in template
20
+ */
21
+ message: string;
10
22
  }
@@ -1,5 +1,8 @@
1
1
 
2
2
  export default interface IValidationSubrule {
3
+ /** Name of subrule */
3
4
  name: string;
5
+
6
+ /** Subrule arguments */
4
7
  args: any;
5
8
  }
@@ -3,15 +3,20 @@
3
3
  * Licensed under the Apache License, Version 2.0
4
4
  */
5
5
 
6
+ import AnyType from "./types/AnyType";
6
7
  import ArrayType from "./types/ArrayType";
8
+ import BooleanType from "./types/BooleanType";
9
+ import FunctionType from "./types/FunctionType";
7
10
  import NumberType from "./types/NumberType";
8
11
  import ObjectType from "./types/ObjectType";
9
12
  import StringType from "./types/StringType";
10
13
 
11
14
 
12
- /**
13
- */
14
15
  export default class Rule {
16
+ static any() {
17
+ return new AnyType()
18
+ }
19
+
15
20
  static number() {
16
21
  return new NumberType()
17
22
  }
@@ -27,4 +32,13 @@ export default class Rule {
27
32
  static array (){
28
33
  return new ArrayType()
29
34
  }
35
+
36
+ static boolean (){
37
+ return new BooleanType()
38
+ }
39
+
40
+ static function (){
41
+ return new FunctionType()
42
+ }
43
+
30
44
  }