@alfalab/bridge-to-native 1.5.1 → 1.5.2-beta.feed590

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.
@@ -1,5 +1,5 @@
1
1
 
2
- import { type BrowserHistoryApiWrappers, type HistoryPushStateParams, type HistoryReplaceStateParams, type LocationAssignParam, type LogError, type NativeFeatureKey, type PdfType } from './types';
2
+ import { type BrowserHistoryApiWrappers, type GeoConfiguration, type HapticsOptions, type HistoryPushStateParams, type HistoryReplaceStateParams, type LocationAssignParam, type LogError, type NativeFeatureKey, type PdfType, type SheetDragArea } from './types';
3
3
  /**
4
4
  * Сервис, предоставляет методы для WA, работающего внутри NA.
5
5
  */
@@ -13,14 +13,18 @@ export declare class BridgeToNative {
13
13
  * будут использованы стандартные `History: pushState()` и `History: go()`.
14
14
  * @param options.logError Функция с помощью которой B2N может залогировать ошибку,
15
15
  * если не передать, B2N не будет логировать ошибки.
16
+ * @param options.isSheetWebview Признак открытия WV в шторе. Отвечает за доступность
17
+ * новых методов взаимодействия с нативом. По умолчанию true.
16
18
  */
17
19
  constructor(options?: {
18
20
  browserHistoryApiWrappers?: BrowserHistoryApiWrappers;
19
21
  logError?: LogError;
22
+ isSheetWebview?: boolean;
20
23
  } | undefined);
21
24
  private nativeParamsService;
22
25
  private externalLinksService;
23
26
  private nativeNavigationAndTitleService;
27
+ private nativeCommandsService;
24
28
  /**
25
29
  * Схема NA.
26
30
  */
@@ -241,4 +245,48 @@ export declare class BridgeToNative {
241
245
  * @param nativeTitle Текст заголовка, для «нативной» части WV, пустая строка — отсутствие заголовка.
242
246
  */
243
247
  setTitle(nativeTitle: string): void;
248
+ /**
249
+ * Возвращает статус доступа к геолокации и, при наличии разрешения, координаты пользователя.
250
+ * Работает только на iOS в версиях `17.0.0` и выше.
251
+ * В Android нужно использовать Web API.
252
+ *
253
+ * @returns Promise с конфигурацией геолокации:
254
+ * `permission`: `allowed` — доступ разрешён; `denied` — запрещён;
255
+ * `notDetermined` — решение ещё не принято; `restricted` — доступ ограничен.
256
+ * `userCoordinate`: `{ latitude, longitude }` или `null`, если доступ не разрешён.
257
+ * Отказ в доступе — успешный ответ с соответствующим permission, а не ошибка запроса.
258
+ */
259
+ getGeoConfiguration(): Promise<GeoConfiguration>;
260
+ /**
261
+ * Воспроизводит тактильный отклик.
262
+ * Работает только на iOS в версиях `17.0.0` и выше.
263
+ *
264
+ * @param isFTEnabled Значение фича-тогла webViewHapticsIOS;
265
+ * при false команда не отправляется.
266
+ * @param options.type Тип тактильного отклика.
267
+ * @param options.intensity Интенсивность от 0 до 1, применяется только
268
+ * к impact-типам. Если не передана, NA использует значение по умолчанию.
269
+ */
270
+ vibrate(options: HapticsOptions, isFTEnabled: boolean): void;
271
+ /**
272
+ * Задаёт область нативной шторы, за которую можно её перетаскивать.
273
+ * Работает только на iOS в версиях `17.0.0` и выше.
274
+ *
275
+ * @param area
276
+ * `wholeSheet` — перетаскивание за любую часть шторы (по умолчанию в NA),
277
+ * данная опция может конфликтовать с `drag` обработчиками в вебе.
278
+ */
279
+ setSheetDragArea(area: SheetDragArea): void;
280
+ /**
281
+ * Скрывает нативный таббар.
282
+ * Метод имеет смысл только на iOS в версиях `17.0.0` и выше, в которых WV-модуль
283
+ * может открываться с таббаром внизу.
284
+ */
285
+ hideTabbar(): void;
286
+ /**
287
+ * Показывает нативный таббар (будет активна вкладка, которая была активна при скрытии).
288
+ * Метод имеет смысл только на iOS в версиях `17.0.0` и выше, в которых WV-модуль
289
+ * может открываться с таббаром внизу.
290
+ */
291
+ showTabbar(): void;
244
292
  }
@@ -3,6 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.BridgeToNative = void 0;
5
5
  const external_links_service_1 = require("./services-and-utils/external-links-service");
6
+ const native_commands_service_1 = require("./services-and-utils/native-commands-service");
6
7
  const native_navigation_and_title_service_1 = require("./services-and-utils/native-navigation-and-title-service");
7
8
  const native_params_service_1 = require("./services-and-utils/native-params-service");
8
9
  /**
@@ -17,13 +18,16 @@ class BridgeToNative {
17
18
  * будут использованы стандартные `History: pushState()` и `History: go()`.
18
19
  * @param options.logError Функция с помощью которой B2N может залогировать ошибку,
19
20
  * если не передать, B2N не будет логировать ошибки.
21
+ * @param options.isSheetWebview Признак открытия WV в шторе. Отвечает за доступность
22
+ * новых методов взаимодействия с нативом. По умолчанию true.
20
23
  */
21
24
  constructor(options) {
22
- var _a, _b, _c, _d;
25
+ var _a, _b, _c, _d, _e, _f, _g;
23
26
  this.options = options;
24
27
  this.nativeParamsService = new native_params_service_1.NativeParamsService((_a = this.options) === null || _a === void 0 ? void 0 : _a.logError);
25
28
  this.externalLinksService = new external_links_service_1.ExternalLinksService(this.nativeParamsService, (_b = this.options) === null || _b === void 0 ? void 0 : _b.logError);
26
29
  this.nativeNavigationAndTitleService = new native_navigation_and_title_service_1.NativeNavigationAndTitleService(this.nativeParamsService, (_c = this.options) === null || _c === void 0 ? void 0 : _c.browserHistoryApiWrappers, (_d = this.options) === null || _d === void 0 ? void 0 : _d.logError);
30
+ this.nativeCommandsService = new native_commands_service_1.NativeCommandsService(this.nativeParamsService, (_e = this.options) === null || _e === void 0 ? void 0 : _e.logError, (_g = (_f = this.options) === null || _f === void 0 ? void 0 : _f.isSheetWebview) !== null && _g !== void 0 ? _g : true);
27
31
  }
28
32
  /**
29
33
  * Схема NA.
@@ -296,5 +300,59 @@ class BridgeToNative {
296
300
  setTitle(nativeTitle) {
297
301
  this.nativeNavigationAndTitleService.setTitle(nativeTitle);
298
302
  }
303
+ /**
304
+ * Возвращает статус доступа к геолокации и, при наличии разрешения, координаты пользователя.
305
+ * Работает только на iOS в версиях `17.0.0` и выше.
306
+ * В Android нужно использовать Web API.
307
+ *
308
+ * @returns Promise с конфигурацией геолокации:
309
+ * `permission`: `allowed` — доступ разрешён; `denied` — запрещён;
310
+ * `notDetermined` — решение ещё не принято; `restricted` — доступ ограничен.
311
+ * `userCoordinate`: `{ latitude, longitude }` или `null`, если доступ не разрешён.
312
+ * Отказ в доступе — успешный ответ с соответствующим permission, а не ошибка запроса.
313
+ */
314
+ getGeoConfiguration() {
315
+ return this.nativeCommandsService.getGeoConfiguration();
316
+ }
317
+ /**
318
+ * Воспроизводит тактильный отклик.
319
+ * Работает только на iOS в версиях `17.0.0` и выше.
320
+ *
321
+ * @param isFTEnabled Значение фича-тогла webViewHapticsIOS;
322
+ * при false команда не отправляется.
323
+ * @param options.type Тип тактильного отклика.
324
+ * @param options.intensity Интенсивность от 0 до 1, применяется только
325
+ * к impact-типам. Если не передана, NA использует значение по умолчанию.
326
+ */
327
+ vibrate(options, isFTEnabled) {
328
+ this.nativeCommandsService.vibrate(options, isFTEnabled);
329
+ }
330
+ /**
331
+ * Задаёт область нативной шторы, за которую можно её перетаскивать.
332
+ * Работает только на iOS в версиях `17.0.0` и выше.
333
+ *
334
+ * @param area
335
+ * `wholeSheet` — перетаскивание за любую часть шторы (по умолчанию в NA),
336
+ * данная опция может конфликтовать с `drag` обработчиками в вебе.
337
+ */
338
+ setSheetDragArea(area) {
339
+ this.nativeCommandsService.setSheetDragArea(area);
340
+ }
341
+ /**
342
+ * Скрывает нативный таббар.
343
+ * Метод имеет смысл только на iOS в версиях `17.0.0` и выше, в которых WV-модуль
344
+ * может открываться с таббаром внизу.
345
+ */
346
+ hideTabbar() {
347
+ this.nativeCommandsService.hideTabbar();
348
+ }
349
+ /**
350
+ * Показывает нативный таббар (будет активна вкладка, которая была активна при скрытии).
351
+ * Метод имеет смысл только на iOS в версиях `17.0.0` и выше, в которых WV-модуль
352
+ * может открываться с таббаром внизу.
353
+ */
354
+ showTabbar() {
355
+ this.nativeCommandsService.showTabbar();
356
+ }
299
357
  }
300
358
  exports.BridgeToNative = BridgeToNative;
@@ -1,4 +1,4 @@
1
- import { type NativeFeaturesFromVersion } from './types';
1
+ import { type ModernAction, type NativeFeaturesFromVersion } from './types';
2
2
  export declare const ANDROID_APP_ID = "alfabank";
3
3
  export declare const DEEP_LINK_PATTERN: RegExp;
4
4
  export declare const NATIVE_FEATURES_FROM_VERSION: NativeFeaturesFromVersion;
@@ -11,3 +11,6 @@ export declare const VERSION_TO_IOS_APP_ID: {
11
11
  readonly '13.5.0': "assistmekz";
12
12
  readonly '14.5.0': "smartfinancementor";
13
13
  };
14
+ export declare const NATIVE_COMMANDS_FROM_VERSION: Readonly<Record<ModernAction, {
15
+ fromVersion: string;
16
+ }>>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VERSION_TO_IOS_APP_ID = exports.NATIVE_FEATURES_FROM_VERSION = exports.DEEP_LINK_PATTERN = exports.ANDROID_APP_ID = void 0;
3
+ exports.NATIVE_COMMANDS_FROM_VERSION = exports.VERSION_TO_IOS_APP_ID = exports.NATIVE_FEATURES_FROM_VERSION = exports.DEEP_LINK_PATTERN = exports.ANDROID_APP_ID = void 0;
4
4
  exports.ANDROID_APP_ID = 'alfabank';
5
5
  exports.DEEP_LINK_PATTERN = /^(\/|alfabank:\/{3}dashboard\/|alfabank:\/{3}|alfabank:\/{2}|https:\/{2}online.alfabank.ru\/)/;
6
6
  exports.NATIVE_FEATURES_FROM_VERSION = {
@@ -28,3 +28,10 @@ exports.VERSION_TO_IOS_APP_ID = {
28
28
  '13.5.0': 'assistmekz',
29
29
  '14.5.0': 'smartfinancementor',
30
30
  };
31
+ exports.NATIVE_COMMANDS_FROM_VERSION = {
32
+ 'geo.configuration': { fromVersion: '17.0.0' },
33
+ 'haptics.vibrate': { fromVersion: '17.0.0' },
34
+ 'sheet.setDragArea': { fromVersion: '17.0.0' },
35
+ 'tabbar.hide': { fromVersion: '17.0.0' },
36
+ 'tabbar.show': { fromVersion: '17.0.0' },
37
+ };
@@ -0,0 +1,33 @@
1
+ import { type LogError, type ModernAction } from '../types';
2
+ export declare const CALL_TIMEOUT_MS = 10000;
3
+ /**
4
+ * Сервис-транспорт для взаимодействия WA с NA.
5
+ */
6
+ export declare class ModernBridgeService {
7
+ private logError?;
8
+ private pendingCalls;
9
+ private savedCallback?;
10
+ constructor(logError?: LogError | undefined);
11
+ /**
12
+ * Отправляет fire-and-forget сообщение в NA (без ожидания ответа).
13
+ */
14
+ send(action: ModernAction, data: unknown): void;
15
+ /**
16
+ * Отправляет сообщение типа `call` и возвращает промис с ответом NA.
17
+ *
18
+ * @throws Если транспорт недоступен или ответ не пришёл за {@link CALL_TIMEOUT_MS}.
19
+ */
20
+ call<Data>(action: ModernAction, data: unknown): Promise<Data>;
21
+ private handleCallback;
22
+ /**
23
+ * Проверяет доступность нативного webkit-моста iOS.
24
+ */
25
+ private hasTransport;
26
+ /**
27
+ * Отправляет тело сообщения доступным транспортом.
28
+ *
29
+ * @returns `true`, если сообщение удалось передать.
30
+ */
31
+ private dispatch;
32
+ private reportNoTransport;
33
+ }
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ModernBridgeService = exports.CALL_TIMEOUT_MS = void 0;
4
+ exports.CALL_TIMEOUT_MS = 10000;
5
+ const BRIDGE_KIND_SEND = 'send';
6
+ const BRIDGE_KIND_CALL = 'call';
7
+ let requestIdCounter = 0;
8
+ const generateRequestId = () => {
9
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
10
+ return crypto.randomUUID();
11
+ }
12
+ requestIdCounter += 1;
13
+ return String(requestIdCounter);
14
+ };
15
+ /**
16
+ * Сервис-транспорт для взаимодействия WA с NA.
17
+ */
18
+ class ModernBridgeService {
19
+ constructor(logError) {
20
+ var _a;
21
+ this.logError = logError;
22
+ this.pendingCalls = new Map();
23
+ this.handleCallback = this.handleCallback.bind(this);
24
+ this.savedCallback = (_a = window.webBridge) === null || _a === void 0 ? void 0 : _a.callback;
25
+ window.webBridge = Object.assign(Object.assign({}, window.webBridge), { callback: this.handleCallback });
26
+ }
27
+ /**
28
+ * Отправляет fire-and-forget сообщение в NA (без ожидания ответа).
29
+ */
30
+ send(action, data) {
31
+ const body = {
32
+ kind: BRIDGE_KIND_SEND,
33
+ action,
34
+ requestId: generateRequestId(),
35
+ data,
36
+ };
37
+ if (!this.dispatch(body)) {
38
+ this.reportNoTransport('send', action);
39
+ }
40
+ }
41
+ /**
42
+ * Отправляет сообщение типа `call` и возвращает промис с ответом NA.
43
+ *
44
+ * @throws Если транспорт недоступен или ответ не пришёл за {@link CALL_TIMEOUT_MS}.
45
+ */
46
+ call(action, data) {
47
+ const requestId = generateRequestId();
48
+ const body = {
49
+ kind: BRIDGE_KIND_CALL,
50
+ action,
51
+ requestId,
52
+ data,
53
+ };
54
+ if (!this.hasTransport()) {
55
+ this.reportNoTransport('call', action);
56
+ return Promise.reject(new Error(`ModernBridgeService: transport is not available for "${action}"`));
57
+ }
58
+ return new Promise((resolve, reject) => {
59
+ const timeoutId = setTimeout(() => {
60
+ this.pendingCalls.delete(requestId);
61
+ reject(new Error(`ModernBridgeService: request "${action}" timed out`));
62
+ }, exports.CALL_TIMEOUT_MS);
63
+ this.pendingCalls.set(requestId, {
64
+ resolve: resolve,
65
+ reject,
66
+ timeoutId,
67
+ });
68
+ this.dispatch(body);
69
+ });
70
+ }
71
+ handleCallback(requestId, payload) {
72
+ var _a;
73
+ const pending = this.pendingCalls.get(requestId);
74
+ if (!pending) {
75
+ (_a = this.savedCallback) === null || _a === void 0 ? void 0 : _a.call(this, requestId, payload);
76
+ return;
77
+ }
78
+ clearTimeout(pending.timeoutId);
79
+ this.pendingCalls.delete(requestId);
80
+ if (payload.error) {
81
+ const error = new Error(payload.error.message);
82
+ error.code = payload.error.code;
83
+ pending.reject(error);
84
+ return;
85
+ }
86
+ pending.resolve(payload.data);
87
+ }
88
+ /**
89
+ * Проверяет доступность нативного webkit-моста iOS.
90
+ */
91
+ // eslint-disable-next-line class-methods-use-this -- единая точка доступа к глобалам window.
92
+ hasTransport() {
93
+ var _a, _b, _c;
94
+ return Boolean((_c = (_b = (_a = window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) === null || _c === void 0 ? void 0 : _c.postMessage);
95
+ }
96
+ /**
97
+ * Отправляет тело сообщения доступным транспортом.
98
+ *
99
+ * @returns `true`, если сообщение удалось передать.
100
+ */
101
+ // eslint-disable-next-line class-methods-use-this -- единая точка доступа к глобалам window.
102
+ dispatch(body) {
103
+ var _a, _b, _c;
104
+ if ((_c = (_b = (_a = window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) === null || _c === void 0 ? void 0 : _c.postMessage) {
105
+ window.webkit.messageHandlers.bridge.postMessage(body);
106
+ return true;
107
+ }
108
+ return false;
109
+ }
110
+ reportNoTransport(kind, action) {
111
+ var _a;
112
+ const message = `ModernBridgeService: native bridge is not available, "${action}" (${kind}) was not sent`;
113
+ (_a = this.logError) === null || _a === void 0 ? void 0 : _a.call(this, message, { action, kind });
114
+ // eslint-disable-next-line no-console -- сообщаем потребителю о недоступности моста.
115
+ console.error(message);
116
+ }
117
+ }
118
+ exports.ModernBridgeService = ModernBridgeService;
@@ -0,0 +1,21 @@
1
+ import { type GeoConfiguration, type HapticsOptions, type LogError, type SheetDragArea } from '../types';
2
+ import { type NativeParamsService } from './native-params-service';
3
+ /**
4
+ * Сервис команд для взаимодействия WA с NA (iOS, NA ≥ 17.0.0):
5
+ * геолокация, тактильный отклик, нативная штора и таббар.
6
+ *
7
+ * Инкапсулирует гейт доступности по платформе и версии NA и формирует
8
+ * данные для вызовов через {@link ModernBridgeService}.
9
+ */
10
+ export declare class NativeCommandsService {
11
+ private nativeParamsService;
12
+ private isSheetWebview;
13
+ constructor(nativeParamsService: NativeParamsService, logError?: LogError, isSheetWebview?: boolean);
14
+ private modernBridgeService;
15
+ getGeoConfiguration(): Promise<GeoConfiguration>;
16
+ vibrate({ type, intensity }: HapticsOptions, isFTEnabled: boolean): void;
17
+ setSheetDragArea(area: SheetDragArea): void;
18
+ hideTabbar(): void;
19
+ showTabbar(): void;
20
+ private isAvailable;
21
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NativeCommandsService = void 0;
4
+ const modern_bridge_service_1 = require("./modern-bridge-service");
5
+ const native_features_1 = require("./native-features");
6
+ /**
7
+ * Сервис команд для взаимодействия WA с NA (iOS, NA ≥ 17.0.0):
8
+ * геолокация, тактильный отклик, нативная штора и таббар.
9
+ *
10
+ * Инкапсулирует гейт доступности по платформе и версии NA и формирует
11
+ * данные для вызовов через {@link ModernBridgeService}.
12
+ */
13
+ class NativeCommandsService {
14
+ constructor(nativeParamsService, logError, isSheetWebview = true) {
15
+ this.nativeParamsService = nativeParamsService;
16
+ this.isSheetWebview = isSheetWebview;
17
+ this.modernBridgeService = new modern_bridge_service_1.ModernBridgeService(logError);
18
+ }
19
+ getGeoConfiguration() {
20
+ if (!this.isAvailable('geo.configuration')) {
21
+ return Promise.reject(new Error('NativeCommandsService: geo.configuration is unavailable in this environment'));
22
+ }
23
+ return this.modernBridgeService.call('geo.configuration', {});
24
+ }
25
+ vibrate({ type, intensity }, isFTEnabled) {
26
+ if (!isFTEnabled || !this.isAvailable('haptics.vibrate')) {
27
+ return;
28
+ }
29
+ this.modernBridgeService.send('haptics.vibrate', Object.assign({ type }, (intensity === undefined ? {} : { intensity })));
30
+ }
31
+ setSheetDragArea(area) {
32
+ if (!this.isAvailable('sheet.setDragArea')) {
33
+ return;
34
+ }
35
+ this.modernBridgeService.send('sheet.setDragArea', { area });
36
+ }
37
+ hideTabbar() {
38
+ if (!this.isAvailable('tabbar.hide')) {
39
+ return;
40
+ }
41
+ this.modernBridgeService.send('tabbar.hide', {});
42
+ }
43
+ showTabbar() {
44
+ if (!this.isAvailable('tabbar.show')) {
45
+ return;
46
+ }
47
+ this.modernBridgeService.send('tabbar.show', {});
48
+ }
49
+ isAvailable(action) {
50
+ return (this.isSheetWebview &&
51
+ (0, native_features_1.canUseNativeCommand)(this.nativeParamsService.environment, this.nativeParamsService.appVersion, action));
52
+ }
53
+ }
54
+ exports.NativeCommandsService = NativeCommandsService;
@@ -1,4 +1,4 @@
1
- import { type Environment, type NativeFeatureKey } from '../types';
1
+ import { type Environment, type ModernAction, type NativeFeatureKey } from '../types';
2
2
  export declare const isValidVersionFormat: (version?: string) => version is string;
3
3
  /**
4
4
  * Сравнивает версии формата `x.y.z` покомпонентно, как числа.
@@ -10,3 +10,10 @@ export declare const isVersionHigherOrEqual: (version: string, versionToCompare:
10
10
  * Версия в неизвестном формате считается `0.0.0`.
11
11
  */
12
12
  export declare const canUseNativeFeature: (platform: Environment, appVersion: string, feature: NativeFeatureKey) => boolean;
13
+ /**
14
+ * Проверяет доступность команды для указанной платформы и версии NA.
15
+ *
16
+ * Проверяемые команды поддерживаются только на iOS.
17
+ * Версия в неизвестном формате считается `0.0.0`.
18
+ */
19
+ export declare const canUseNativeCommand: (platform: Environment, appVersion: string, action: ModernAction) => boolean;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.canUseNativeFeature = exports.isVersionHigherOrEqual = exports.isValidVersionFormat = void 0;
3
+ exports.canUseNativeCommand = exports.canUseNativeFeature = exports.isVersionHigherOrEqual = exports.isValidVersionFormat = void 0;
4
4
  const constants_1 = require("../constants");
5
5
  const VERSION_FORMAT_PATTERN = /^\d+\.\d+\.\d+$/;
6
6
  const isValidVersionFormat = (version) => Boolean(version) && VERSION_FORMAT_PATTERN.test(version);
@@ -32,3 +32,17 @@ const canUseNativeFeature = (platform, appVersion, feature) => {
32
32
  return (0, exports.isVersionHigherOrEqual)((0, exports.isValidVersionFormat)(appVersion) ? appVersion : '0.0.0', fromVersion);
33
33
  };
34
34
  exports.canUseNativeFeature = canUseNativeFeature;
35
+ /**
36
+ * Проверяет доступность команды для указанной платформы и версии NA.
37
+ *
38
+ * Проверяемые команды поддерживаются только на iOS.
39
+ * Версия в неизвестном формате считается `0.0.0`.
40
+ */
41
+ const canUseNativeCommand = (platform, appVersion, action) => {
42
+ if (platform !== 'ios') {
43
+ return false;
44
+ }
45
+ const { fromVersion } = constants_1.NATIVE_COMMANDS_FROM_VERSION[action];
46
+ return (0, exports.isVersionHigherOrEqual)((0, exports.isValidVersionFormat)(appVersion) ? appVersion : '0.0.0', fromVersion);
47
+ };
48
+ exports.canUseNativeCommand = canUseNativeCommand;
package/client/types.d.ts CHANGED
@@ -22,4 +22,27 @@ export type NativeFeaturesFromVersion = Readonly<{
22
22
  }>;
23
23
  export type PdfType = 'pdfFile' | 'base64' | 'binary';
24
24
  export type Theme = 'light' | 'dark';
25
+ export type ModernAction = 'geo.configuration' | 'haptics.vibrate' | 'sheet.setDragArea' | 'tabbar.hide' | 'tabbar.show';
26
+ export type GeoPermission = 'allowed' | 'denied' | 'notDetermined' | 'restricted';
27
+ export type UserCoordinate = {
28
+ latitude: number;
29
+ longitude: number;
30
+ };
31
+ export type GeoConfiguration = {
32
+ permission: GeoPermission;
33
+ userCoordinate: UserCoordinate | null;
34
+ };
35
+ export type HapticsType = 'light' | 'medium' | 'heavy' | 'soft' | 'rigid' | 'success' | 'warning' | 'error' | 'selection';
36
+ export type HapticsOptions = {
37
+ type: HapticsType;
38
+ intensity?: number;
39
+ };
40
+ export type SheetDragArea = 'wholeSheet' | 'navigationBar';
41
+ export type CallbackPayload = {
42
+ data: unknown;
43
+ error: {
44
+ code: number;
45
+ message: string;
46
+ } | null;
47
+ };
25
48
  export {};
package/package.json CHANGED
@@ -1,127 +1,132 @@
1
1
  {
2
- "name": "@alfalab/bridge-to-native",
3
- "version": "1.5.1",
4
- "license": "MIT",
5
- "description": "Утилита для удобной работы веб приложения внутри нативного приложения и коммуникации с ним.",
6
- "engines": {
7
- "node": ">=20.19.2",
8
- "npm": "please-use-yarn"
2
+ "name": "@alfalab/bridge-to-native",
3
+ "version": "1.5.2-beta.feed590",
4
+ "license": "MIT",
5
+ "description": "Утилита для удобной работы веб приложения внутри нативного приложения и коммуникации с ним.",
6
+ "engines": {
7
+ "node": ">=20.19.2",
8
+ "npm": "please-use-yarn"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/core-ds/bridge-to-native.git"
13
+ },
14
+ "exports": {
15
+ "./client": {
16
+ "import": "./client/index.js",
17
+ "require": "./client/index.js",
18
+ "types": "./client/index.d.ts"
9
19
  },
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/core-ds/bridge-to-native.git"
20
+ "./client/primitives": {
21
+ "import": "./client/primitives.js",
22
+ "require": "./client/primitives.js",
23
+ "types": "./client/primitives.d.ts"
13
24
  },
14
- "exports": {
15
- "./client": {
16
- "import": "./client/index.js",
17
- "require": "./client/index.js",
18
- "types": "./client/index.d.ts"
19
- },
20
- "./client/primitives": {
21
- "import": "./client/primitives.js",
22
- "require": "./client/primitives.js",
23
- "types": "./client/primitives.d.ts"
24
- },
25
- "./server": {
26
- "import": "./server/index.js",
27
- "require": "./server/index.js",
28
- "types": "./server/index.d.ts"
29
- }
30
- },
31
- "sideEffects": false,
32
- "bugs": {
33
- "url": "https://github.com/core-ds/bridge-to-native/issues"
34
- },
35
- "scripts": {
36
- "build": "yarn build:clean && yarn build:ts",
37
- "build:clean": "shx rm -rf .publish",
38
- "build:copy-package-json": "shx cp package.json .publish/package.json",
39
- "build:ts": "tsc --build",
40
- "format": "arui-presets-lint format",
41
- "format:check": "arui-presets-lint format:check",
42
- "lint": "yarn lint:scripts && yarn format:check",
43
- "lint:fix": "yarn lint:scripts --fix && yarn format",
44
- "lint:scripts": "arui-presets-lint scripts",
45
- "pub": "npm publish .publish --userconfig \"../.npmrc\" --tag \"$TAG\"",
46
- "release": "yarn build && yarn build:copy-package-json && yarn pub",
47
- "test": "arui-scripts test --silent --collect-coverage"
25
+ "./server": {
26
+ "import": "./server/index.js",
27
+ "require": "./server/index.js",
28
+ "types": "./server/index.d.ts"
29
+ }
30
+ },
31
+ "sideEffects": false,
32
+ "bugs": {
33
+ "url": "https://github.com/core-ds/bridge-to-native/issues"
34
+ },
35
+ "scripts": {
36
+ "build": "yarn build:clean && yarn build:ts",
37
+ "build:clean": "shx rm -rf .publish",
38
+ "build:copy-package-json": "shx cp package.json .publish/package.json",
39
+ "build:ts": "tsc --build",
40
+ "format": "arui-presets-lint format",
41
+ "format:check": "arui-presets-lint format:check",
42
+ "lint": "yarn lint:scripts && yarn format:check",
43
+ "lint:fix": "yarn lint:scripts --fix && yarn format",
44
+ "lint:scripts": "arui-presets-lint scripts",
45
+ "pub": "npm publish .publish --userconfig \"../.npmrc\" --tag \"$TAG\"",
46
+ "release": "yarn build && yarn build:copy-package-json && yarn pub",
47
+ "test": "arui-scripts test --silent --collect-coverage"
48
+ },
49
+ "devDependencies": {
50
+ "@happy-dom/jest-environment": "18.0.1",
51
+ "@types/jest": "29.5.14",
52
+ "@types/node": "20.19.1",
53
+ "arui-presets-lint": "8.7.0",
54
+ "arui-scripts": "19.0.7",
55
+ "copyfiles": "2.4.1",
56
+ "jest-junit": "10.0.0",
57
+ "lint-staged": "^12.5.0",
58
+ "promisify-child-process": "4.1.1",
59
+ "shx": "0.3.4",
60
+ "typescript": "5.5.4"
61
+ },
62
+ "commitlint": {
63
+ "extends": "./node_modules/arui-presets-lint/commitlint"
64
+ },
65
+ "eslintConfig": {
66
+ "extends": "./node_modules/arui-presets-lint/eslint",
67
+ "settings": {
68
+ "react": {
69
+ "version": "18.0.0"
70
+ }
48
71
  },
49
- "devDependencies": {
50
- "@happy-dom/jest-environment": "18.0.1",
51
- "@types/jest": "29.5.14",
52
- "@types/node": "20.19.1",
53
- "arui-presets-lint": "8.7.0",
54
- "arui-scripts": "19.0.7",
55
- "copyfiles": "2.4.1",
56
- "jest-junit": "10.0.0",
57
- "lint-staged": "^12.5.0",
58
- "promisify-child-process": "4.1.1",
59
- "shx": "0.3.4",
60
- "typescript": "5.5.4"
61
- },
62
- "commitlint": {
63
- "extends": "./node_modules/arui-presets-lint/commitlint"
64
- },
65
- "eslintConfig": {
66
- "extends": "./node_modules/arui-presets-lint/eslint",
67
- "parserOptions": {
68
- "project": [
69
- "./__tests__/tsconfig.json",
70
- "./src/client/tsconfig.json",
71
- "./src/server/tsconfig.json"
72
- ]
73
- },
74
- "overrides": [
75
- {
76
- "files": [
77
- "__tests__/**/*"
78
- ],
79
- "rules": {
80
- "max-lines": "off"
81
- }
82
- }
83
- ]
72
+ "parserOptions": {
73
+ "project": [
74
+ "./__tests__/tsconfig.json",
75
+ "./src/client/tsconfig.json",
76
+ "./src/server/tsconfig.json"
77
+ ]
84
78
  },
85
- "jest": {
86
- "projects": [
87
- {
88
- "displayName": "client-tests",
89
- "testEnvironment": "@happy-dom/jest-environment",
90
- "testPathIgnorePatterns": [
91
- "/__tests__/server/"
92
- ]
93
- },
94
- {
95
- "displayName": "server-tests",
96
- "testEnvironment": "node",
97
- "testPathIgnorePatterns": [
98
- "/__tests__/client/"
99
- ]
100
- }
79
+ "overrides": [
80
+ {
81
+ "files": [
82
+ "__tests__/**/*"
101
83
  ],
102
- "testRegex": [
103
- "__tests__/.*\\.test\\.ts"
104
- ],
105
- "coveragePathIgnorePatterns": [
106
- "/node_modules/",
107
- "/src/(client|server)/index.ts",
108
- "/src/client/primitives.ts"
109
- ],
110
- "reporters": [
111
- "default",
112
- "jest-junit"
84
+ "rules": {
85
+ "max-lines": "off"
86
+ }
87
+ }
88
+ ]
89
+ },
90
+ "jest": {
91
+ "projects": [
92
+ {
93
+ "displayName": "client-tests",
94
+ "testEnvironment": "@happy-dom/jest-environment",
95
+ "testPathIgnorePatterns": [
96
+ "/__tests__/server/"
113
97
  ]
114
- },
115
- "prettier": "arui-presets-lint/prettier",
116
- "stylelint": {
117
- "extends": "arui-presets-lint/stylelint",
118
- "ignoreFiles": [
119
- "coverage/**/*.js",
120
- ".yarn/releases/*"
98
+ },
99
+ {
100
+ "displayName": "server-tests",
101
+ "testEnvironment": "node",
102
+ "testPathIgnorePatterns": [
103
+ "/__tests__/client/"
121
104
  ]
122
- },
123
- "publishConfig": {
124
- "registry": "https://registry.npmjs.org"
125
- },
126
- "packageManager": "yarn@4.12.0"
105
+ }
106
+ ],
107
+ "testRegex": [
108
+ "__tests__/.*\\.test\\.ts"
109
+ ],
110
+ "coveragePathIgnorePatterns": [
111
+ "/node_modules/",
112
+ "/src/(client|server)/index.ts",
113
+ "/src/client/primitives.ts"
114
+ ],
115
+ "reporters": [
116
+ "default",
117
+ "jest-junit"
118
+ ]
119
+ },
120
+ "prettier": "arui-presets-lint/prettier",
121
+ "stylelint": {
122
+ "extends": "arui-presets-lint/stylelint",
123
+ "ignoreFiles": [
124
+ "coverage/**/*.js",
125
+ ".yarn/releases/*"
126
+ ]
127
+ },
128
+ "publishConfig": {
129
+ "registry": "https://registry.npmjs.org"
130
+ },
131
+ "packageManager": "yarn@4.12.0"
127
132
  }