@matreshka/bff 0.16.0 → 0.19.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 (47) hide show
  1. package/dist/components/board.d.ts +0 -3
  2. package/dist/components/board.js +3 -11
  3. package/dist/components/camera.d.ts +0 -3
  4. package/dist/components/camera.js +4 -11
  5. package/dist/components/component.d.ts +17 -1
  6. package/dist/components/component.js +19 -2
  7. package/dist/components/container.js +8 -11
  8. package/dist/components/dialog.d.ts +0 -3
  9. package/dist/components/dialog.js +4 -11
  10. package/dist/components/file-upload-area.js +8 -11
  11. package/dist/components/form.js +8 -11
  12. package/dist/components/grid.js +7 -11
  13. package/dist/components/map.d.ts +0 -3
  14. package/dist/components/map.js +2 -12
  15. package/dist/components/page.d.ts +0 -1
  16. package/dist/components/page.js +4 -10
  17. package/dist/components/popover.d.ts +0 -3
  18. package/dist/components/popover.js +4 -11
  19. package/dist/components/stack.d.ts +2 -5
  20. package/dist/components/stack.js +4 -11
  21. package/dist/core/utils/serialize-component-tree.d.ts +3 -0
  22. package/dist/core/utils/serialize-component-tree.js +21 -0
  23. package/dist/platforms/browser-platform.d.ts +21 -37
  24. package/dist/platforms/browser-platform.js +61 -104
  25. package/dist/platforms/max-mini-app-platform.d.ts +2 -8
  26. package/dist/platforms/max-mini-app-platform.js +10 -21
  27. package/dist/platforms/mobile-platform.d.ts +32 -58
  28. package/dist/platforms/mobile-platform.js +139 -211
  29. package/dist/platforms/platform.d.ts +32 -49
  30. package/dist/platforms/platform.js +77 -87
  31. package/dist/platforms/telegram-mini-app-platform.d.ts +16 -34
  32. package/dist/platforms/telegram-mini-app-platform.js +41 -92
  33. package/dist/platforms/utils/client-back-platform-action.d.ts +9 -0
  34. package/dist/platforms/utils/client-back-platform-action.js +48 -0
  35. package/dist/platforms/utils/client-navigate-platform-action.d.ts +19 -0
  36. package/dist/platforms/utils/client-navigate-platform-action.js +60 -0
  37. package/dist/platforms/utils/client-reload-platform-action.d.ts +8 -0
  38. package/dist/platforms/utils/client-reload-platform-action.js +41 -0
  39. package/dist/platforms/utils/client-route-page-wait.d.ts +11 -0
  40. package/dist/platforms/utils/client-route-page-wait.js +33 -0
  41. package/dist/platforms/utils/match-navigate-path.d.ts +11 -0
  42. package/dist/platforms/utils/match-navigate-path.js +95 -0
  43. package/dist/platforms/utils/targeted-client-platform-action.d.ts +11 -0
  44. package/dist/platforms/utils/targeted-client-platform-action.js +80 -0
  45. package/dist/platforms/utils/targeted-client-platform-stream.d.ts +17 -0
  46. package/dist/platforms/utils/targeted-client-platform-stream.js +90 -0
  47. package/package.json +2 -2
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clientBackPlatformAction = clientBackPlatformAction;
4
+ const app_back_message_1 = require("@matreshka/shared/messages/bff-to-client/app/app-back-message");
5
+ const rxjs_1 = require("rxjs");
6
+ const client_route_page_wait_1 = require("./client-route-page-wait");
7
+ /**
8
+ * Back без targeted ack с клиента (как {@link clientNavigatePlatformAction}).
9
+ *
10
+ * Завершение: новый `route.visitedAt`, {@link AppPageMessage} и receipt.
11
+ * Timeout нет; при {@link Client.destroy$} до завершения — error.
12
+ */
13
+ function clientBackPlatformAction(client) {
14
+ const result$ = new rxjs_1.ReplaySubject(1);
15
+ let finalized = false;
16
+ const subscriptions = new rxjs_1.Subscription();
17
+ const teardown = () => {
18
+ if (finalized) {
19
+ return;
20
+ }
21
+ finalized = true;
22
+ subscriptions.unsubscribe();
23
+ };
24
+ const finishSuccess = () => {
25
+ result$.next(undefined);
26
+ result$.complete();
27
+ teardown();
28
+ };
29
+ const finishError = (error) => {
30
+ result$.error(error);
31
+ teardown();
32
+ };
33
+ subscriptions.add(client.destroy$.subscribe(() => {
34
+ if (!finalized) {
35
+ finishError(new Error("Client destroyed before back completed"));
36
+ }
37
+ }));
38
+ subscriptions.add((0, client_route_page_wait_1.baselineVisitedAt$)(client)
39
+ .pipe((0, rxjs_1.switchMap)((baselineVisitedAt) => {
40
+ client.outcomingMessage$.next(new app_back_message_1.AppBackMessage());
41
+ return (0, client_route_page_wait_1.waitForRouteChangeAndPageReceipt)(client, baselineVisitedAt).pipe((0, rxjs_1.map)(() => undefined));
42
+ }))
43
+ .subscribe({
44
+ next: () => finishSuccess(),
45
+ error: (error) => finishError(error instanceof Error ? error : new Error(String(error))),
46
+ }));
47
+ return result$.asObservable();
48
+ }
@@ -0,0 +1,19 @@
1
+ import { Observable } from "rxjs";
2
+ import { Client } from "../../core";
3
+ /** Результат `Platform.navigate()`: навигация дошла до доставки page; path может не совпасть (redirect). */
4
+ export type NavigateResult = {
5
+ /** Фактический route клиента совпал с маской аргумента `path` (см. match-navigate-path). */
6
+ routeMatched: boolean;
7
+ };
8
+ /**
9
+ * Navigate без targeted ack с клиента (исключение рядом с {@link clientReloadPlatformAction}).
10
+ *
11
+ * SPA: observable завершается, когда выполнены все шаги:
12
+ * 1. клиент сообщил новый `route.visitedAt` (после {@link AppNavigateMessage});
13
+ * 2. BFF отправил {@link AppPageMessage} для этого route (boot по client-state);
14
+ * 3. пришёл `message-received` на id page (retry через reliable delivery на Client).
15
+ *
16
+ * Искусственного timeout нет: ждём доставку или {@link Client.destroy$}.
17
+ * Несовпадение path (guard, redirect) — не error, только `routeMatched: false`.
18
+ */
19
+ export declare function clientNavigatePlatformAction(client: Client, path: string): Observable<NavigateResult>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clientNavigatePlatformAction = clientNavigatePlatformAction;
4
+ const app_navigate_message_1 = require("@matreshka/shared/messages/bff-to-client/app/app-navigate-message");
5
+ const rxjs_1 = require("rxjs");
6
+ const client_route_page_wait_1 = require("./client-route-page-wait");
7
+ const match_navigate_path_1 = require("./match-navigate-path");
8
+ /**
9
+ * Navigate без targeted ack с клиента (исключение рядом с {@link clientReloadPlatformAction}).
10
+ *
11
+ * SPA: observable завершается, когда выполнены все шаги:
12
+ * 1. клиент сообщил новый `route.visitedAt` (после {@link AppNavigateMessage});
13
+ * 2. BFF отправил {@link AppPageMessage} для этого route (boot по client-state);
14
+ * 3. пришёл `message-received` на id page (retry через reliable delivery на Client).
15
+ *
16
+ * Искусственного timeout нет: ждём доставку или {@link Client.destroy$}.
17
+ * Несовпадение path (guard, redirect) — не error, только `routeMatched: false`.
18
+ */
19
+ function clientNavigatePlatformAction(client, path) {
20
+ const result$ = new rxjs_1.ReplaySubject(1);
21
+ let finalized = false;
22
+ const subscriptions = new rxjs_1.Subscription();
23
+ const teardown = () => {
24
+ if (finalized) {
25
+ return;
26
+ }
27
+ finalized = true;
28
+ subscriptions.unsubscribe();
29
+ };
30
+ const finishSuccess = (routeMatched) => {
31
+ result$.next({ routeMatched });
32
+ result$.complete();
33
+ teardown();
34
+ };
35
+ const finishError = (error) => {
36
+ result$.error(error);
37
+ teardown();
38
+ };
39
+ subscriptions.add(client.destroy$.subscribe(() => {
40
+ if (!finalized) {
41
+ finishError(new Error("Client destroyed before navigate completed"));
42
+ }
43
+ }));
44
+ // Внешний URL: нет SPA route и AppPageMessage — сразу успех без routeMatched.
45
+ if ((0, match_navigate_path_1.isExternalNavigatePath)(path)) {
46
+ client.outcomingMessage$.next(new app_navigate_message_1.AppNavigateMessage({ path }));
47
+ finishSuccess(false);
48
+ return result$.asObservable();
49
+ }
50
+ subscriptions.add((0, client_route_page_wait_1.baselineVisitedAt$)(client)
51
+ .pipe((0, rxjs_1.switchMap)((baselineVisitedAt) => {
52
+ client.outcomingMessage$.next(new app_navigate_message_1.AppNavigateMessage({ path }));
53
+ return (0, client_route_page_wait_1.waitForRouteChangeAndPageReceipt)(client, baselineVisitedAt).pipe((0, rxjs_1.map)((state) => (0, match_navigate_path_1.clientRouteMatchesNavigatePath)(state.route, path)));
54
+ }))
55
+ .subscribe({
56
+ next: (routeMatched) => finishSuccess(routeMatched),
57
+ error: (error) => finishError(error instanceof Error ? error : new Error(String(error))),
58
+ }));
59
+ return result$.asObservable();
60
+ }
@@ -0,0 +1,8 @@
1
+ import { Observable } from "rxjs";
2
+ import { Client } from "../../core";
3
+ /**
4
+ * Reload platform-action: клиент не может прислать ack до перезагрузки страницы.
5
+ * Успех — первый {@link Client.reconnect$} после отправки {@link AppReloadMessage}
6
+ * (клиент переподключился с тем же token в grace period).
7
+ */
8
+ export declare function clientReloadPlatformAction(client: Client): Observable<void>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clientReloadPlatformAction = clientReloadPlatformAction;
4
+ const app_reload_message_1 = require("@matreshka/shared/messages/bff-to-client/app/app-reload-message");
5
+ const rxjs_1 = require("rxjs");
6
+ /**
7
+ * Reload platform-action: клиент не может прислать ack до перезагрузки страницы.
8
+ * Успех — первый {@link Client.reconnect$} после отправки {@link AppReloadMessage}
9
+ * (клиент переподключился с тем же token в grace period).
10
+ */
11
+ function clientReloadPlatformAction(client) {
12
+ const result$ = new rxjs_1.ReplaySubject(1);
13
+ let finalized = false;
14
+ const teardown = () => {
15
+ if (finalized) {
16
+ return;
17
+ }
18
+ finalized = true;
19
+ reconnectSubscription.unsubscribe();
20
+ destroySubscription.unsubscribe();
21
+ };
22
+ const finish = (notify) => {
23
+ notify();
24
+ teardown();
25
+ };
26
+ const reconnectSubscription = client.reconnect$
27
+ .pipe((0, rxjs_1.take)(1))
28
+ .subscribe(() => {
29
+ finish(() => {
30
+ result$.next(undefined);
31
+ result$.complete();
32
+ });
33
+ });
34
+ const destroySubscription = client.destroy$.subscribe(() => {
35
+ finish(() => {
36
+ result$.error(new Error("Client destroyed before reload reconnect"));
37
+ });
38
+ });
39
+ client.outcomingMessage$.next(new app_reload_message_1.AppReloadMessage());
40
+ return result$.asObservable();
41
+ }
@@ -0,0 +1,11 @@
1
+ import type { ClientState } from "@matreshka/shared/types/client-state";
2
+ import { Observable } from "rxjs";
3
+ import { Client } from "../../core";
4
+ export declare function hasRouteVisitedAt(state: ClientState | undefined): state is ClientState;
5
+ /** `visitedAt` до команды — от него отличаем следующую навигацию клиента. */
6
+ export declare function baselineVisitedAt$(client: Client): Observable<number>;
7
+ /**
8
+ * После смены `route.visitedAt` относительно baseline — первый {@link AppPageMessage} и receipt.
9
+ * Эмитит {@link ClientState} на новом route (для navigate: проверка path).
10
+ */
11
+ export declare function waitForRouteChangeAndPageReceipt(client: Client, baselineVisitedAt: number): Observable<ClientState>;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasRouteVisitedAt = hasRouteVisitedAt;
4
+ exports.baselineVisitedAt$ = baselineVisitedAt$;
5
+ exports.waitForRouteChangeAndPageReceipt = waitForRouteChangeAndPageReceipt;
6
+ const app_page_message_1 = require("@matreshka/shared/messages/bff-to-client/app/app-page-message");
7
+ const message_received_message_1 = require("@matreshka/shared/messages/client-to-bff/message-received-message");
8
+ const rxjs_1 = require("rxjs");
9
+ function hasRouteVisitedAt(state) {
10
+ return typeof state?.route?.visitedAt === "number";
11
+ }
12
+ /** `visitedAt` до команды — от него отличаем следующую навигацию клиента. */
13
+ function baselineVisitedAt$(client) {
14
+ const current = client.state$.getValue();
15
+ if (hasRouteVisitedAt(current)) {
16
+ return new rxjs_1.Observable((subscriber) => {
17
+ subscriber.next(current.route.visitedAt);
18
+ subscriber.complete();
19
+ });
20
+ }
21
+ return client.state$.pipe((0, rxjs_1.filter)(hasRouteVisitedAt), (0, rxjs_1.take)(1), (0, rxjs_1.map)((state) => state.route.visitedAt));
22
+ }
23
+ function waitForPageReceipt(client, pageMessage) {
24
+ return client.incomingMessage$.pipe((0, rxjs_1.filter)((message) => message instanceof message_received_message_1.ClientToBffMessageReceivedMessage &&
25
+ message.payload.id === pageMessage.id), (0, rxjs_1.take)(1), (0, rxjs_1.map)(() => undefined));
26
+ }
27
+ /**
28
+ * После смены `route.visitedAt` относительно baseline — первый {@link AppPageMessage} и receipt.
29
+ * Эмитит {@link ClientState} на новом route (для navigate: проверка path).
30
+ */
31
+ function waitForRouteChangeAndPageReceipt(client, baselineVisitedAt) {
32
+ return client.state$.pipe((0, rxjs_1.filter)((state) => hasRouteVisitedAt(state) && state.route.visitedAt !== baselineVisitedAt), (0, rxjs_1.take)(1), (0, rxjs_1.switchMap)((state) => client.outcomingMessage$.pipe((0, rxjs_1.filter)((message) => message instanceof app_page_message_1.AppPageMessage), (0, rxjs_1.take)(1), (0, rxjs_1.switchMap)((pageMessage) => waitForPageReceipt(client, pageMessage).pipe((0, rxjs_1.map)(() => state))))));
33
+ }
@@ -0,0 +1,11 @@
1
+ type ClientRouteSlice = {
2
+ path: string;
3
+ query: Record<string, string>;
4
+ };
5
+ /**
6
+ * Сравнивает фактический route клиента с аргументом {@link Platform.navigate}:
7
+ * литералы и query должны совпасть, `@{context.path}` и `{param}` — wildcard сегмента.
8
+ */
9
+ export declare function clientRouteMatchesNavigatePath(clientRoute: ClientRouteSlice, navigatePath: string): boolean;
10
+ export declare function isExternalNavigatePath(path: string): boolean;
11
+ export {};
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clientRouteMatchesNavigatePath = clientRouteMatchesNavigatePath;
4
+ exports.isExternalNavigatePath = isExternalNavigatePath;
5
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6
+ function normalizePathname(pathname) {
7
+ return pathname.replace(/^\/+|\/+$/g, "");
8
+ }
9
+ function parseNavigatePath(path) {
10
+ const questionIndex = path.indexOf("?");
11
+ const pathnamePart = questionIndex === -1 ? path : path.slice(0, questionIndex);
12
+ const queryPart = questionIndex === -1 ? "" : path.slice(questionIndex + 1);
13
+ const query = {};
14
+ if (queryPart) {
15
+ for (const [key, value] of new URLSearchParams(queryPart)) {
16
+ query[key] = value;
17
+ }
18
+ }
19
+ return {
20
+ pathname: normalizePathname(pathnamePart),
21
+ query,
22
+ };
23
+ }
24
+ function segmentToRegexPattern(segment) {
25
+ let pattern = "";
26
+ let index = 0;
27
+ while (index < segment.length) {
28
+ if (segment.startsWith("@{", index)) {
29
+ const close = segment.indexOf("}", index + 2);
30
+ if (close !== -1) {
31
+ pattern += "[^/]+";
32
+ index = close + 1;
33
+ continue;
34
+ }
35
+ }
36
+ if (segment[index] === "{") {
37
+ const close = segment.indexOf("}", index + 1);
38
+ if (close !== -1) {
39
+ pattern += "[^/]+";
40
+ index = close + 1;
41
+ continue;
42
+ }
43
+ }
44
+ const nextSpecial = (() => {
45
+ const at = segment.indexOf("@{", index);
46
+ const brace = segment.indexOf("{", index);
47
+ const candidates = [at, brace].filter((i) => i !== -1);
48
+ return candidates.length ? Math.min(...candidates) : -1;
49
+ })();
50
+ const literalEnd = nextSpecial === -1 ? segment.length : nextSpecial;
51
+ pattern += escapeRegExp(segment.slice(index, literalEnd));
52
+ index = literalEnd;
53
+ }
54
+ return pattern;
55
+ }
56
+ function pathnameToRegex(pathname) {
57
+ if (pathname === "") {
58
+ return /^$/;
59
+ }
60
+ const segments = pathname.split("/");
61
+ const regexBody = segments.map(segmentToRegexPattern).join("/");
62
+ return new RegExp(`^${regexBody}$`);
63
+ }
64
+ function queryMatches(expected, actual) {
65
+ for (const [key, expectedValue] of Object.entries(expected)) {
66
+ if (actual[key] !== expectedValue) {
67
+ return false;
68
+ }
69
+ }
70
+ return true;
71
+ }
72
+ /**
73
+ * Сравнивает фактический route клиента с аргументом {@link Platform.navigate}:
74
+ * литералы и query должны совпасть, `@{context.path}` и `{param}` — wildcard сегмента.
75
+ */
76
+ function clientRouteMatchesNavigatePath(clientRoute, navigatePath) {
77
+ const expected = parseNavigatePath(navigatePath);
78
+ const actualPathname = normalizePathname(clientRoute.path);
79
+ if (!pathnameToRegex(expected.pathname).test(actualPathname)) {
80
+ return false;
81
+ }
82
+ return queryMatches(expected.query, clientRoute.query);
83
+ }
84
+ function isExternalNavigatePath(path) {
85
+ if (!path || path.startsWith("/")) {
86
+ return false;
87
+ }
88
+ try {
89
+ const url = new URL(path);
90
+ return url.protocol === "http:" || url.protocol === "https:";
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
@@ -0,0 +1,11 @@
1
+ import { AnyBffToClientMessage } from "@matreshka/shared/messages/bff-to-client/bff-to-client-message";
2
+ import { AnyClientToBffMessage } from "@matreshka/shared/messages/client-to-bff/client-to-bff-message";
3
+ import { Observable } from "rxjs";
4
+ import { Client } from "../../core";
5
+ export type TargetedClientPlatformActionConfig<T> = {
6
+ outgoingMessage: (scope: string) => AnyBffToClientMessage;
7
+ parseSuccess?: (unsafeMessage: AnyClientToBffMessage) => T | undefined;
8
+ /** Ответ клиента, который завершает action ошибкой (например отмена диалога). */
9
+ parseFailure?: (unsafeMessage: AnyClientToBffMessage) => Error | undefined;
10
+ };
11
+ export declare function targetedClientPlatformAction<T>(client: Client, config: TargetedClientPlatformActionConfig<T>): Observable<T>;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.targetedClientPlatformAction = targetedClientPlatformAction;
4
+ const error_message_1 = require("@matreshka/shared/messages/client-to-bff/error-message");
5
+ const platform_action_completed_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/platform-action-completed-message");
6
+ const targeted_message_1 = require("@matreshka/shared/messages/targeted-message");
7
+ const rxjs_1 = require("rxjs");
8
+ const v4_1 = require("zod/v4");
9
+ const incoming_message_observer_1 = require("../../core/utils/incoming-message-observer");
10
+ const errorMessagePayloadSchema = v4_1.z.strictObject({
11
+ message: v4_1.z.string(),
12
+ });
13
+ function startTargetedClientPlatformAction(client, config, terminal) {
14
+ const scope = "platform-action-" + crypto.randomUUID();
15
+ let finalized = false;
16
+ const teardown = () => {
17
+ if (finalized) {
18
+ return;
19
+ }
20
+ finalized = true;
21
+ subscription.unsubscribe();
22
+ destroySubscription.unsubscribe();
23
+ };
24
+ const finish = (notify) => {
25
+ notify();
26
+ teardown();
27
+ };
28
+ const subscription = client.incomingMessage$
29
+ .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope), (0, rxjs_1.take)(1))
30
+ .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(client, (unsafeMessage) => {
31
+ if (unsafeMessage instanceof error_message_1.ErrorMessage) {
32
+ const messagePayload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
33
+ finish(() => terminal.error(new Error(messagePayload.message)));
34
+ return;
35
+ }
36
+ if (unsafeMessage instanceof platform_action_completed_message_1.PlatformActionCompletedMessage) {
37
+ finish(() => {
38
+ terminal.next(undefined);
39
+ terminal.complete();
40
+ });
41
+ return;
42
+ }
43
+ const failure = config.parseFailure?.(unsafeMessage);
44
+ if (failure) {
45
+ finish(() => terminal.error(failure));
46
+ return;
47
+ }
48
+ const value = config.parseSuccess?.(unsafeMessage);
49
+ if (value !== undefined) {
50
+ finish(() => {
51
+ terminal.next(value);
52
+ terminal.complete();
53
+ });
54
+ }
55
+ }));
56
+ const destroySubscription = client.destroy$.subscribe(() => {
57
+ if (!terminal.closed()) {
58
+ terminal.complete();
59
+ }
60
+ teardown();
61
+ });
62
+ const start = () => {
63
+ client.outcomingMessage$.next(config.outgoingMessage(scope));
64
+ };
65
+ return { start, teardown };
66
+ }
67
+ function targetedClientPlatformAction(client, config) {
68
+ const result$ = new rxjs_1.ReplaySubject(1);
69
+ const { start } = startTargetedClientPlatformAction(client, config, {
70
+ next: (value) => {
71
+ result$.next(value);
72
+ result$.complete();
73
+ },
74
+ error: (error) => result$.error(error),
75
+ complete: () => result$.complete(),
76
+ closed: () => result$.closed,
77
+ });
78
+ start();
79
+ return result$.asObservable();
80
+ }
@@ -0,0 +1,17 @@
1
+ import { AnyBffToClientMessage } from "@matreshka/shared/messages/bff-to-client/bff-to-client-message";
2
+ import { AnyClientToBffMessage } from "@matreshka/shared/messages/client-to-bff/client-to-bff-message";
3
+ import { Observable } from "rxjs";
4
+ import { Client } from "../../core";
5
+ export type TargetedClientPlatformStreamConfig<T> = {
6
+ outgoingMessage: (scope: string) => AnyBffToClientMessage;
7
+ parseItem: (unsafeMessage: AnyClientToBffMessage) => T | undefined;
8
+ parseFailure?: (unsafeMessage: AnyClientToBffMessage) => Error | undefined;
9
+ /** Вызывается при teardown (отписка всех observers, ошибка, complete, destroy клиента). */
10
+ onTeardown?: (scope: string, client: Client) => void;
11
+ };
12
+ /**
13
+ * Hot platform-action stream: исходящее сообщение при вызове, много входящих с тем же target.
14
+ * Teardown (и {@link TargetedClientPlatformStreamConfig.onTeardown}) — когда не осталось подписчиков,
15
+ * при terminal-сообщении или destroy$ клиента.
16
+ */
17
+ export declare function targetedClientPlatformStream<T>(client: Client, config: TargetedClientPlatformStreamConfig<T>): Observable<T>;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.targetedClientPlatformStream = targetedClientPlatformStream;
4
+ const error_message_1 = require("@matreshka/shared/messages/client-to-bff/error-message");
5
+ const platform_action_completed_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/platform-action-completed-message");
6
+ const targeted_message_1 = require("@matreshka/shared/messages/targeted-message");
7
+ const rxjs_1 = require("rxjs");
8
+ const v4_1 = require("zod/v4");
9
+ const incoming_message_observer_1 = require("../../core/utils/incoming-message-observer");
10
+ const errorMessagePayloadSchema = v4_1.z.strictObject({
11
+ message: v4_1.z.string(),
12
+ });
13
+ /**
14
+ * Hot platform-action stream: исходящее сообщение при вызове, много входящих с тем же target.
15
+ * Teardown (и {@link TargetedClientPlatformStreamConfig.onTeardown}) — когда не осталось подписчиков,
16
+ * при terminal-сообщении или destroy$ клиента.
17
+ */
18
+ function targetedClientPlatformStream(client, config) {
19
+ const scope = "platform-action-" + crypto.randomUUID();
20
+ const bus$ = new rxjs_1.Subject();
21
+ let finalized = false;
22
+ let subscriberCount = 0;
23
+ const teardownSession = () => {
24
+ if (finalized) {
25
+ return;
26
+ }
27
+ finalized = true;
28
+ incomingSubscription.unsubscribe();
29
+ destroySubscription.unsubscribe();
30
+ config.onTeardown?.(scope, client);
31
+ };
32
+ const finishWithError = (error) => {
33
+ if (finalized) {
34
+ return;
35
+ }
36
+ bus$.error(error);
37
+ teardownSession();
38
+ };
39
+ const finishComplete = () => {
40
+ if (finalized) {
41
+ return;
42
+ }
43
+ bus$.complete();
44
+ teardownSession();
45
+ };
46
+ const incomingSubscription = client.incomingMessage$
47
+ .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope))
48
+ .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(client, (unsafeMessage) => {
49
+ if (finalized) {
50
+ return;
51
+ }
52
+ if (unsafeMessage instanceof error_message_1.ErrorMessage) {
53
+ const messagePayload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
54
+ finishWithError(new Error(messagePayload.message));
55
+ return;
56
+ }
57
+ const failure = config.parseFailure?.(unsafeMessage);
58
+ if (failure) {
59
+ finishWithError(failure);
60
+ return;
61
+ }
62
+ if (unsafeMessage instanceof platform_action_completed_message_1.PlatformActionCompletedMessage) {
63
+ finishComplete();
64
+ return;
65
+ }
66
+ const item = config.parseItem(unsafeMessage);
67
+ if (item !== undefined) {
68
+ bus$.next(item);
69
+ }
70
+ }));
71
+ const destroySubscription = client.destroy$.subscribe(() => {
72
+ finishComplete();
73
+ });
74
+ client.outcomingMessage$.next(config.outgoingMessage(scope));
75
+ return new rxjs_1.Observable((subscriber) => {
76
+ if (finalized) {
77
+ subscriber.complete();
78
+ return;
79
+ }
80
+ subscriberCount++;
81
+ const inner = bus$.subscribe(subscriber);
82
+ return () => {
83
+ inner.unsubscribe();
84
+ subscriberCount--;
85
+ if (subscriberCount === 0 && !finalized) {
86
+ teardownSession();
87
+ }
88
+ };
89
+ });
90
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.16.0",
3
+ "version": "0.19.0",
4
4
  "description": "Matreshka BFF: server-driven UI runtime — routing, pages, context, component DSL, and platform APIs",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -62,7 +62,7 @@
62
62
  "vitest": "^4.1.0"
63
63
  },
64
64
  "dependencies": {
65
- "@matreshka/shared": "^0.16.0",
65
+ "@matreshka/shared": "^0.19.0",
66
66
  "@simplewebauthn/server": "^13.1.1",
67
67
  "@simplewebauthn/types": "^12.0.0",
68
68
  "fast-xml-parser": "^5.3.3",