@matreshka/bff 0.17.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 +1 -4
  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
@@ -1,12 +1,12 @@
1
1
  import type { MobileBleService } from "@matreshka/shared/types/mobile-ble-services";
2
- import { Subject } from "rxjs";
2
+ import { Observable, Subject } from "rxjs";
3
3
  import { z } from "zod/v4";
4
4
  import { Client } from "../core";
5
5
  import { ClientPlatform } from "./client-platform";
6
6
  /**
7
7
  * Входящее сообщение с найденным устройством BLE
8
8
  */
9
- declare const bleScanResultSchema: z.ZodObject<{
9
+ export declare const bleScanResultSchema: z.ZodObject<{
10
10
  device: z.ZodObject<{
11
11
  name: z.ZodOptional<z.ZodString>;
12
12
  deviceId: z.ZodString;
@@ -18,14 +18,13 @@ declare const bleScanResultSchema: z.ZodObject<{
18
18
  serviceData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
19
19
  uuids: z.ZodArray<z.ZodString>;
20
20
  }, z.core.$strip>;
21
+ export type BleScanResult = z.infer<typeof bleScanResultSchema>;
21
22
  /**
22
23
  * Абстрактная платформа, реализующая функции взаимодействия с нативной мобильной средой.
23
24
  */
24
25
  export declare abstract class MobilePlatform extends ClientPlatform {
25
26
  /**
26
27
  * Добавляет событие в системный календарь устройства.
27
- *
28
- * @param data Объект с параметрами события (начало, конец, описание и т.п.).
29
28
  */
30
29
  addEventToCalendar(data: {
31
30
  start: string | EpochTimeStamp;
@@ -33,85 +32,60 @@ export declare abstract class MobilePlatform extends ClientPlatform {
33
32
  summary: string;
34
33
  location?: string;
35
34
  description?: string;
36
- }): void;
35
+ }): Observable<void>;
37
36
  /**
38
37
  * Инициирует загрузку CSV-файла с заданным именем и содержимым.
39
- *
40
- * @param filename Имя файла (с расширением .csv, будет добавлено при необходимости).
41
- * @param content Содержимое файла в виде двумерного массива строк.
42
38
  */
43
- downloadCsvContent(filename: string, content: string[][]): void;
39
+ downloadCsvContent(filename: string, content: string[][]): Observable<void>;
44
40
  /**
45
41
  * Инициирует загрузку файла по заданной ссылке.
46
- *
47
- * @param url Ссылка на файл.
48
- * @param filename Имя файла для сохранения.
49
42
  */
50
- downloadFile(url: string, filename: string): void;
43
+ downloadFile(url: string, filename: string): Observable<void>;
51
44
  /**
52
45
  * Делится содержимым через системное диалоговое окно обмена.
53
- *
54
- * @param data Объект с текстом, ссылкой и/или заголовком.
55
46
  */
56
47
  share(data: {
57
48
  url?: string;
58
49
  title?: string;
59
50
  text?: string;
60
- }): void;
61
- /**
62
- * Запрашивает геолокацию пользователя.
63
- *
64
- * @param config Объект с обработчиками успешного получения геолокации и отмены.
65
- */
66
- getGeolocation(config: {
67
- onSuccess: (position: {
68
- latitude: number;
69
- longitude: number;
70
- }) => void;
71
- onError?: (error: string) => void;
72
- }): void;
51
+ }): Observable<void>;
52
+ /** Запрашивает геолокацию пользователя. */
53
+ getGeolocation(): Observable<{
54
+ latitude: number;
55
+ longitude: number;
56
+ }>;
57
+ /** Запрашивает разрешение на push-уведомления и возвращает токен. */
58
+ registerPushNotifications(): Observable<{
59
+ value: string;
60
+ }>;
73
61
  /**
74
- * Запрашивает разрешение на push-уведомления и обрабатывает результат.
62
+ * Запрашивает сканирование BLE-устройств.
75
63
  *
76
- * @param config Объект с колбэками: `onGranted` при успехе, `onError` при ошибке.
64
+ * Hot: скан стартует при вызове метода. Отписка всех observers отправляет stop на клиент.
77
65
  */
78
- registerPushNotifications(config: {
79
- onGranted: (token: {
80
- value: string;
81
- }) => void;
82
- onError?: (text: string) => void;
83
- }): void;
84
- /** Запрашивает сканирование BLE устройств.
85
- * @return Функция для остановки отслеживания. */
86
66
  requestBLEScan(config: {
87
67
  services?: (number | string)[];
88
68
  name?: string;
89
69
  namePrefix?: string;
90
- onReceive: (result: z.infer<typeof bleScanResultSchema>) => void;
91
- onError?: (text: string) => void;
92
- }): () => void;
93
- connectToBLEDevice(deviceId: string): BLEDevice;
70
+ }): Observable<BleScanResult>;
71
+ connectToBLEDevice(deviceId: string): Observable<BLEDevice>;
94
72
  }
95
73
  declare class BLEDevice {
96
74
  private id;
97
75
  private client;
98
- private scope;
99
- connect$: Subject<void>;
100
- error$: Subject<string>;
76
+ private sessionScope;
101
77
  disconnect$: Subject<void>;
78
+ private sessionEnded;
79
+ private sessionDisconnectListenerStarted;
80
+ private sessionIncomingSubscription?;
81
+ private clientDestroySubscription?;
102
82
  constructor(id: string, client: Client);
103
- disconnect(): void;
104
- read(serviceId: number | string, characteristicId: number | string, config: {
105
- onReceive: (value: number) => void;
106
- onError?: (text: string) => void;
107
- }): () => void;
108
- getServices(config: {
109
- onReceive: (services: MobileBleService[]) => void;
110
- onError?: (text: string) => void;
111
- }): () => void;
112
- discoverServices(config: {
113
- onReceive: (services: MobileBleService[]) => void;
114
- onError?: (text: string) => void;
115
- }): () => void;
83
+ connect(): Observable<void>;
84
+ private startSessionDisconnectListener;
85
+ private endSession;
86
+ disconnect(): Observable<void>;
87
+ read(serviceId: number | string, characteristicId: number | string): Observable<number>;
88
+ getServices(): Observable<MobileBleService[]>;
89
+ discoverServices(): Observable<MobileBleService[]>;
116
90
  }
117
91
  export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MobilePlatform = void 0;
3
+ exports.MobilePlatform = exports.bleScanResultSchema = void 0;
4
4
  const mobile_add_event_to_calendar_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/mobile/mobile-add-event-to-calendar-message");
5
5
  const mobile_connect_to_ble_device_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/mobile/mobile-connect-to-ble-device-message");
6
6
  const mobile_disconnect_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/mobile/mobile-disconnect-message");
@@ -14,8 +14,6 @@ const mobile_request_ble_scan_message_1 = require("@matreshka/shared/messages/bf
14
14
  const mobile_request_push_notifications_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/mobile/mobile-request-push-notifications-message");
15
15
  const mobile_share_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/mobile/mobile-share-message");
16
16
  const mobile_stop_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/mobile/mobile-stop-message");
17
- const error_message_1 = require("@matreshka/shared/messages/client-to-bff/error-message");
18
- const mobile_ble_connect_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/mobile/mobile-ble-connect-message");
19
17
  const mobile_ble_disconnect_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/mobile/mobile-ble-disconnect-message");
20
18
  const mobile_ble_receive_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/mobile/mobile-ble-receive-message");
21
19
  const mobile_ble_services_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/mobile/mobile-ble-services-message");
@@ -28,6 +26,8 @@ const v4_1 = require("zod/v4");
28
26
  const incoming_message_observer_1 = require("../core/utils/incoming-message-observer");
29
27
  const client_platform_1 = require("./client-platform");
30
28
  const mobile_ble_services_1 = require("./utils/mobile-ble-services");
29
+ const targeted_client_platform_action_1 = require("./utils/targeted-client-platform-action");
30
+ const targeted_client_platform_stream_1 = require("./utils/targeted-client-platform-stream");
31
31
  /**
32
32
  * Входящее сообщение, содержащее успешно полученный push-токен.
33
33
  */
@@ -36,16 +36,10 @@ const pushTokenGrantedMessageSchema = v4_1.z.strictObject({
36
36
  value: v4_1.z.string(),
37
37
  }),
38
38
  });
39
- /**
40
- * Входящее сообщение об ошибке при получении push-токена.
41
- */
42
- const errorMessagePayloadSchema = v4_1.z.strictObject({
43
- message: v4_1.z.string(),
44
- });
45
39
  /**
46
40
  * Входящее сообщение с найденным устройством BLE
47
41
  */
48
- const bleScanResultSchema = v4_1.z.object({
42
+ exports.bleScanResultSchema = v4_1.z.object({
49
43
  // Не strictObject, потому что на андройде еще прилетает rawAdvertisement
50
44
  // https://github.com/capacitor-community/bluetooth-le?tab=readme-ov-file#scanresult
51
45
  device: v4_1.z.strictObject({
@@ -65,128 +59,93 @@ const bleScanResultSchema = v4_1.z.object({
65
59
  class MobilePlatform extends client_platform_1.ClientPlatform {
66
60
  /**
67
61
  * Добавляет событие в системный календарь устройства.
68
- *
69
- * @param data Объект с параметрами события (начало, конец, описание и т.п.).
70
62
  */
71
63
  addEventToCalendar(data) {
72
- this.client.outcomingMessage$.next(new mobile_add_event_to_calendar_message_1.MobileAddEventToCalendarMessage(data));
64
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
65
+ outgoingMessage: (scope) => new mobile_add_event_to_calendar_message_1.MobileAddEventToCalendarMessage(scope, data),
66
+ });
73
67
  }
74
68
  /**
75
69
  * Инициирует загрузку CSV-файла с заданным именем и содержимым.
76
- *
77
- * @param filename Имя файла (с расширением .csv, будет добавлено при необходимости).
78
- * @param content Содержимое файла в виде двумерного массива строк.
79
70
  */
80
71
  downloadCsvContent(filename, content) {
81
- this.client.outcomingMessage$.next(new mobile_download_csv_content_message_1.MobileDownloadCsvContentMessage({
82
- filename: filename.endsWith(".csv") ? filename : filename + ".csv",
83
- content,
84
- }));
72
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
73
+ outgoingMessage: (scope) => new mobile_download_csv_content_message_1.MobileDownloadCsvContentMessage(scope, {
74
+ filename: filename.endsWith(".csv") ? filename : filename + ".csv",
75
+ content,
76
+ }),
77
+ });
85
78
  }
86
79
  /**
87
80
  * Инициирует загрузку файла по заданной ссылке.
88
- *
89
- * @param url Ссылка на файл.
90
- * @param filename Имя файла для сохранения.
91
81
  */
92
82
  downloadFile(url, filename) {
93
- this.client.outcomingMessage$.next(new mobile_download_file_message_1.MobileDownloadFileMessage({ url, filename }));
83
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
84
+ outgoingMessage: (scope) => new mobile_download_file_message_1.MobileDownloadFileMessage(scope, { url, filename }),
85
+ });
94
86
  }
95
87
  /**
96
88
  * Делится содержимым через системное диалоговое окно обмена.
97
- *
98
- * @param data Объект с текстом, ссылкой и/или заголовком.
99
89
  */
100
90
  share(data) {
101
- this.client.outcomingMessage$.next(new mobile_share_message_1.MobileShareMessage(data));
91
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
92
+ outgoingMessage: (scope) => new mobile_share_message_1.MobileShareMessage(scope, data),
93
+ });
102
94
  }
103
- /**
104
- * Запрашивает геолокацию пользователя.
105
- *
106
- * @param config Объект с обработчиками успешного получения геолокации и отмены.
107
- */
108
- getGeolocation(config) {
109
- const scope = "platform-action-" + crypto.randomUUID();
110
- const subscription = this.client.incomingMessage$
111
- .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope))
112
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
113
- subscription.unsubscribe();
114
- if (unsafeMessage instanceof mobile_get_geolocation_success_message_1.MobileGetGeolocationSuccessMessage) {
115
- const messagePayload = v4_1.z
116
- .strictObject({
117
- latitude: v4_1.z.number(),
118
- longitude: v4_1.z.number(),
119
- })
120
- .parse(unsafeMessage.payload);
121
- config.onSuccess(messagePayload);
122
- return;
123
- }
124
- if (unsafeMessage instanceof error_message_1.ErrorMessage) {
125
- const messagePayload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
126
- if (typeof config.onError === "function") {
127
- config.onError(messagePayload.message);
95
+ /** Запрашивает геолокацию пользователя. */
96
+ getGeolocation() {
97
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
98
+ outgoingMessage: (scope) => new mobile_get_geolocation_message_1.MobileGetGeolocationMessage(scope),
99
+ parseSuccess: (unsafeMessage) => {
100
+ if (unsafeMessage instanceof mobile_get_geolocation_success_message_1.MobileGetGeolocationSuccessMessage) {
101
+ return v4_1.z
102
+ .strictObject({
103
+ latitude: v4_1.z.number(),
104
+ longitude: v4_1.z.number(),
105
+ })
106
+ .parse(unsafeMessage.payload);
128
107
  }
129
- }
130
- }));
131
- this.client.outcomingMessage$.next(new mobile_get_geolocation_message_1.MobileGetGeolocationMessage(scope));
108
+ },
109
+ });
110
+ }
111
+ /** Запрашивает разрешение на push-уведомления и возвращает токен. */
112
+ registerPushNotifications() {
113
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
114
+ outgoingMessage: (scope) => new mobile_request_push_notifications_message_1.MobileRequestPushNotificationsMessage(scope),
115
+ parseSuccess: (unsafeMessage) => {
116
+ if (unsafeMessage instanceof
117
+ mobile_request_push_notifications_action_granted_message_1.MobileRequestPushNotificationsActionGrantedMessage) {
118
+ const messagePayload = pushTokenGrantedMessageSchema.parse(unsafeMessage.payload);
119
+ return messagePayload.token;
120
+ }
121
+ },
122
+ });
132
123
  }
133
124
  /**
134
- * Запрашивает разрешение на push-уведомления и обрабатывает результат.
125
+ * Запрашивает сканирование BLE-устройств.
135
126
  *
136
- * @param config Объект с колбэками: `onGranted` при успехе, `onError` при ошибке.
127
+ * Hot: скан стартует при вызове метода. Отписка всех observers отправляет stop на клиент.
137
128
  */
138
- registerPushNotifications(config) {
139
- const scope = "platform-action-" + crypto.randomUUID();
140
- const subscription = this.client.incomingMessage$
141
- .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope))
142
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
143
- subscription.unsubscribe();
144
- if (unsafeMessage instanceof
145
- mobile_request_push_notifications_action_granted_message_1.MobileRequestPushNotificationsActionGrantedMessage) {
146
- const messagePayload = pushTokenGrantedMessageSchema.parse(unsafeMessage.payload);
147
- config.onGranted(messagePayload.token);
148
- return;
149
- }
150
- if (unsafeMessage instanceof error_message_1.ErrorMessage) {
151
- const messagePayload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
152
- if ("onError" in config) {
153
- config.onError(messagePayload.message);
154
- }
155
- }
156
- }));
157
- this.client.outcomingMessage$.next(new mobile_request_push_notifications_message_1.MobileRequestPushNotificationsMessage(scope));
158
- }
159
- /** Запрашивает сканирование BLE устройств.
160
- * @return Функция для остановки отслеживания. */
161
129
  requestBLEScan(config) {
162
- const scope = "platform-action-" + crypto.randomUUID();
163
- const subscription = this.client.incomingMessage$
164
- .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope))
165
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
166
- if (unsafeMessage instanceof mobile_ble_receive_message_1.MobileBleReceiveMessage) {
167
- const messagePayload = bleScanResultSchema.parse(unsafeMessage.payload);
168
- config.onReceive(messagePayload);
169
- return;
170
- }
171
- if (unsafeMessage instanceof error_message_1.ErrorMessage) {
172
- const messagePayload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
173
- if ("onError" in config) {
174
- config.onError(messagePayload.message);
130
+ return (0, targeted_client_platform_stream_1.targetedClientPlatformStream)(this.client, {
131
+ outgoingMessage: (scope) => new mobile_request_ble_scan_message_1.MobileRequestBleScanMessage(scope, {
132
+ services: config.services,
133
+ name: config.name,
134
+ namePrefix: config.namePrefix,
135
+ }),
136
+ parseItem: (unsafeMessage) => {
137
+ if (unsafeMessage instanceof mobile_ble_receive_message_1.MobileBleReceiveMessage) {
138
+ return exports.bleScanResultSchema.parse(unsafeMessage.payload);
175
139
  }
176
- subscription.unsubscribe();
177
- }
178
- }));
179
- this.client.outcomingMessage$.next(new mobile_request_ble_scan_message_1.MobileRequestBleScanMessage(scope, {
180
- services: config.services,
181
- name: config.name,
182
- namePrefix: config.namePrefix,
183
- }));
184
- return () => {
185
- this.client.outcomingMessage$.next(new mobile_stop_message_1.MobileStopMessage(scope));
186
- };
140
+ },
141
+ onTeardown: (scope, client) => {
142
+ client.outcomingMessage$.next(new mobile_stop_message_1.MobileStopMessage(scope));
143
+ },
144
+ });
187
145
  }
188
146
  connectToBLEDevice(deviceId) {
189
- return new BLEDevice(deviceId, this.client);
147
+ const device = new BLEDevice(deviceId, this.client);
148
+ return device.connect().pipe((0, rxjs_1.map)(() => device));
190
149
  }
191
150
  }
192
151
  exports.MobilePlatform = MobilePlatform;
@@ -194,125 +153,94 @@ class BLEDevice {
194
153
  constructor(id, client) {
195
154
  this.id = id;
196
155
  this.client = client;
197
- this.scope = "ble-device-" + crypto.randomUUID();
198
- this.connect$ = new rxjs_1.Subject();
199
- this.error$ = new rxjs_1.Subject();
156
+ this.sessionScope = "ble-device-" + crypto.randomUUID();
200
157
  this.disconnect$ = new rxjs_1.Subject();
201
- this.client.incomingMessage$
158
+ this.sessionEnded = false;
159
+ this.sessionDisconnectListenerStarted = false;
160
+ }
161
+ connect() {
162
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
163
+ outgoingMessage: (scope) => new mobile_connect_to_ble_device_message_1.MobileConnectToBleDeviceMessage(scope, {
164
+ deviceId: this.id,
165
+ disconnectNotifyTarget: this.sessionScope,
166
+ }),
167
+ }).pipe((0, rxjs_1.tap)(() => this.startSessionDisconnectListener()));
168
+ }
169
+ startSessionDisconnectListener() {
170
+ if (this.sessionDisconnectListenerStarted || this.sessionEnded) {
171
+ return;
172
+ }
173
+ this.sessionDisconnectListenerStarted = true;
174
+ this.sessionIncomingSubscription = this.client.incomingMessage$
202
175
  .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) &&
203
- unsafeMessage.target === this.scope), (0, rxjs_1.takeUntil)(this.disconnect$))
176
+ unsafeMessage.target === this.sessionScope), (0, rxjs_1.takeUntil)(this.disconnect$))
204
177
  .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
205
- if (unsafeMessage instanceof mobile_ble_connect_message_1.MobileBleConnectMessage) {
206
- this.connect$.next();
207
- return;
208
- }
209
- if (unsafeMessage instanceof error_message_1.ErrorMessage) {
210
- const payload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
211
- this.error$.next(payload.message);
212
- return;
213
- }
214
178
  if (unsafeMessage instanceof mobile_ble_disconnect_message_1.MobileBleDisconnectMessage) {
215
- this.disconnect$.next();
216
- this.connect$.complete();
217
- this.disconnect$.complete();
179
+ this.endSession();
218
180
  }
219
181
  }));
220
- this.client.outcomingMessage$.next(new mobile_connect_to_ble_device_message_1.MobileConnectToBleDeviceMessage(this.scope, { deviceId: this.id }));
182
+ this.clientDestroySubscription = this.client.destroy$
183
+ .pipe((0, rxjs_1.take)(1))
184
+ .subscribe(() => this.endSession());
185
+ }
186
+ endSession() {
187
+ if (this.sessionEnded) {
188
+ return;
189
+ }
190
+ this.sessionEnded = true;
191
+ this.sessionIncomingSubscription?.unsubscribe();
192
+ this.clientDestroySubscription?.unsubscribe();
193
+ this.disconnect$.next();
194
+ this.disconnect$.complete();
221
195
  }
222
196
  disconnect() {
223
- this.client.outcomingMessage$.next(new mobile_disconnect_message_1.MobileDisconnectMessage(this.scope, { deviceId: this.id }));
197
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
198
+ outgoingMessage: (scope) => new mobile_disconnect_message_1.MobileDisconnectMessage(scope, { deviceId: this.id }),
199
+ }).pipe((0, rxjs_1.tap)(() => this.endSession()));
224
200
  }
225
- read(serviceId, characteristicId, config) {
226
- const scope = "platform-action-" + crypto.randomUUID();
227
- const subscription = this.client.incomingMessage$
228
- .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope), (0, rxjs_1.takeUntil)(this.disconnect$))
229
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
230
- if (unsafeMessage instanceof mobile_ble_value_message_1.MobileBleValueMessage) {
231
- const payload = v4_1.z
232
- .strictObject({
233
- value: v4_1.z.number(),
234
- })
235
- .parse(unsafeMessage.payload);
236
- config.onReceive(payload.value);
237
- subscription.unsubscribe();
238
- return;
239
- }
240
- if (unsafeMessage instanceof error_message_1.ErrorMessage) {
241
- const payload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
242
- const errorText = payload.message;
243
- this.error$.next(errorText);
244
- if (typeof config.onError === "function") {
245
- config.onError(errorText);
201
+ read(serviceId, characteristicId) {
202
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
203
+ outgoingMessage: (scope) => new mobile_read_ble_characteristic_message_1.MobileReadBleCharacteristicMessage(scope, {
204
+ deviceId: this.id,
205
+ serviceId,
206
+ characteristicId,
207
+ }),
208
+ parseSuccess: (unsafeMessage) => {
209
+ if (unsafeMessage instanceof mobile_ble_value_message_1.MobileBleValueMessage) {
210
+ const payload = v4_1.z
211
+ .strictObject({
212
+ value: v4_1.z.number(),
213
+ })
214
+ .parse(unsafeMessage.payload);
215
+ return payload.value;
246
216
  }
247
- subscription.unsubscribe();
248
- }
249
- }));
250
- this.client.outcomingMessage$.next(new mobile_read_ble_characteristic_message_1.MobileReadBleCharacteristicMessage(scope, {
251
- deviceId: this.id,
252
- serviceId,
253
- characteristicId,
254
- }));
255
- return () => {
256
- subscription.unsubscribe();
257
- this.client.outcomingMessage$.next(new mobile_stop_message_1.MobileStopMessage(scope));
258
- };
217
+ },
218
+ });
259
219
  }
260
- getServices(config) {
261
- const scope = "platform-action-" + crypto.randomUUID();
262
- const subscription = this.client.incomingMessage$
263
- .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope), (0, rxjs_1.takeUntil)(this.disconnect$))
264
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
265
- if (unsafeMessage instanceof mobile_ble_services_message_1.MobileBleServicesMessage) {
266
- const payload = v4_1.z
267
- .strictObject({ services: mobile_ble_services_1.mobileBleServicesSchema })
268
- .parse(unsafeMessage.payload);
269
- config.onReceive(payload.services);
270
- subscription.unsubscribe();
271
- return;
272
- }
273
- if (unsafeMessage instanceof error_message_1.ErrorMessage) {
274
- const payload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
275
- const errorText = payload.message;
276
- this.error$.next(errorText);
277
- if (typeof config.onError === "function") {
278
- config.onError(errorText);
220
+ getServices() {
221
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
222
+ outgoingMessage: (scope) => new mobile_get_ble_services_message_1.MobileGetBleServicesMessage(scope, { deviceId: this.id }),
223
+ parseSuccess: (unsafeMessage) => {
224
+ if (unsafeMessage instanceof mobile_ble_services_message_1.MobileBleServicesMessage) {
225
+ const payload = v4_1.z
226
+ .strictObject({ services: mobile_ble_services_1.mobileBleServicesSchema })
227
+ .parse(unsafeMessage.payload);
228
+ return payload.services;
279
229
  }
280
- subscription.unsubscribe();
281
- }
282
- }));
283
- this.client.outcomingMessage$.next(new mobile_get_ble_services_message_1.MobileGetBleServicesMessage(scope, { deviceId: this.id }));
284
- return () => {
285
- subscription.unsubscribe();
286
- this.client.outcomingMessage$.next(new mobile_stop_message_1.MobileStopMessage(scope));
287
- };
230
+ },
231
+ });
288
232
  }
289
- discoverServices(config) {
290
- const scope = "platform-action-" + crypto.randomUUID();
291
- const subscription = this.client.incomingMessage$
292
- .pipe((0, rxjs_1.filter)((unsafeMessage) => (0, targeted_message_1.isTargetedMessage)(unsafeMessage) && unsafeMessage.target === scope), (0, rxjs_1.takeUntil)(this.disconnect$))
293
- .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
294
- if (unsafeMessage instanceof mobile_ble_services_message_1.MobileBleServicesMessage) {
295
- const payload = v4_1.z
296
- .strictObject({ services: mobile_ble_services_1.mobileBleServicesSchema })
297
- .parse(unsafeMessage.payload);
298
- config.onReceive(payload.services);
299
- subscription.unsubscribe();
300
- return;
301
- }
302
- if (unsafeMessage instanceof error_message_1.ErrorMessage) {
303
- const payload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
304
- const errorText = payload.message;
305
- this.error$.next(errorText);
306
- if (typeof config.onError === "function") {
307
- config.onError(errorText);
233
+ discoverServices() {
234
+ return (0, targeted_client_platform_action_1.targetedClientPlatformAction)(this.client, {
235
+ outgoingMessage: (scope) => new mobile_discover_ble_services_message_1.MobileDiscoverBleServicesMessage(scope, { deviceId: this.id }),
236
+ parseSuccess: (unsafeMessage) => {
237
+ if (unsafeMessage instanceof mobile_ble_services_message_1.MobileBleServicesMessage) {
238
+ const payload = v4_1.z
239
+ .strictObject({ services: mobile_ble_services_1.mobileBleServicesSchema })
240
+ .parse(unsafeMessage.payload);
241
+ return payload.services;
308
242
  }
309
- subscription.unsubscribe();
310
- }
311
- }));
312
- this.client.outcomingMessage$.next(new mobile_discover_ble_services_message_1.MobileDiscoverBleServicesMessage(scope, { deviceId: this.id }));
313
- return () => {
314
- subscription.unsubscribe();
315
- this.client.outcomingMessage$.next(new mobile_stop_message_1.MobileStopMessage(scope));
316
- };
243
+ },
244
+ });
317
245
  }
318
246
  }