@matreshka/bff 0.9.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 (275) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +35 -0
  3. package/dist/components/actions/server-action.d.ts +30 -0
  4. package/dist/components/actions/server-action.js +23 -0
  5. package/dist/components/aliases/button.d.ts +17 -0
  6. package/dist/components/aliases/button.js +54 -0
  7. package/dist/components/aliases/column.d.ts +11 -0
  8. package/dist/components/aliases/column.js +31 -0
  9. package/dist/components/aliases/row.d.ts +11 -0
  10. package/dist/components/aliases/row.js +31 -0
  11. package/dist/components/aliases/surface.d.ts +11 -0
  12. package/dist/components/aliases/surface.js +30 -0
  13. package/dist/components/app.d.ts +5 -0
  14. package/dist/components/app.js +12 -0
  15. package/dist/components/board.d.ts +58 -0
  16. package/dist/components/board.js +152 -0
  17. package/dist/components/boot.d.ts +2 -0
  18. package/dist/components/boot.js +39 -0
  19. package/dist/components/camera.d.ts +77 -0
  20. package/dist/components/camera.js +116 -0
  21. package/dist/components/charts/bar-chart.d.ts +14 -0
  22. package/dist/components/charts/bar-chart.js +27 -0
  23. package/dist/components/charts/chart.d.ts +69 -0
  24. package/dist/components/charts/chart.js +42 -0
  25. package/dist/components/charts/doughnut-chart.d.ts +14 -0
  26. package/dist/components/charts/doughnut-chart.js +27 -0
  27. package/dist/components/charts/line-chart.d.ts +14 -0
  28. package/dist/components/charts/line-chart.js +27 -0
  29. package/dist/components/charts/pie-chart.d.ts +14 -0
  30. package/dist/components/charts/pie-chart.js +27 -0
  31. package/dist/components/charts/polar-area-chart.d.ts +14 -0
  32. package/dist/components/charts/polar-area-chart.js +27 -0
  33. package/dist/components/charts/radar-chart.d.ts +14 -0
  34. package/dist/components/charts/radar-chart.js +27 -0
  35. package/dist/components/component.d.ts +159 -0
  36. package/dist/components/component.js +380 -0
  37. package/dist/components/container.d.ts +48 -0
  38. package/dist/components/container.js +80 -0
  39. package/dist/components/dialog.d.ts +83 -0
  40. package/dist/components/dialog.js +120 -0
  41. package/dist/components/entry-component.d.ts +34 -0
  42. package/dist/components/entry-component.js +74 -0
  43. package/dist/components/enum/password-input-kind.d.ts +1 -0
  44. package/dist/components/enum/password-input-kind.js +5 -0
  45. package/dist/components/enum/popover-position-area.d.ts +1 -0
  46. package/dist/components/enum/popover-position-area.js +5 -0
  47. package/dist/components/enum/text-input-kind.d.ts +1 -0
  48. package/dist/components/enum/text-input-kind.js +5 -0
  49. package/dist/components/enum/textarea-resize.d.ts +1 -0
  50. package/dist/components/enum/textarea-resize.js +5 -0
  51. package/dist/components/file-upload-area.d.ts +79 -0
  52. package/dist/components/file-upload-area.js +138 -0
  53. package/dist/components/for-each.d.ts +188 -0
  54. package/dist/components/for-each.js +362 -0
  55. package/dist/components/form.d.ts +62 -0
  56. package/dist/components/form.js +92 -0
  57. package/dist/components/grid.d.ts +80 -0
  58. package/dist/components/grid.js +79 -0
  59. package/dist/components/index.d.ts +55 -0
  60. package/dist/components/index.js +76 -0
  61. package/dist/components/inputs/input-component.d.ts +37 -0
  62. package/dist/components/inputs/input-component.js +30 -0
  63. package/dist/components/inputs/number-input.d.ts +45 -0
  64. package/dist/components/inputs/number-input.js +43 -0
  65. package/dist/components/inputs/password-input.d.ts +28 -0
  66. package/dist/components/inputs/password-input.js +42 -0
  67. package/dist/components/inputs/text-editor.d.ts +91 -0
  68. package/dist/components/inputs/text-editor.js +282 -0
  69. package/dist/components/inputs/text-input.d.ts +48 -0
  70. package/dist/components/inputs/text-input.js +40 -0
  71. package/dist/components/inputs/textarea.d.ts +36 -0
  72. package/dist/components/inputs/textarea.js +42 -0
  73. package/dist/components/item-list/flatten-nested-items.d.ts +11 -0
  74. package/dist/components/item-list/flatten-nested-items.js +100 -0
  75. package/dist/components/item-list/index.d.ts +5 -0
  76. package/dist/components/item-list/index.js +21 -0
  77. package/dist/components/item-list/item-list-host.d.ts +10 -0
  78. package/dist/components/item-list/item-list-host.js +2 -0
  79. package/dist/components/item-list/item-list.d.ts +68 -0
  80. package/dist/components/item-list/item-list.js +206 -0
  81. package/dist/components/item-list/list-from-ref-context.d.ts +11 -0
  82. package/dist/components/item-list/list-from-ref-context.js +27 -0
  83. package/dist/components/item-list/nested-items-host-support.d.ts +36 -0
  84. package/dist/components/item-list/nested-items-host-support.js +109 -0
  85. package/dist/components/item-list/types.d.ts +40 -0
  86. package/dist/components/item-list/types.js +13 -0
  87. package/dist/components/line.d.ts +43 -0
  88. package/dist/components/line.js +35 -0
  89. package/dist/components/map.d.ts +83 -0
  90. package/dist/components/map.js +146 -0
  91. package/dist/components/outputs/currency.d.ts +63 -0
  92. package/dist/components/outputs/currency.js +42 -0
  93. package/dist/components/outputs/datetime.d.ts +69 -0
  94. package/dist/components/outputs/datetime.js +49 -0
  95. package/dist/components/outputs/icon.d.ts +43 -0
  96. package/dist/components/outputs/icon.js +38 -0
  97. package/dist/components/outputs/iframe.d.ts +48 -0
  98. package/dist/components/outputs/iframe.js +44 -0
  99. package/dist/components/outputs/image.d.ts +73 -0
  100. package/dist/components/outputs/image.js +63 -0
  101. package/dist/components/outputs/number.d.ts +39 -0
  102. package/dist/components/outputs/number.js +47 -0
  103. package/dist/components/outputs/output-component.d.ts +58 -0
  104. package/dist/components/outputs/output-component.js +50 -0
  105. package/dist/components/outputs/progress-bar.d.ts +33 -0
  106. package/dist/components/outputs/progress-bar.js +42 -0
  107. package/dist/components/outputs/progress-spinner.d.ts +37 -0
  108. package/dist/components/outputs/progress-spinner.js +43 -0
  109. package/dist/components/outputs/qr-code.d.ts +28 -0
  110. package/dist/components/outputs/qr-code.js +40 -0
  111. package/dist/components/outputs/text.d.ts +57 -0
  112. package/dist/components/outputs/text.js +78 -0
  113. package/dist/components/outputs/vector.d.ts +47 -0
  114. package/dist/components/outputs/vector.js +53 -0
  115. package/dist/components/page.d.ts +96 -0
  116. package/dist/components/page.js +127 -0
  117. package/dist/components/popover.d.ts +63 -0
  118. package/dist/components/popover.js +96 -0
  119. package/dist/components/stack.d.ts +158 -0
  120. package/dist/components/stack.js +146 -0
  121. package/dist/components/types/component-sequence.d.ts +3 -0
  122. package/dist/components/types/component-sequence.js +2 -0
  123. package/dist/components/types/container-overlay.d.ts +3 -0
  124. package/dist/components/types/container-overlay.js +2 -0
  125. package/dist/components/utils/component-factory-shared.d.ts +4 -0
  126. package/dist/components/utils/component-factory-shared.js +12 -0
  127. package/dist/core/actions/action.d.ts +35 -0
  128. package/dist/core/actions/action.js +45 -0
  129. package/dist/core/actions/animate-component.d.ts +58 -0
  130. package/dist/core/actions/animate-component.js +57 -0
  131. package/dist/core/actions/local-action.d.ts +8 -0
  132. package/dist/core/actions/local-action.js +12 -0
  133. package/dist/core/actions/set-context-value.d.ts +18 -0
  134. package/dist/core/actions/set-context-value.js +32 -0
  135. package/dist/core/actions/set-context-values.d.ts +34 -0
  136. package/dist/core/actions/set-context-values.js +30 -0
  137. package/dist/core/actions/toggle-context-value.d.ts +21 -0
  138. package/dist/core/actions/toggle-context-value.js +30 -0
  139. package/dist/core/actions/write-text-to-clipboard.d.ts +30 -0
  140. package/dist/core/actions/write-text-to-clipboard.js +44 -0
  141. package/dist/core/boot.d.ts +2 -0
  142. package/dist/core/boot.js +8 -0
  143. package/dist/core/client-context.d.ts +7 -0
  144. package/dist/core/client-context.js +20 -0
  145. package/dist/core/client.d.ts +133 -0
  146. package/dist/core/client.js +292 -0
  147. package/dist/core/conditions/condition-group.d.ts +14 -0
  148. package/dist/core/conditions/condition-group.js +30 -0
  149. package/dist/core/conditions/condition-operand.d.ts +27 -0
  150. package/dist/core/conditions/condition-operand.js +15 -0
  151. package/dist/core/conditions/condition.d.ts +27 -0
  152. package/dist/core/conditions/condition.js +35 -0
  153. package/dist/core/conditions/context-array-includes.d.ts +32 -0
  154. package/dist/core/conditions/context-array-includes.js +52 -0
  155. package/dist/core/conditions/context-array-length.d.ts +86 -0
  156. package/dist/core/conditions/context-array-length.js +155 -0
  157. package/dist/core/conditions/context-value-defined.d.ts +12 -0
  158. package/dist/core/conditions/context-value-defined.js +21 -0
  159. package/dist/core/conditions/context-value-equal.d.ts +14 -0
  160. package/dist/core/conditions/context-value-equal.js +26 -0
  161. package/dist/core/conditions/context-value-in.d.ts +17 -0
  162. package/dist/core/conditions/context-value-in.js +26 -0
  163. package/dist/core/conditions/context-value-not-equal.d.ts +14 -0
  164. package/dist/core/conditions/context-value-not-equal.js +26 -0
  165. package/dist/core/conditions/context-value-undefined.d.ts +12 -0
  166. package/dist/core/conditions/context-value-undefined.js +21 -0
  167. package/dist/core/conditions/desktop-device.d.ts +11 -0
  168. package/dist/core/conditions/desktop-device.js +21 -0
  169. package/dist/core/conditions/groups.d.ts +71 -0
  170. package/dist/core/conditions/groups.js +74 -0
  171. package/dist/core/conditions/index.d.ts +17 -0
  172. package/dist/core/conditions/index.js +33 -0
  173. package/dist/core/conditions/mobile-device.d.ts +11 -0
  174. package/dist/core/conditions/mobile-device.js +21 -0
  175. package/dist/core/conditions/not-desktop-device.d.ts +11 -0
  176. package/dist/core/conditions/not-desktop-device.js +21 -0
  177. package/dist/core/conditions/not-mobile-device.d.ts +11 -0
  178. package/dist/core/conditions/not-mobile-device.js +21 -0
  179. package/dist/core/conditions/not-tablet-device.d.ts +11 -0
  180. package/dist/core/conditions/not-tablet-device.js +21 -0
  181. package/dist/core/conditions/tablet-device.d.ts +11 -0
  182. package/dist/core/conditions/tablet-device.js +21 -0
  183. package/dist/core/context/context-ref.d.ts +48 -0
  184. package/dist/core/context/context-ref.js +58 -0
  185. package/dist/core/context/context.d.ts +121 -0
  186. package/dist/core/context/context.js +353 -0
  187. package/dist/core/entry-context.d.ts +14 -0
  188. package/dist/core/entry-context.js +31 -0
  189. package/dist/core/gateway-connection.d.ts +29 -0
  190. package/dist/core/gateway-connection.js +146 -0
  191. package/dist/core/index.d.ts +30 -0
  192. package/dist/core/index.js +46 -0
  193. package/dist/core/matreshka.d.ts +61 -0
  194. package/dist/core/matreshka.js +186 -0
  195. package/dist/core/router.d.ts +38 -0
  196. package/dist/core/router.js +116 -0
  197. package/dist/core/types/client-settings.d.ts +31 -0
  198. package/dist/core/types/client-settings.js +2 -0
  199. package/dist/core/types/component-instance.d.ts +25 -0
  200. package/dist/core/types/component-instance.js +42 -0
  201. package/dist/core/types/component-tree-node.d.ts +11 -0
  202. package/dist/core/types/component-tree-node.js +18 -0
  203. package/dist/core/types/componentable.d.ts +21 -0
  204. package/dist/core/types/componentable.js +2 -0
  205. package/dist/core/types/context-ref-primitive-value.d.ts +5 -0
  206. package/dist/core/types/context-ref-primitive-value.js +2 -0
  207. package/dist/core/types/message.d.ts +15 -0
  208. package/dist/core/types/message.js +2 -0
  209. package/dist/core/types/mixed-with-callbacks-array.d.ts +9 -0
  210. package/dist/core/types/mixed-with-callbacks-array.js +2 -0
  211. package/dist/core/types/native-picker-context-ref.d.ts +7 -0
  212. package/dist/core/types/native-picker-context-ref.js +2 -0
  213. package/dist/core/types/pageable.d.ts +15 -0
  214. package/dist/core/types/pageable.js +2 -0
  215. package/dist/core/types/standalone-component.d.ts +9 -0
  216. package/dist/core/types/standalone-component.js +2 -0
  217. package/dist/core/types/status-code.d.ts +319 -0
  218. package/dist/core/types/status-code.js +322 -0
  219. package/dist/core/utils/calculate-components.d.ts +13 -0
  220. package/dist/core/utils/calculate-components.js +40 -0
  221. package/dist/core/utils/color-token-id.d.ts +11 -0
  222. package/dist/core/utils/color-token-id.js +24 -0
  223. package/dist/core/utils/deep-pick.d.ts +2 -0
  224. package/dist/core/utils/deep-pick.js +54 -0
  225. package/dist/core/utils/hex-to-hsl.d.ts +14 -0
  226. package/dist/core/utils/hex-to-hsl.js +49 -0
  227. package/dist/core/utils/incoming-message-observer.d.ts +9 -0
  228. package/dist/core/utils/incoming-message-observer.js +23 -0
  229. package/dist/core/utils/merge-deep.d.ts +8 -0
  230. package/dist/core/utils/merge-deep.js +39 -0
  231. package/dist/core/utils/objects-diff.d.ts +13 -0
  232. package/dist/core/utils/objects-diff.js +56 -0
  233. package/dist/core/utils/parse-context-path.d.ts +4 -0
  234. package/dist/core/utils/parse-context-path.js +16 -0
  235. package/dist/core/utils/replace-context-keys.d.ts +12 -0
  236. package/dist/core/utils/replace-context-keys.js +90 -0
  237. package/dist/core/utils/serialize-component-tree.d.ts +9 -0
  238. package/dist/core/utils/serialize-component-tree.js +24 -0
  239. package/dist/core/utils/set-object-property.d.ts +2 -0
  240. package/dist/core/utils/set-object-property.js +29 -0
  241. package/dist/core/utils/track-created-instances.d.ts +10 -0
  242. package/dist/core/utils/track-created-instances.js +18 -0
  243. package/dist/core/version.d.ts +1 -0
  244. package/dist/core/version.js +21 -0
  245. package/dist/index.d.ts +3 -0
  246. package/dist/index.js +19 -0
  247. package/dist/platforms/android-platform.d.ts +6 -0
  248. package/dist/platforms/android-platform.js +10 -0
  249. package/dist/platforms/browser-platform.d.ts +79 -0
  250. package/dist/platforms/browser-platform.js +143 -0
  251. package/dist/platforms/client-platform.d.ts +6 -0
  252. package/dist/platforms/client-platform.js +10 -0
  253. package/dist/platforms/index.d.ts +12 -0
  254. package/dist/platforms/index.js +28 -0
  255. package/dist/platforms/ios-platform.d.ts +6 -0
  256. package/dist/platforms/ios-platform.js +10 -0
  257. package/dist/platforms/max-mini-app-platform.d.ts +45 -0
  258. package/dist/platforms/max-mini-app-platform.js +87 -0
  259. package/dist/platforms/mobile-platform.d.ts +117 -0
  260. package/dist/platforms/mobile-platform.js +316 -0
  261. package/dist/platforms/platform.d.ts +109 -0
  262. package/dist/platforms/platform.js +224 -0
  263. package/dist/platforms/pwa-platform.d.ts +6 -0
  264. package/dist/platforms/pwa-platform.js +10 -0
  265. package/dist/platforms/server-platform.d.ts +6 -0
  266. package/dist/platforms/server-platform.js +10 -0
  267. package/dist/platforms/telegram-mini-app-platform.d.ts +87 -0
  268. package/dist/platforms/telegram-mini-app-platform.js +166 -0
  269. package/dist/platforms/utils/client-platform.d.ts +4 -0
  270. package/dist/platforms/utils/client-platform.js +38 -0
  271. package/dist/platforms/utils/mobile-ble-services.d.ts +3 -0
  272. package/dist/platforms/utils/mobile-ble-services.js +31 -0
  273. package/dist/platforms/web-platform.d.ts +9 -0
  274. package/dist/platforms/web-platform.js +13 -0
  275. package/package.json +109 -0
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SetContextValues = void 0;
4
+ exports.setContextValues = setContextValues;
5
+ const local_action_1 = require("./local-action");
6
+ /**
7
+ * Batch-запись значений в Context на клиенте (с sync на BFF через `context-values`).
8
+ */
9
+ class SetContextValues extends local_action_1.LocalAction {
10
+ constructor(values, config = {}) {
11
+ super(config.conditions);
12
+ this.values = values;
13
+ }
14
+ class() {
15
+ return "set-context-values";
16
+ }
17
+ payload() {
18
+ return {
19
+ values: this.values.map(({ ref, value }) => ({ ref, value })),
20
+ };
21
+ }
22
+ }
23
+ exports.SetContextValues = SetContextValues;
24
+ /**
25
+ * Функциональная форма {@link SetContextValues}.
26
+ * У каждого элемента массива тип `value` должен совпадать с типом значения по `ref`.
27
+ */
28
+ function setContextValues(values, config = {}) {
29
+ return new SetContextValues(values, config);
30
+ }
@@ -0,0 +1,21 @@
1
+ import { ContextRef, ContextRefValue } from "../context/context-ref";
2
+ import { ActionConfig } from "./action";
3
+ import { LocalAction } from "./local-action";
4
+ /**
5
+ * `ContextRef`, значение которого — `boolean` (допустимо `boolean | undefined`).
6
+ */
7
+ export type BooleanContextRef<R extends ContextRef<any, any>> = Exclude<ContextRefValue<R>, undefined> extends boolean ? R : never;
8
+ /**
9
+ * Инверсия boolean-значения в Context на клиенте (с sync на BFF через `context-values`).
10
+ */
11
+ export declare class ToggleContextValue extends LocalAction {
12
+ private readonly ref;
13
+ constructor(ref: ContextRef<any, any>, config?: ActionConfig);
14
+ class(): string;
15
+ payload(): object;
16
+ }
17
+ /**
18
+ * Функциональная форма {@link ToggleContextValue}.
19
+ * Принимает только `ContextRef` с boolean-значением.
20
+ */
21
+ export declare function toggleContextValue<R extends ContextRef<any, any>>(ref: BooleanContextRef<R>, config?: ActionConfig): ToggleContextValue;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToggleContextValue = void 0;
4
+ exports.toggleContextValue = toggleContextValue;
5
+ const local_action_1 = require("./local-action");
6
+ /**
7
+ * Инверсия boolean-значения в Context на клиенте (с sync на BFF через `context-values`).
8
+ */
9
+ class ToggleContextValue extends local_action_1.LocalAction {
10
+ constructor(ref, config = {}) {
11
+ super(config.conditions);
12
+ this.ref = ref;
13
+ }
14
+ class() {
15
+ return "toggle-context-value";
16
+ }
17
+ payload() {
18
+ return {
19
+ ref: this.ref,
20
+ };
21
+ }
22
+ }
23
+ exports.ToggleContextValue = ToggleContextValue;
24
+ /**
25
+ * Функциональная форма {@link ToggleContextValue}.
26
+ * Принимает только `ContextRef` с boolean-значением.
27
+ */
28
+ function toggleContextValue(ref, config = {}) {
29
+ return new ToggleContextValue(ref, config);
30
+ }
@@ -0,0 +1,30 @@
1
+ import { ActionConfig } from "./action";
2
+ import { LocalAction } from "./local-action";
3
+ /**
4
+ * Действие для записи текста в буфер обмена на клиенте.
5
+ */
6
+ export declare class WriteTextToClipboard extends LocalAction {
7
+ private text;
8
+ /**
9
+ * Создаёт экземпляр действия записи текста в буфер обмена.
10
+ *
11
+ * @param text Текст, который необходимо скопировать в буфер обмена.
12
+ */
13
+ constructor(text: string, config?: ActionConfig);
14
+ /**
15
+ * Возвращает уникальный идентификатор класса действия.
16
+ *
17
+ * @returns Строка `"write-text-to-clipboard"`.
18
+ */
19
+ class(): string;
20
+ /**
21
+ * Возвращает полезную нагрузку действия, содержащую текст.
22
+ *
23
+ * @returns Объект с полем `text`.
24
+ */
25
+ payload(): object;
26
+ }
27
+ /**
28
+ * Функциональная форма {@link WriteTextToClipboard}.
29
+ */
30
+ export declare function writeTextToClipboard(text: string, config?: ActionConfig): WriteTextToClipboard;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WriteTextToClipboard = void 0;
4
+ exports.writeTextToClipboard = writeTextToClipboard;
5
+ const local_action_1 = require("./local-action");
6
+ /**
7
+ * Действие для записи текста в буфер обмена на клиенте.
8
+ */
9
+ class WriteTextToClipboard extends local_action_1.LocalAction {
10
+ /**
11
+ * Создаёт экземпляр действия записи текста в буфер обмена.
12
+ *
13
+ * @param text Текст, который необходимо скопировать в буфер обмена.
14
+ */
15
+ constructor(text, config = {}) {
16
+ super(config.conditions);
17
+ this.text = text;
18
+ }
19
+ /**
20
+ * Возвращает уникальный идентификатор класса действия.
21
+ *
22
+ * @returns Строка `"write-text-to-clipboard"`.
23
+ */
24
+ class() {
25
+ return "write-text-to-clipboard";
26
+ }
27
+ /**
28
+ * Возвращает полезную нагрузку действия, содержащую текст.
29
+ *
30
+ * @returns Объект с полем `text`.
31
+ */
32
+ payload() {
33
+ return {
34
+ text: this.text,
35
+ };
36
+ }
37
+ }
38
+ exports.WriteTextToClipboard = WriteTextToClipboard;
39
+ /**
40
+ * Функциональная форма {@link WriteTextToClipboard}.
41
+ */
42
+ function writeTextToClipboard(text, config = {}) {
43
+ return new WriteTextToClipboard(text, config);
44
+ }
@@ -0,0 +1,2 @@
1
+ import { Matreshka } from "./matreshka";
2
+ export declare const bootCore: (_matreshka: Matreshka) => void;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bootCore = void 0;
4
+ const register_messages_1 = require("@matreshka/shared/messages/client-to-bff/register-messages");
5
+ const bootCore = (_matreshka) => {
6
+ (0, register_messages_1.registerClientToBffMessages)(); // Чтобы парсить сообщения от клиента
7
+ };
8
+ exports.bootCore = bootCore;
@@ -0,0 +1,7 @@
1
+ import type { Client } from "./client";
2
+ /**
3
+ * Возвращает текущего клиента из AsyncLocalStorage (если обработка выполняется внутри Client.newMessage()).
4
+ */
5
+ export declare function currentClient(): Client;
6
+ /** @internal */
7
+ export declare function runWithClient<T>(client: Client, fn: () => T): T;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.currentClient = currentClient;
4
+ exports.runWithClient = runWithClient;
5
+ const node_async_hooks_1 = require("node:async_hooks");
6
+ const clientStorage = new node_async_hooks_1.AsyncLocalStorage();
7
+ /**
8
+ * Возвращает текущего клиента из AsyncLocalStorage (если обработка выполняется внутри Client.newMessage()).
9
+ */
10
+ function currentClient() {
11
+ const client = clientStorage.getStore();
12
+ if (!client) {
13
+ throw new Error("currentClient() available only in matreshka context");
14
+ }
15
+ return client;
16
+ }
17
+ /** @internal */
18
+ function runWithClient(client, fn) {
19
+ return clientStorage.run(client, fn);
20
+ }
@@ -0,0 +1,133 @@
1
+ import { BrowserEngine } from "@matreshka/shared/enums/browser-engine";
2
+ import { BrowserName } from "@matreshka/shared/enums/browser-name";
3
+ import { DeviceType } from "@matreshka/shared/enums/device-type";
4
+ import { OsName } from "@matreshka/shared/enums/os-name";
5
+ import { PlatformId } from "@matreshka/shared/enums/platform-id";
6
+ import { BffToClientMessage } from "@matreshka/shared/messages/bff-to-client/bff-to-client-message";
7
+ import { ClientToBffMessage } from "@matreshka/shared/messages/client-to-bff/client-to-bff-message";
8
+ import { ClientState } from "@matreshka/shared/types/client-state";
9
+ import { BehaviorSubject, Subject } from "rxjs";
10
+ import { z } from "zod/v4";
11
+ import { Page } from "../components";
12
+ import { App } from "../components/app";
13
+ import { ComponentInstance } from "./types/component-instance";
14
+ import { type ComponentTreeNode } from "./types/component-tree-node";
15
+ /**
16
+ * Схема состояния клиента, определяющая структуру и типы данных, передаваемых от клиента.
17
+ *
18
+ * @property route Информация о маршруте.
19
+ * @property route.visitedAt Временная метка последнего посещения.
20
+ * @property route.path Путь текущего маршрута.
21
+ * @property route.query Параметры запроса в виде пар ключ-значение.
22
+ * @property storage Клиентское хранилище в виде словаря строк.
23
+ * @property language Текущий язык интерфейса.
24
+ * @property userAgent Строка User-Agent в исходном виде, как ее отдает браузер.
25
+ * @property prefersColorScheme Предпочтительная цветовая схема клиента: "light" или "dark".
26
+ * @property platform Информация о платформе клиента.
27
+ * @property platform.id Идентификатор платформы.
28
+ * @property platform.payload Дополнительные данные о платформе.
29
+ */
30
+ export declare const ClientHandshakePayloadSchema: z.ZodObject<{
31
+ applicationId: z.ZodString;
32
+ }, z.core.$strict>;
33
+ export declare const ClientStateSchema: z.ZodObject<{
34
+ route: z.ZodObject<{
35
+ visitedAt: z.ZodNumber;
36
+ path: z.ZodString;
37
+ query: z.ZodRecord<z.ZodString, z.ZodString>;
38
+ }, z.core.$strict>;
39
+ storage: z.ZodRecord<z.ZodString, z.ZodString>;
40
+ language: z.ZodString;
41
+ userAgent: z.ZodString;
42
+ prefersColorScheme: z.ZodLiteral<"light" | "dark" | "system">;
43
+ platform: z.ZodObject<{
44
+ id: z.ZodEnum<typeof PlatformId>;
45
+ payload: z.ZodUnknown;
46
+ }, z.core.$strict>;
47
+ }, z.core.$strict>;
48
+ export declare class Client {
49
+ incomingMessage$: Subject<ClientToBffMessage<unknown>>;
50
+ outcomingMessage$: Subject<BffToClientMessage<unknown>>;
51
+ ping$: BehaviorSubject<number | undefined>;
52
+ reconnect$: Subject<void>;
53
+ disconnect$: Subject<void>;
54
+ destroy$: Subject<void>;
55
+ error$: Subject<unknown>;
56
+ app: App;
57
+ /**
58
+ * Id страницы, для которой при навигации нужно снять обработчики предыдущей страницы.
59
+ * Диалоги/popover/оверлеи сюда не входят — их снимают по AppDestroyEntryInstanceMessage или removeGlobalComponent.
60
+ */
61
+ private currentPageInstance?;
62
+ private appOverlayEntry?;
63
+ private transportSend?;
64
+ private readonly reliableDelivery;
65
+ readonly state$: BehaviorSubject<ClientState>;
66
+ readonly applicationId$: BehaviorSubject<string | undefined>;
67
+ /**
68
+ * Создает новый экземпляр клиента.
69
+ *
70
+ * @param initState Начальное состояние клиента.
71
+ */
72
+ constructor();
73
+ /**
74
+ * Подключает transport-слой для фактической отправки сообщений клиенту.
75
+ *
76
+ * Вызывается при каждом новом соединении; предыдущий transport снимается автоматически.
77
+ */
78
+ attachTransport(send: (message: BffToClientMessage) => void): void;
79
+ /**
80
+ * Отключает transport-слой без уничтожения клиента (grace period).
81
+ */
82
+ detachTransport(): void;
83
+ /**
84
+ * Entry instance для сериализации глобальных App-оверлеев (platform.setOverlays).
85
+ */
86
+ ensureAppOverlayEntry(): ComponentInstance<App>;
87
+ /**
88
+ * Завершает работу клиента и завершает потоки сообщений.
89
+ */
90
+ destroy(): void;
91
+ /**
92
+ * Обрабатывает новое входящее сообщение в виде строки.
93
+ *
94
+ * @param messageString Строка с сериализованным сообщением.
95
+ */
96
+ newMessage(messageString: string): void;
97
+ /**
98
+ * Переход на другую страницу: снимает обработчики с предыдущей страницы и запоминает id новой.
99
+ */
100
+ switchPage(newPageInstance: ComponentInstance<Page>): void;
101
+ /**
102
+ * Снимает использования глобального компонента (оверлеи платформы и т.п.) для этого клиента.
103
+ */
104
+ removeGlobalComponent(node: ComponentTreeNode): void;
105
+ browserVersion(): string | null;
106
+ browserName(): BrowserName;
107
+ browserEngine(): BrowserEngine;
108
+ osName(): OsName;
109
+ deviceType(): DeviceType;
110
+ /**
111
+ * Возвращает значение из клиентского хранилища по заданному ключу.
112
+ *
113
+ * @param key Ключ значения.
114
+ * @returns Значение, если оно существует.
115
+ */
116
+ getStorageValue(key: string): string;
117
+ /**
118
+ * Устанавливает значение в клиентское хранилище и отправляет соответствующее сообщение.
119
+ *
120
+ * @param key Ключ значения.
121
+ * @param value Значение или undefined для удаления.
122
+ * @returns Ссылку на текущий экземпляр клиента.
123
+ */
124
+ setStorageValue(key: string, value: string | undefined): this;
125
+ /**
126
+ * Удаляет значение из хранилища по ключу.
127
+ *
128
+ * @param key Ключ для удаления.
129
+ * @returns Ссылку на текущий экземпляр клиента.
130
+ */
131
+ clearStorageValue(key: string): this;
132
+ private forwardToTransport;
133
+ }
@@ -0,0 +1,292 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Client = exports.ClientStateSchema = exports.ClientHandshakePayloadSchema = void 0;
4
+ const shared_1 = require("@matreshka/shared");
5
+ const browser_engine_1 = require("@matreshka/shared/enums/browser-engine");
6
+ const browser_name_1 = require("@matreshka/shared/enums/browser-name");
7
+ const platform_id_1 = require("@matreshka/shared/enums/platform-id");
8
+ const index_1 = require("@matreshka/shared/messages/bff-to-client/app/index");
9
+ const message_received_message_1 = require("@matreshka/shared/messages/bff-to-client/message-received-message");
10
+ const app_client_state_message_1 = require("@matreshka/shared/messages/client-to-bff/app/app-client-state-message");
11
+ const handshake_message_1 = require("@matreshka/shared/messages/client-to-bff/app/handshake-message");
12
+ const message_received_message_2 = require("@matreshka/shared/messages/client-to-bff/message-received-message");
13
+ const parse_client_to_bff_message_1 = require("@matreshka/shared/messages/client-to-bff/parse-client-to-bff-message");
14
+ const reliable_delivery_1 = require("@matreshka/shared/messages/reliable-delivery");
15
+ const fetch_from_object_1 = require("@matreshka/shared/utils/fetch-from-object");
16
+ const rxjs_1 = require("rxjs");
17
+ const v4_1 = require("zod/v4");
18
+ const app_1 = require("../components/app");
19
+ const component_1 = require("../components/component");
20
+ const client_context_1 = require("./client-context");
21
+ const component_tree_node_1 = require("./types/component-tree-node");
22
+ const incoming_message_observer_1 = require("./utils/incoming-message-observer");
23
+ const set_object_property_1 = require("./utils/set-object-property");
24
+ const resolveOsNameFromUserAgent = shared_1.getOsNameFromUserAgent;
25
+ const resolveDeviceTypeFromUserAgent = shared_1.getDeviceTypeFromUserAgent;
26
+ /**
27
+ * Схема состояния клиента, определяющая структуру и типы данных, передаваемых от клиента.
28
+ *
29
+ * @property route Информация о маршруте.
30
+ * @property route.visitedAt Временная метка последнего посещения.
31
+ * @property route.path Путь текущего маршрута.
32
+ * @property route.query Параметры запроса в виде пар ключ-значение.
33
+ * @property storage Клиентское хранилище в виде словаря строк.
34
+ * @property language Текущий язык интерфейса.
35
+ * @property userAgent Строка User-Agent в исходном виде, как ее отдает браузер.
36
+ * @property prefersColorScheme Предпочтительная цветовая схема клиента: "light" или "dark".
37
+ * @property platform Информация о платформе клиента.
38
+ * @property platform.id Идентификатор платформы.
39
+ * @property platform.payload Дополнительные данные о платформе.
40
+ */
41
+ exports.ClientHandshakePayloadSchema = v4_1.z.strictObject({
42
+ applicationId: v4_1.z.string(),
43
+ });
44
+ exports.ClientStateSchema = v4_1.z.strictObject({
45
+ route: v4_1.z.strictObject({
46
+ visitedAt: v4_1.z.number(),
47
+ path: v4_1.z.string(),
48
+ query: v4_1.z.record(v4_1.z.string(), v4_1.z.string()),
49
+ }),
50
+ storage: v4_1.z.record(v4_1.z.string(), v4_1.z.string()),
51
+ language: v4_1.z.string(),
52
+ userAgent: v4_1.z.string(),
53
+ prefersColorScheme: v4_1.z.literal(["light", "dark", "system"]),
54
+ platform: v4_1.z.strictObject({
55
+ id: v4_1.z.enum(platform_id_1.PlatformId),
56
+ payload: v4_1.z.unknown(),
57
+ }),
58
+ });
59
+ class Client {
60
+ /**
61
+ * Создает новый экземпляр клиента.
62
+ *
63
+ * @param initState Начальное состояние клиента.
64
+ */
65
+ constructor() {
66
+ this.incomingMessage$ = new rxjs_1.Subject();
67
+ this.outcomingMessage$ = new rxjs_1.Subject();
68
+ this.ping$ = new rxjs_1.BehaviorSubject(undefined);
69
+ this.reconnect$ = new rxjs_1.Subject();
70
+ this.disconnect$ = new rxjs_1.Subject();
71
+ this.destroy$ = new rxjs_1.Subject();
72
+ this.error$ = new rxjs_1.Subject();
73
+ this.app = new app_1.App({});
74
+ this.reliableDelivery = new reliable_delivery_1.ReliableDelivery({
75
+ emitOutgoing: (message) => this.outcomingMessage$.next(message),
76
+ createReceipt: (payload) => new message_received_message_1.BffToClientMessageReceivedMessage(payload),
77
+ isReceiptMessage: (message) => message instanceof message_received_message_2.ClientToBffMessageReceivedMessage,
78
+ ping$: this.ping$,
79
+ });
80
+ this.applicationId$ = new rxjs_1.BehaviorSubject(undefined);
81
+ this.state$ = new rxjs_1.BehaviorSubject(undefined);
82
+ this.outcomingMessage$.subscribe((message) => {
83
+ this.reliableDelivery.observeOutgoing(message);
84
+ this.forwardToTransport(message);
85
+ });
86
+ this.disconnect$.subscribe(() => {
87
+ this.reliableDelivery.pause();
88
+ });
89
+ this.reconnect$.subscribe(() => {
90
+ this.reliableDelivery.resume();
91
+ });
92
+ this.incomingMessage$
93
+ .pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage instanceof app_client_state_message_1.AppClientStateMessage))
94
+ .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this, (unsafeMessage) => {
95
+ const messagePayload = exports.ClientStateSchema.parse(unsafeMessage.payload);
96
+ this.state$.next(messagePayload);
97
+ }));
98
+ this.incomingMessage$
99
+ .pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage instanceof handshake_message_1.HandshakeMessage))
100
+ .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this, (unsafeMessage) => {
101
+ const messagePayload = exports.ClientHandshakePayloadSchema.parse(unsafeMessage.payload);
102
+ this.applicationId$.next(messagePayload.applicationId);
103
+ }));
104
+ }
105
+ /**
106
+ * Подключает transport-слой для фактической отправки сообщений клиенту.
107
+ *
108
+ * Вызывается при каждом новом соединении; предыдущий transport снимается автоматически.
109
+ */
110
+ attachTransport(send) {
111
+ this.detachTransport();
112
+ this.transportSend = send;
113
+ }
114
+ /**
115
+ * Отключает transport-слой без уничтожения клиента (grace period).
116
+ */
117
+ detachTransport() {
118
+ delete this.transportSend;
119
+ }
120
+ /**
121
+ * Entry instance для сериализации глобальных App-оверлеев (platform.setOverlays).
122
+ */
123
+ ensureAppOverlayEntry() {
124
+ if (!this.appOverlayEntry) {
125
+ this.appOverlayEntry = (0, client_context_1.runWithClient)(this, () => this.app.beginSerializationContext());
126
+ }
127
+ return this.appOverlayEntry;
128
+ }
129
+ /**
130
+ * Завершает работу клиента и завершает потоки сообщений.
131
+ */
132
+ destroy() {
133
+ this.detachTransport();
134
+ this.reliableDelivery.destroy();
135
+ this.incomingMessage$.complete();
136
+ this.outcomingMessage$.complete();
137
+ this.ping$.complete();
138
+ this.applicationId$.complete();
139
+ this.error$.complete();
140
+ this.destroy$.next();
141
+ this.destroy$.complete();
142
+ }
143
+ /**
144
+ * Обрабатывает новое входящее сообщение в виде строки.
145
+ *
146
+ * @param messageString Строка с сериализованным сообщением.
147
+ */
148
+ newMessage(messageString) {
149
+ try {
150
+ const abstractMessageSchema = v4_1.z.union([
151
+ v4_1.z.strictObject({
152
+ type: v4_1.z.string(),
153
+ payload: v4_1.z.unknown(),
154
+ scope: v4_1.z.string(),
155
+ }),
156
+ v4_1.z.strictObject({
157
+ type: v4_1.z.string(),
158
+ payload: v4_1.z.unknown(),
159
+ scope: v4_1.z.string(),
160
+ id: v4_1.z.string(),
161
+ attempt: v4_1.z.number().int().positive(),
162
+ }),
163
+ ]);
164
+ const message = abstractMessageSchema.parse(JSON.parse(messageString));
165
+ (0, client_context_1.runWithClient)(this, () => {
166
+ const nextMessage = this.reliableDelivery.handleIncoming((0, parse_client_to_bff_message_1.parseClientToBffMessage)(message));
167
+ if (nextMessage) {
168
+ this.incomingMessage$.next(nextMessage);
169
+ }
170
+ });
171
+ }
172
+ catch (error) {
173
+ this.error$.next(error);
174
+ }
175
+ }
176
+ /**
177
+ * Переход на другую страницу: снимает обработчики с предыдущей страницы и запоминает id новой.
178
+ */
179
+ switchPage(newPageInstance) {
180
+ this.currentPageInstance?.component.releaseInstances([
181
+ this.currentPageInstance,
182
+ ]);
183
+ this.currentPageInstance = newPageInstance;
184
+ }
185
+ /**
186
+ * Снимает использования глобального компонента (оверлеи платформы и т.п.) для этого клиента.
187
+ */
188
+ removeGlobalComponent(node) {
189
+ if ((0, component_tree_node_1.isComponentInstance)(node)) {
190
+ node.component.releaseInstances([node]);
191
+ return;
192
+ }
193
+ if (node instanceof component_1.Component) {
194
+ node.releaseInstances(node.getInstances({ client: this }));
195
+ }
196
+ }
197
+ browserVersion() {
198
+ const userAgent = this.state$.getValue().userAgent;
199
+ const patterns = [
200
+ /Edg\/([\d.]+)/,
201
+ /OPR\/([\d.]+)/,
202
+ /Firefox\/([\d.]+)/,
203
+ /Chrome\/([\d.]+)/,
204
+ /Version\/([\d.]+).*Safari/,
205
+ ];
206
+ for (const pattern of patterns) {
207
+ const match = userAgent.match(pattern);
208
+ if (match?.[1]) {
209
+ return match[1];
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+ browserName() {
215
+ const userAgent = this.state$.getValue().userAgent;
216
+ const patterns = [
217
+ [/EdgiOS\/[\d.]+|Edg\/[\d.]+/, browser_name_1.BrowserName.Edge],
218
+ [/OPiOS\/[\d.]+|OPR\/[\d.]+/, browser_name_1.BrowserName.Opera],
219
+ [/YaBrowser\/[\d.]+/, browser_name_1.BrowserName.YandexBrowser],
220
+ [/SamsungBrowser\/[\d.]+/, browser_name_1.BrowserName.SamsungInternet],
221
+ [/FxiOS\/[\d.]+|Firefox\/[\d.]+/, browser_name_1.BrowserName.Firefox],
222
+ [/CriOS\/[\d.]+|Chrome\/[\d.]+/, browser_name_1.BrowserName.Chrome],
223
+ [/Version\/[\d.]+.*Safari/, browser_name_1.BrowserName.Safari],
224
+ ];
225
+ for (const [pattern, browserFamily] of patterns) {
226
+ if (pattern.test(userAgent)) {
227
+ return browserFamily;
228
+ }
229
+ }
230
+ return browser_name_1.BrowserName.Unknown;
231
+ }
232
+ browserEngine() {
233
+ const userAgent = this.state$.getValue().userAgent;
234
+ if (/Firefox\/[\d.]+/.test(userAgent)) {
235
+ return browser_engine_1.BrowserEngine.Gecko;
236
+ }
237
+ if (/iPhone|iPad|iPod/.test(userAgent) &&
238
+ /AppleWebKit\/[\d.]+/.test(userAgent)) {
239
+ return browser_engine_1.BrowserEngine.WebKit;
240
+ }
241
+ if (/Chrome\/[\d.]+|Chromium\/[\d.]+|Edg\/[\d.]+|OPR\/[\d.]+|YaBrowser\/[\d.]+|SamsungBrowser\/[\d.]+/.test(userAgent)) {
242
+ return browser_engine_1.BrowserEngine.Blink;
243
+ }
244
+ if (/AppleWebKit\/[\d.]+/.test(userAgent)) {
245
+ return browser_engine_1.BrowserEngine.WebKit;
246
+ }
247
+ return browser_engine_1.BrowserEngine.Unknown;
248
+ }
249
+ osName() {
250
+ return resolveOsNameFromUserAgent(this.state$.getValue().userAgent);
251
+ }
252
+ deviceType() {
253
+ return resolveDeviceTypeFromUserAgent(this.state$.getValue().userAgent);
254
+ }
255
+ /**
256
+ * Возвращает значение из клиентского хранилища по заданному ключу.
257
+ *
258
+ * @param key Ключ значения.
259
+ * @returns Значение, если оно существует.
260
+ */
261
+ getStorageValue(key) {
262
+ return (0, fetch_from_object_1.fetchFromObject)(this.state$.getValue().storage, key);
263
+ }
264
+ /**
265
+ * Устанавливает значение в клиентское хранилище и отправляет соответствующее сообщение.
266
+ *
267
+ * @param key Ключ значения.
268
+ * @param value Значение или undefined для удаления.
269
+ * @returns Ссылку на текущий экземпляр клиента.
270
+ */
271
+ setStorageValue(key, value) {
272
+ const storage = this.state$.getValue().storage;
273
+ (0, set_object_property_1.setObjectProperty)(storage, key, value);
274
+ this.state$.next({ ...this.state$.getValue(), storage });
275
+ const message = new index_1.AppStorageValueMessage({ key, value });
276
+ this.outcomingMessage$.next(message);
277
+ return this;
278
+ }
279
+ /**
280
+ * Удаляет значение из хранилища по ключу.
281
+ *
282
+ * @param key Ключ для удаления.
283
+ * @returns Ссылку на текущий экземпляр клиента.
284
+ */
285
+ clearStorageValue(key) {
286
+ return this.setStorageValue(key, undefined);
287
+ }
288
+ forwardToTransport(message) {
289
+ this.transportSend?.(message);
290
+ }
291
+ }
292
+ exports.Client = Client;
@@ -0,0 +1,14 @@
1
+ import { ConditionGroupOperator } from "@matreshka/shared/enums/condition-group-operator";
2
+ import { Condition } from "./condition";
3
+ /**
4
+ * Составное условие: все (`and`) или хотя бы одно (`or`) из вложенных условий.
5
+ *
6
+ * @internal Используйте {@link conditionAny} / {@link conditionAll} или {@link when.any} / {@link when.all}.
7
+ */
8
+ export declare class ConditionGroup extends Condition {
9
+ constructor(operator: ConditionGroupOperator, conditions: Condition[]);
10
+ }
11
+ /** Хотя бы одно из условий (OR). */
12
+ export declare function conditionAny(conditions: Condition[]): ConditionGroup;
13
+ /** Все условия (AND) — явная группа, удобна внутри {@link conditionAny}. */
14
+ export declare function conditionAll(conditions: Condition[]): ConditionGroup;