@webority/mobile-core 0.0.28 → 0.1.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.
- package/lib/commonjs/api/baseUrl.js +1 -34
- package/lib/commonjs/api/curl.js +1 -109
- package/lib/commonjs/api/multipart.js +1 -21
- package/lib/commonjs/api/publicClient.js +1 -79
- package/lib/commonjs/api/responseBodyText.js +1 -0
- package/lib/commonjs/api/retry.js +1 -91
- package/lib/commonjs/api/tokenRefresh.js +1 -205
- package/lib/commonjs/api/userClient.js +1 -265
- package/lib/commonjs/auth/authStore.js +1 -265
- package/lib/commonjs/auth/index.js +1 -44
- package/lib/commonjs/auth/jwt.js +1 -112
- package/lib/commonjs/config/index.js +1 -72
- package/lib/commonjs/deepLink/index.js +1 -286
- package/lib/commonjs/download/adapters/expoFs.js +1 -69
- package/lib/commonjs/download/adapters/shared.js +1 -13
- package/lib/commonjs/download/index.js +1 -250
- package/lib/commonjs/formatters/currency.js +1 -70
- package/lib/commonjs/formatters/date.js +1 -167
- package/lib/commonjs/formatters/dateMath.js +1 -311
- package/lib/commonjs/formatters/index.js +1 -246
- package/lib/commonjs/formatters/initials.js +1 -32
- package/lib/commonjs/formatters/intlCache.js +1 -37
- package/lib/commonjs/formatters/number.js +1 -89
- package/lib/commonjs/formatters/phone.js +1 -369
- package/lib/commonjs/formatters/windowsToIanaTable.js +1 -164
- package/lib/commonjs/geolocation/adapters/expoLocation.js +1 -126
- package/lib/commonjs/geolocation/index.js +1 -355
- package/lib/commonjs/index.js +1 -644
- package/lib/commonjs/initSDK.js +1 -66
- package/lib/commonjs/initUserAuth.js +1 -37
- package/lib/commonjs/logger/crashlytics.js +1 -0
- package/lib/commonjs/logger/index.js +1 -301
- package/lib/commonjs/logger/redact.js +1 -50
- package/lib/commonjs/network/index.js +1 -31
- package/lib/commonjs/network/networkStatus.js +1 -171
- package/lib/commonjs/permissions/calendar.js +1 -14
- package/lib/commonjs/permissions/camera.js +1 -14
- package/lib/commonjs/permissions/contacts.js +1 -10
- package/lib/commonjs/permissions/index.js +1 -133
- package/lib/commonjs/permissions/location.js +1 -14
- package/lib/commonjs/permissions/mediaLibrary.js +1 -10
- package/lib/commonjs/permissions/notifications.js +1 -10
- package/lib/commonjs/permissions/photos.js +1 -14
- package/lib/commonjs/phone/countries.js +1 -265
- package/lib/commonjs/push/index.js +1 -61
- package/lib/commonjs/push/push.js +1 -443
- package/lib/commonjs/push/status.js +1 -0
- package/lib/commonjs/push/task.js +1 -43
- package/lib/commonjs/secureScreen/index.js +1 -0
- package/lib/commonjs/share/index.js +1 -70
- package/lib/commonjs/smsRetriever/index.js +1 -91
- package/lib/commonjs/specs/NativeSmsRetriever.js +1 -15
- package/lib/commonjs/sqlite/adapters/expo.js +1 -53
- package/lib/commonjs/sqlite/index.js +1 -604
- package/lib/commonjs/storage/index.js +1 -214
- package/lib/commonjs/types/axios.js +1 -4
- package/lib/commonjs/types/globals.d.js +1 -6
- package/lib/commonjs/utils/base64.js +1 -24
- package/lib/commonjs/utils/imageCompression.js +1 -389
- package/lib/commonjs/utils/index.js +1 -19
- package/lib/commonjs/validators/index.js +1 -227
- package/lib/commonjs/versionCheck/index.js +1 -419
- package/lib/module/api/baseUrl.js +1 -30
- package/lib/module/api/curl.js +1 -104
- package/lib/module/api/multipart.js +1 -16
- package/lib/module/api/publicClient.js +1 -75
- package/lib/module/api/responseBodyText.js +1 -0
- package/lib/module/api/retry.js +1 -85
- package/lib/module/api/tokenRefresh.js +1 -192
- package/lib/module/api/userClient.js +1 -243
- package/lib/module/auth/authStore.js +1 -257
- package/lib/module/auth/index.js +1 -5
- package/lib/module/auth/jwt.js +1 -106
- package/lib/module/config/index.js +1 -64
- package/lib/module/deepLink/index.js +1 -280
- package/lib/module/download/adapters/expoFs.js +1 -64
- package/lib/module/download/adapters/shared.js +1 -8
- package/lib/module/download/index.js +1 -242
- package/lib/module/formatters/currency.js +1 -65
- package/lib/module/formatters/date.js +1 -159
- package/lib/module/formatters/dateMath.js +1 -295
- package/lib/module/formatters/index.js +1 -9
- package/lib/module/formatters/initials.js +1 -27
- package/lib/module/formatters/intlCache.js +1 -30
- package/lib/module/formatters/number.js +1 -82
- package/lib/module/formatters/phone.js +1 -302
- package/lib/module/formatters/windowsToIanaTable.js +1 -160
- package/lib/module/geolocation/adapters/expoLocation.js +1 -121
- package/lib/module/geolocation/index.js +1 -347
- package/lib/module/index.js +1 -57
- package/lib/module/initSDK.js +1 -61
- package/lib/module/initUserAuth.js +1 -33
- package/lib/module/logger/crashlytics.js +1 -0
- package/lib/module/logger/index.js +1 -295
- package/lib/module/logger/redact.js +1 -44
- package/lib/module/network/index.js +1 -4
- package/lib/module/network/networkStatus.js +1 -161
- package/lib/module/permissions/calendar.js +1 -15
- package/lib/module/permissions/camera.js +1 -15
- package/lib/module/permissions/contacts.js +1 -11
- package/lib/module/permissions/index.js +1 -128
- package/lib/module/permissions/location.js +1 -15
- package/lib/module/permissions/mediaLibrary.js +1 -11
- package/lib/module/permissions/notifications.js +1 -11
- package/lib/module/permissions/photos.js +1 -15
- package/lib/module/phone/countries.js +1 -261
- package/lib/module/push/index.js +1 -4
- package/lib/module/push/push.js +1 -427
- package/lib/module/push/status.js +1 -0
- package/lib/module/push/task.js +1 -38
- package/lib/module/secureScreen/index.js +1 -0
- package/lib/module/share/index.js +1 -64
- package/lib/module/smsRetriever/index.js +1 -86
- package/lib/module/specs/NativeSmsRetriever.js +1 -13
- package/lib/module/sqlite/adapters/expo.js +1 -48
- package/lib/module/sqlite/index.js +1 -594
- package/lib/module/storage/index.js +1 -208
- package/lib/module/types/axios.js +1 -4
- package/lib/module/types/globals.d.js +1 -10
- package/lib/module/utils/base64.js +1 -19
- package/lib/module/utils/imageCompression.js +1 -383
- package/lib/module/utils/index.js +1 -4
- package/lib/module/validators/index.js +1 -205
- package/lib/module/versionCheck/index.js +1 -413
- package/lib/typescript/commonjs/api/responseBodyText.d.ts +6 -0
- package/lib/typescript/commonjs/index.d.ts +5 -0
- package/lib/typescript/commonjs/logger/crashlytics.d.ts +31 -0
- package/lib/typescript/commonjs/push/index.d.ts +3 -1
- package/lib/typescript/commonjs/push/push.d.ts +9 -1
- package/lib/typescript/commonjs/push/status.d.ts +9 -0
- package/lib/typescript/commonjs/secureScreen/index.d.ts +25 -0
- package/lib/typescript/module/api/responseBodyText.d.ts +6 -0
- package/lib/typescript/module/index.d.ts +5 -0
- package/lib/typescript/module/logger/crashlytics.d.ts +31 -0
- package/lib/typescript/module/push/index.d.ts +3 -1
- package/lib/typescript/module/push/push.d.ts +9 -1
- package/lib/typescript/module/push/status.d.ts +9 -0
- package/lib/typescript/module/secureScreen/index.d.ts +25 -0
- package/package.json +23 -4
|
@@ -1,443 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.usePush = exports.toPushAction = exports.toNotificationActions = exports.setPushImplementation = exports.setCategories = exports.setBadgeCount = exports.routeTaskPayload = exports.resolveModules = exports.onAction = exports.notifyLocal = exports.initPush = exports.enablePush = exports.disablePush = void 0;
|
|
7
|
-
var _react = require("react");
|
|
8
|
-
var _reactNative = require("react-native");
|
|
9
|
-
var _index = require("../logger/index.js");
|
|
10
|
-
/** A button on a notification category. */
|
|
11
|
-
|
|
12
|
-
/** A set of buttons a push names through its category id. */
|
|
13
|
-
|
|
14
|
-
/** A button tap on a notification. */
|
|
15
|
-
|
|
16
|
-
/** The slice of expo-notifications this module calls, so the optional peer stays untyped at build. */
|
|
17
|
-
|
|
18
|
-
let override = null;
|
|
19
|
-
|
|
20
|
-
/** Expo modules resolved once; null when push cannot work in this build. */
|
|
21
|
-
let resolved;
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Replace the native modules. For tests and the showcase, to reach paths a
|
|
25
|
-
* real device never takes; an injected backend is taken on trust, Expo Go
|
|
26
|
-
* included. Pass `null` to restore expo-notifications.
|
|
27
|
-
*/
|
|
28
|
-
const setPushImplementation = impl => {
|
|
29
|
-
override = impl;
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* The only place expo-notifications and expo-application are named. Expo Go is
|
|
34
|
-
* checked first because expo-notifications refuses remote push there and its
|
|
35
|
-
* import throws on Android. Exported for `./task`; not on the `/push` entry.
|
|
36
|
-
*/
|
|
37
|
-
exports.setPushImplementation = setPushImplementation;
|
|
38
|
-
const resolveModules = () => {
|
|
39
|
-
if (override) {
|
|
40
|
-
return override;
|
|
41
|
-
}
|
|
42
|
-
if (resolved !== undefined) {
|
|
43
|
-
return resolved;
|
|
44
|
-
}
|
|
45
|
-
try {
|
|
46
|
-
const expo = require('expo');
|
|
47
|
-
if (expo.isRunningInExpoGo()) {
|
|
48
|
-
resolved = null;
|
|
49
|
-
return resolved;
|
|
50
|
-
}
|
|
51
|
-
const notifications = require('expo-notifications');
|
|
52
|
-
const application = require('expo-application');
|
|
53
|
-
resolved = {
|
|
54
|
-
notifications,
|
|
55
|
-
applicationId: application.applicationId
|
|
56
|
-
};
|
|
57
|
-
} catch (error) {
|
|
58
|
-
_index.Logger.warn('[push] expo-notifications is not available; push is off', error);
|
|
59
|
-
resolved = null;
|
|
60
|
-
}
|
|
61
|
-
return resolved;
|
|
62
|
-
};
|
|
63
|
-
exports.resolveModules = resolveModules;
|
|
64
|
-
let state = {
|
|
65
|
-
status: 'unknown',
|
|
66
|
-
enabled: false
|
|
67
|
-
};
|
|
68
|
-
const subscribers = new Set();
|
|
69
|
-
const setState = next => {
|
|
70
|
-
state = {
|
|
71
|
-
...state,
|
|
72
|
-
...next
|
|
73
|
-
};
|
|
74
|
-
for (const notify of subscribers) {
|
|
75
|
-
notify();
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
let config = null;
|
|
79
|
-
let channelsReady = Promise.resolve();
|
|
80
|
-
let tokenSubscription = null;
|
|
81
|
-
let actionHandler = null;
|
|
82
|
-
let listening = false;
|
|
83
|
-
/** Responses that arrived before anything could handle them, e.g. the launching tap before initPush. */
|
|
84
|
-
const pendingResponses = [];
|
|
85
|
-
/** Response key to when it was routed. */
|
|
86
|
-
const routedAt = new Map();
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* The cold-start read, the live listener and, on Android, the background task
|
|
90
|
-
* can each report the same response a moment apart.
|
|
91
|
-
*/
|
|
92
|
-
const REPEAT_WINDOW_MS = 10_000;
|
|
93
|
-
const requireConfig = () => {
|
|
94
|
-
if (!config) {
|
|
95
|
-
throw new Error('[@webority/mobile-core] call initPush before enablePush or disablePush.');
|
|
96
|
-
}
|
|
97
|
-
return config;
|
|
98
|
-
};
|
|
99
|
-
const toPermissionStatus = response => {
|
|
100
|
-
if (response.granted) {
|
|
101
|
-
return 'granted';
|
|
102
|
-
}
|
|
103
|
-
return response.status === 'denied' ? 'denied' : 'unknown';
|
|
104
|
-
};
|
|
105
|
-
|
|
106
|
-
/** Push data travels as strings; iOS can hand back numbers or objects for top-level keys. */
|
|
107
|
-
const toStringData = data => {
|
|
108
|
-
const out = {};
|
|
109
|
-
for (const [key, value] of Object.entries(data ?? {})) {
|
|
110
|
-
if (value === null || value === undefined) {
|
|
111
|
-
continue;
|
|
112
|
-
}
|
|
113
|
-
out[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);
|
|
114
|
-
}
|
|
115
|
-
return out;
|
|
116
|
-
};
|
|
117
|
-
const responseData = response => {
|
|
118
|
-
const content = response.notification.request.content;
|
|
119
|
-
if (content.data) {
|
|
120
|
-
return toStringData(content.data);
|
|
121
|
-
}
|
|
122
|
-
if (typeof content.dataString === 'string') {
|
|
123
|
-
try {
|
|
124
|
-
return toStringData(JSON.parse(content.dataString));
|
|
125
|
-
} catch (error) {
|
|
126
|
-
_index.Logger.error('[push] notification data is not JSON', error);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
return {};
|
|
130
|
-
};
|
|
131
|
-
const toPushAction = response => ({
|
|
132
|
-
actionId: response.actionIdentifier,
|
|
133
|
-
...(response.userText ? {
|
|
134
|
-
userText: response.userText
|
|
135
|
-
} : {}),
|
|
136
|
-
data: responseData(response),
|
|
137
|
-
notificationId: response.notification.request.identifier
|
|
138
|
-
});
|
|
139
|
-
exports.toPushAction = toPushAction;
|
|
140
|
-
const toNotificationActions = actions => actions.map(action => ({
|
|
141
|
-
identifier: action.id,
|
|
142
|
-
buttonTitle: action.title,
|
|
143
|
-
...(action.textInput ? {
|
|
144
|
-
textInput: {
|
|
145
|
-
submitButtonTitle: action.textInput.submitTitle,
|
|
146
|
-
placeholder: action.textInput.placeholder
|
|
147
|
-
}
|
|
148
|
-
} : {}),
|
|
149
|
-
options: {
|
|
150
|
-
opensAppToForeground: action.opensApp ?? true,
|
|
151
|
-
isDestructive: action.destructive ?? false,
|
|
152
|
-
isAuthenticationRequired: action.authenticationRequired ?? false
|
|
153
|
-
}
|
|
154
|
-
}));
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Sends a button tap to the action handler and a plain tap to `onOpen`. A
|
|
158
|
-
* button tap with no action handler opens like a plain tap. Resolves once the
|
|
159
|
-
* handler has finished, so a background task stays alive for its request.
|
|
160
|
-
*/
|
|
161
|
-
exports.toNotificationActions = toNotificationActions;
|
|
162
|
-
const routeResponse = async (m, response) => {
|
|
163
|
-
const key = `${response.notification.request.identifier}:${response.actionIdentifier}`;
|
|
164
|
-
const last = routedAt.get(key);
|
|
165
|
-
if (last !== undefined && Date.now() - last < REPEAT_WINDOW_MS) {
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
const isAction = response.actionIdentifier !== m.DEFAULT_ACTION_IDENTIFIER;
|
|
169
|
-
if (isAction && actionHandler) {
|
|
170
|
-
routedAt.set(key, Date.now());
|
|
171
|
-
try {
|
|
172
|
-
await actionHandler(toPushAction(response));
|
|
173
|
-
} catch (error) {
|
|
174
|
-
_index.Logger.error('[push] onAction threw', error);
|
|
175
|
-
}
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
if (!config) {
|
|
179
|
-
pendingResponses.push(response);
|
|
180
|
-
return;
|
|
181
|
-
}
|
|
182
|
-
routedAt.set(key, Date.now());
|
|
183
|
-
try {
|
|
184
|
-
config.onOpen(responseData(response));
|
|
185
|
-
} catch (error) {
|
|
186
|
-
_index.Logger.error('[push] onOpen threw', error);
|
|
187
|
-
}
|
|
188
|
-
};
|
|
189
|
-
const drainPending = async m => {
|
|
190
|
-
const queued = pendingResponses.splice(0);
|
|
191
|
-
for (const response of queued) {
|
|
192
|
-
await routeResponse(m, response);
|
|
193
|
-
}
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
/** Follows taps and button taps, including the one that launched the app. Wired once per process. */
|
|
197
|
-
const listenForResponses = m => {
|
|
198
|
-
if (listening) {
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
|
-
listening = true;
|
|
202
|
-
m.addNotificationResponseReceivedListener(response => {
|
|
203
|
-
void routeResponse(m, response);
|
|
204
|
-
});
|
|
205
|
-
void m.getLastNotificationResponseAsync().then(async response => {
|
|
206
|
-
if (response) {
|
|
207
|
-
await routeResponse(m, response);
|
|
208
|
-
}
|
|
209
|
-
return m.clearLastNotificationResponseAsync?.();
|
|
210
|
-
}).catch(error => _index.Logger.error('[push] reading the launch notification failed', error));
|
|
211
|
-
};
|
|
212
|
-
|
|
213
|
-
/** The payload of the background notification task: routes button taps, ignores received pushes. */
|
|
214
|
-
const routeTaskPayload = async payload => {
|
|
215
|
-
const mods = resolveModules();
|
|
216
|
-
const response = payload;
|
|
217
|
-
if (!mods || typeof response?.actionIdentifier !== 'string' || typeof response.notification?.request?.identifier !== 'string') {
|
|
218
|
-
return;
|
|
219
|
-
}
|
|
220
|
-
await routeResponse(mods.notifications, response);
|
|
221
|
-
};
|
|
222
|
-
exports.routeTaskPayload = routeTaskPayload;
|
|
223
|
-
const createChannels = async (m, channels) => {
|
|
224
|
-
for (const channel of channels) {
|
|
225
|
-
try {
|
|
226
|
-
await m.setNotificationChannelAsync(channel.id, {
|
|
227
|
-
name: channel.name,
|
|
228
|
-
importance: channel.importance === 'high' ? m.AndroidImportance.HIGH : m.AndroidImportance.DEFAULT
|
|
229
|
-
});
|
|
230
|
-
} catch (error) {
|
|
231
|
-
_index.Logger.error(`[push] creating channel ${channel.id} failed`, error);
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
};
|
|
235
|
-
const toDevice = async (token, applicationId) => {
|
|
236
|
-
const platform = token.type === 'android' ? 'Fcm' : token.type === 'ios' ? 'Apns' : null;
|
|
237
|
-
if (!platform || typeof token.data !== 'string') {
|
|
238
|
-
return null;
|
|
239
|
-
}
|
|
240
|
-
if (!applicationId) {
|
|
241
|
-
throw new Error('[@webority/mobile-core] push needs the app bundle id from expo-application.');
|
|
242
|
-
}
|
|
243
|
-
const installationId = await requireConfig().getInstallationId();
|
|
244
|
-
return {
|
|
245
|
-
installationId,
|
|
246
|
-
platform,
|
|
247
|
-
token: token.data,
|
|
248
|
-
appId: applicationId
|
|
249
|
-
};
|
|
250
|
-
};
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Wires push at startup: the foreground handler, Android channels, and tap
|
|
254
|
-
* handling, including the tap that launched the app. Calling it again only
|
|
255
|
-
* replaces the config.
|
|
256
|
-
*/
|
|
257
|
-
const initPush = next => {
|
|
258
|
-
const first = config === null;
|
|
259
|
-
config = next;
|
|
260
|
-
if (!first) {
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
const mods = resolveModules();
|
|
264
|
-
if (!mods) {
|
|
265
|
-
setState({
|
|
266
|
-
status: 'unavailable'
|
|
267
|
-
});
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
const m = mods.notifications;
|
|
271
|
-
m.setNotificationHandler({
|
|
272
|
-
handleNotification: async () => {
|
|
273
|
-
const show = config?.showInForeground?.() ?? true;
|
|
274
|
-
return {
|
|
275
|
-
shouldShowBanner: show,
|
|
276
|
-
shouldShowList: show,
|
|
277
|
-
shouldPlaySound: show && (config?.playSoundInForeground?.() ?? true),
|
|
278
|
-
shouldSetBadge: true
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
});
|
|
282
|
-
if (_reactNative.Platform.OS === 'android' && next.androidChannels?.length) {
|
|
283
|
-
channelsReady = createChannels(m, next.androidChannels);
|
|
284
|
-
}
|
|
285
|
-
listenForResponses(m);
|
|
286
|
-
void drainPending(m);
|
|
287
|
-
void m.getPermissionsAsync().then(response => setState({
|
|
288
|
-
status: toPermissionStatus(response)
|
|
289
|
-
})).catch(error => _index.Logger.error('[push] permission check failed', error));
|
|
290
|
-
};
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Asks for permission, reads the native device token and registers it through
|
|
294
|
-
* `config.register`, then re-registers whenever the OS rotates the token.
|
|
295
|
-
*/
|
|
296
|
-
exports.initPush = initPush;
|
|
297
|
-
const enablePush = async () => {
|
|
298
|
-
requireConfig();
|
|
299
|
-
const mods = resolveModules();
|
|
300
|
-
if (!mods) {
|
|
301
|
-
setState({
|
|
302
|
-
status: 'unavailable'
|
|
303
|
-
});
|
|
304
|
-
return 'unavailable';
|
|
305
|
-
}
|
|
306
|
-
const m = mods.notifications;
|
|
307
|
-
|
|
308
|
-
// Android 13 shows the permission prompt only once a channel exists.
|
|
309
|
-
await channelsReady;
|
|
310
|
-
let permission = await m.getPermissionsAsync();
|
|
311
|
-
if (!permission.granted) {
|
|
312
|
-
permission = await m.requestPermissionsAsync();
|
|
313
|
-
}
|
|
314
|
-
if (!permission.granted) {
|
|
315
|
-
setState({
|
|
316
|
-
status: 'denied'
|
|
317
|
-
});
|
|
318
|
-
return 'denied';
|
|
319
|
-
}
|
|
320
|
-
const device = await toDevice(await m.getDevicePushTokenAsync(), mods.applicationId);
|
|
321
|
-
if (!device) {
|
|
322
|
-
setState({
|
|
323
|
-
status: 'unavailable'
|
|
324
|
-
});
|
|
325
|
-
return 'unavailable';
|
|
326
|
-
}
|
|
327
|
-
await requireConfig().register(device);
|
|
328
|
-
tokenSubscription?.remove();
|
|
329
|
-
tokenSubscription = m.addPushTokenListener(token => {
|
|
330
|
-
void toDevice(token, mods.applicationId).then(next => next ? requireConfig().register(next) : undefined).catch(error => _index.Logger.error('[push] re-registering a new token failed', error));
|
|
331
|
-
});
|
|
332
|
-
setState({
|
|
333
|
-
status: 'granted',
|
|
334
|
-
enabled: true
|
|
335
|
-
});
|
|
336
|
-
return 'granted';
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
/**
|
|
340
|
-
* Unregisters the device through `config.unregister` and stops following token
|
|
341
|
-
* changes. Taps on notifications already delivered still reach `onOpen`.
|
|
342
|
-
*/
|
|
343
|
-
exports.enablePush = enablePush;
|
|
344
|
-
const disablePush = async () => {
|
|
345
|
-
const current = requireConfig();
|
|
346
|
-
// Stop following token changes first, so a failed unregister cannot re-register the phone.
|
|
347
|
-
tokenSubscription?.remove();
|
|
348
|
-
tokenSubscription = null;
|
|
349
|
-
setState({
|
|
350
|
-
enabled: false
|
|
351
|
-
});
|
|
352
|
-
await current.unregister(await current.getInstallationId());
|
|
353
|
-
};
|
|
354
|
-
|
|
355
|
-
/** Sets the app icon badge; a no-op where push is unavailable or the launcher has no badge. */
|
|
356
|
-
exports.disablePush = disablePush;
|
|
357
|
-
const setBadgeCount = async count => {
|
|
358
|
-
const mods = resolveModules();
|
|
359
|
-
if (!mods) {
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
await mods.notifications.setBadgeCountAsync(count);
|
|
363
|
-
};
|
|
364
|
-
|
|
365
|
-
/**
|
|
366
|
-
* Registers the button sets a push can name by category id. Call it at every
|
|
367
|
-
* start, with the same ids on both platforms. On Android the buttons show only
|
|
368
|
-
* on notifications expo-notifications draws, such as `notifyLocal`.
|
|
369
|
-
*/
|
|
370
|
-
exports.setBadgeCount = setBadgeCount;
|
|
371
|
-
const setCategories = async categories => {
|
|
372
|
-
const mods = resolveModules();
|
|
373
|
-
if (!mods) {
|
|
374
|
-
return;
|
|
375
|
-
}
|
|
376
|
-
for (const category of categories) {
|
|
377
|
-
await mods.notifications.setNotificationCategoryAsync(category.id, toNotificationActions(category.actions));
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
|
|
381
|
-
/**
|
|
382
|
-
* Handles button taps while JavaScript is running; a plain tap still goes to
|
|
383
|
-
* `onOpen`. For taps on a killed app use `definePushActionTask` from
|
|
384
|
-
* `/push/task`, which sets this handler too. Returns a function that removes it.
|
|
385
|
-
*/
|
|
386
|
-
exports.setCategories = setCategories;
|
|
387
|
-
const onAction = handler => {
|
|
388
|
-
actionHandler = handler;
|
|
389
|
-
const mods = resolveModules();
|
|
390
|
-
if (mods) {
|
|
391
|
-
listenForResponses(mods.notifications);
|
|
392
|
-
void drainPending(mods.notifications);
|
|
393
|
-
}
|
|
394
|
-
return () => {
|
|
395
|
-
if (actionHandler === handler) {
|
|
396
|
-
actionHandler = null;
|
|
397
|
-
}
|
|
398
|
-
};
|
|
399
|
-
};
|
|
400
|
-
|
|
401
|
-
/** Shows a notification from the phone itself, for example when a button's request failed. */
|
|
402
|
-
exports.onAction = onAction;
|
|
403
|
-
const notifyLocal = async ({
|
|
404
|
-
title,
|
|
405
|
-
body,
|
|
406
|
-
data
|
|
407
|
-
}) => {
|
|
408
|
-
const mods = resolveModules();
|
|
409
|
-
if (!mods) {
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
await mods.notifications.scheduleNotificationAsync({
|
|
413
|
-
content: {
|
|
414
|
-
title,
|
|
415
|
-
body,
|
|
416
|
-
data: data ?? {}
|
|
417
|
-
},
|
|
418
|
-
trigger: null
|
|
419
|
-
});
|
|
420
|
-
};
|
|
421
|
-
exports.notifyLocal = notifyLocal;
|
|
422
|
-
const subscribe = notify => {
|
|
423
|
-
subscribers.add(notify);
|
|
424
|
-
return () => {
|
|
425
|
-
subscribers.delete(notify);
|
|
426
|
-
};
|
|
427
|
-
};
|
|
428
|
-
const getSnapshot = () => state;
|
|
429
|
-
const enable = async () => {
|
|
430
|
-
await enablePush();
|
|
431
|
-
};
|
|
432
|
-
|
|
433
|
-
/** Push status for a settings switch, re-rendering when it changes. */
|
|
434
|
-
const usePush = () => {
|
|
435
|
-
const snapshot = (0, _react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
436
|
-
return {
|
|
437
|
-
...snapshot,
|
|
438
|
-
enable,
|
|
439
|
-
disable: disablePush
|
|
440
|
-
};
|
|
441
|
-
};
|
|
442
|
-
exports.usePush = usePush;
|
|
443
|
-
//# sourceMappingURL=push.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.usePush=exports.toPushAction=exports.toNotificationActions=exports.setPushImplementation=exports.setCategories=exports.setBadgeCount=exports.routeTaskPayload=exports.resolveModules=exports.onAction=exports.notifyLocal=exports.initPush=exports.enablePush=exports.disablePush=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js");let resolved,override=null;const setPushImplementation=e=>{override=e};exports.setPushImplementation=setPushImplementation;const resolveModules=()=>{if(override)return override;if(void 0!==resolved)return resolved;try{if(require("expo").isRunningInExpoGo())return resolved=null,resolved;const e=require("expo-notifications"),t=require("expo-application");resolved={notifications:e,applicationId:t.applicationId}}catch(e){_index.Logger.warn("[push] expo-notifications is not available; push is off",e),resolved=null}return resolved};exports.resolveModules=resolveModules;let state={status:"unknown",enabled:!1};const subscribers=new Set,setState=e=>{state={...state,...e};for(const e of subscribers)e()};let config=null,channelsReady=Promise.resolve(),tokenSubscription=null,actionHandler=null,listening=!1;const pendingResponses=[],routedAt=new Map,REPEAT_WINDOW_MS=1e4,requireConfig=()=>{if(!config)throw new Error("[@webority/mobile-core] call initPush before enablePush or disablePush.");return config},toPermissionStatus=e=>e.granted?"granted":"denied"===e.status?"denied":"unknown",toStringData=e=>{const t={};for(const[n,o]of Object.entries(e??{}))null!=o&&(t[n]="object"==typeof o?JSON.stringify(o):String(o));return t},contentData=e=>{const t=e.notification.request.content;if(t.data)return toStringData(t.data);if("string"==typeof t.dataString)try{return toStringData(JSON.parse(t.dataString))}catch(e){_index.Logger.error("[push] notification data is not JSON",e)}return{}},triggerData=e=>{const t=e.notification.request.trigger,n={...t?.remoteMessage?.data??{}};for(const[e,o]of Object.entries(t?.payload??{}))"aps"===e||"body"===e&&"object"==typeof o||(n[e]=o);return toStringData(n)},responseData=e=>({...triggerData(e),...contentData(e)}),toPushAction=e=>({actionId:e.actionIdentifier,...e.userText?{userText:e.userText}:{},data:responseData(e),notificationId:e.notification.request.identifier});exports.toPushAction=toPushAction;const toNotificationActions=e=>e.map(e=>({identifier:e.id,buttonTitle:e.title,...e.textInput?{textInput:{submitButtonTitle:e.textInput.submitTitle,placeholder:e.textInput.placeholder}}:{},options:{opensAppToForeground:e.opensApp??!0,isDestructive:e.destructive??!1,isAuthenticationRequired:e.authenticationRequired??!1}}));exports.toNotificationActions=toNotificationActions;const routeResponse=async(e,t)=>{const n=`${t.notification.request.identifier}:${t.actionIdentifier}`,o=routedAt.get(n);if(void 0!==o&&Date.now()-o<1e4)return;if(t.actionIdentifier!==e.DEFAULT_ACTION_IDENTIFIER&&actionHandler){routedAt.set(n,Date.now());try{await actionHandler(toPushAction(t))}catch(e){_index.Logger.error("[push] onAction threw",e)}}else if(config){routedAt.set(n,Date.now());try{config.onOpen(responseData(t))}catch(e){_index.Logger.error("[push] onOpen threw",e)}}else pendingResponses.push(t)},drainPending=async e=>{const t=pendingResponses.splice(0);for(const n of t)await routeResponse(e,n)},listenForResponses=e=>{listening||(listening=!0,e.addNotificationResponseReceivedListener(t=>{routeResponse(e,t)}),e.getLastNotificationResponseAsync().then(async t=>(t&&await routeResponse(e,t),e.clearLastNotificationResponseAsync?.())).catch(e=>_index.Logger.error("[push] reading the launch notification failed",e)))},routeTaskPayload=async e=>{const t=resolveModules(),n=e;t&&"string"==typeof n?.actionIdentifier&&"string"==typeof n.notification?.request?.identifier&&await routeResponse(t.notifications,n)};exports.routeTaskPayload=routeTaskPayload;const createChannels=async(e,t)=>{for(const n of t)try{await e.setNotificationChannelAsync(n.id,{name:n.name,importance:"high"===n.importance?e.AndroidImportance.HIGH:e.AndroidImportance.DEFAULT})}catch(e){_index.Logger.error(`[push] creating channel ${n.id} failed`,e)}},toDevice=async(e,t)=>{const n="android"===e.type?"Fcm":"ios"===e.type?"Apns":null;if(!n||"string"!=typeof e.data)return null;if(!t)throw new Error("[@webority/mobile-core] push needs the app bundle id from expo-application.");return{installationId:await requireConfig().getInstallationId(),platform:n,token:e.data,appId:t}},initPush=e=>{const t=null===config;if(config=e,!t)return;const n=resolveModules();if(!n)return void setState({status:"unavailable"});const o=n.notifications;o.setNotificationHandler({handleNotification:async()=>{const e=config?.showInForeground?.()??!0;return{shouldShowBanner:e,shouldShowList:e,shouldPlaySound:e&&(config?.playSoundInForeground?.()??!0),shouldSetBadge:!0}}}),"android"===_reactNative.Platform.OS&&e.androidChannels?.length&&(channelsReady=createChannels(o,e.androidChannels)),listenForResponses(o),drainPending(o),o.getPermissionsAsync().then(e=>setState({status:toPermissionStatus(e)})).catch(e=>_index.Logger.error("[push] permission check failed",e))};exports.initPush=initPush;let registering=null,registeredKey=null;const registerOnce=e=>{const t=JSON.stringify(e);if(registering?.key===t)return registering.promise;const n=requireConfig().register(e).then(()=>{registeredKey=t}).finally(()=>{registering?.promise===n&&(registering=null)});return registering={key:t,promise:n},n},enablePush=async()=>{requireConfig();const e=resolveModules();if(!e)return setState({status:"unavailable"}),"unavailable";const t=e.notifications;await channelsReady;let n=await t.getPermissionsAsync();if(n.granted||(n=await t.requestPermissionsAsync()),!n.granted)return setState({status:"denied"}),"denied";const o=await toDevice(await t.getDevicePushTokenAsync(),e.applicationId);return o?(await registerOnce(o),tokenSubscription?.remove(),tokenSubscription=t.addPushTokenListener(t=>{toDevice(t,e.applicationId).then(e=>e&&JSON.stringify(e)!==registeredKey?registerOnce(e):void 0).catch(e=>_index.Logger.error("[push] re-registering a new token failed",e))}),setState({status:"granted",enabled:!0}),"granted"):(setState({status:"unavailable"}),"unavailable")};exports.enablePush=enablePush;const disablePush=async()=>{const e=requireConfig();tokenSubscription?.remove(),tokenSubscription=null,registeredKey=null,setState({enabled:!1}),await e.unregister(await e.getInstallationId())};exports.disablePush=disablePush;const setBadgeCount=async e=>{const t=resolveModules();t&&await t.notifications.setBadgeCountAsync(e)};exports.setBadgeCount=setBadgeCount;const setCategories=async e=>{const t=resolveModules();if(t)for(const n of e)await t.notifications.setNotificationCategoryAsync(n.id,toNotificationActions(n.actions))};exports.setCategories=setCategories;const onAction=e=>{actionHandler=e;const t=resolveModules();return t&&(listenForResponses(t.notifications),drainPending(t.notifications)),()=>{actionHandler===e&&(actionHandler=null)}};exports.onAction=onAction;const notifyLocal=async({title:e,body:t,data:n})=>{const o=resolveModules();o&&await o.notifications.scheduleNotificationAsync({content:{title:e,body:t,data:n??{}},trigger:null})};exports.notifyLocal=notifyLocal;const subscribe=e=>(subscribers.add(e),()=>{subscribers.delete(e)}),getSnapshot=()=>state,enable=async()=>{await enablePush()},usePush=()=>({...(0,_react.useSyncExternalStore)(subscribe,getSnapshot,getSnapshot),enable:enable,disable:disablePush});exports.usePush=usePush;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PUSH_STATUS=void 0;const PUSH_STATUS=exports.PUSH_STATUS={unknown:"unknown",granted:"granted",denied:"denied",unavailable:"unavailable"};
|
|
@@ -1,43 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.definePushActionTask = void 0;
|
|
7
|
-
var _reactNative = require("react-native");
|
|
8
|
-
var _index = require("../logger/index.js");
|
|
9
|
-
var _push = require("./push.js");
|
|
10
|
-
const PUSH_ACTION_TASK = 'webority-push-action';
|
|
11
|
-
/**
|
|
12
|
-
* Handles notification button taps in every app state, the killed app
|
|
13
|
-
* included. Call it once at module scope in the app's entry file (index.js),
|
|
14
|
-
* before the root component registers: a tap on a killed app starts the
|
|
15
|
-
* JavaScript bundle without the UI, so nothing later in the app runs.
|
|
16
|
-
*
|
|
17
|
-
* Android runs the handler from a background notification task
|
|
18
|
-
* (expo-task-manager). iOS has no such task for button taps: it launches the
|
|
19
|
-
* app in the background and the response reaches the listener this sets up.
|
|
20
|
-
* The handler's promise is awaited, so a request it makes can finish first.
|
|
21
|
-
*/
|
|
22
|
-
const definePushActionTask = handler => {
|
|
23
|
-
(0, _push.onAction)(handler);
|
|
24
|
-
const mods = (0, _push.resolveModules)();
|
|
25
|
-
if (!mods || _reactNative.Platform.OS !== 'android') {
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
/** The one place `expo-task-manager` is named. Import `/push/task` only if you use button taps. */
|
|
29
|
-
const taskManager = require('expo-task-manager');
|
|
30
|
-
taskManager.defineTask(PUSH_ACTION_TASK, async ({
|
|
31
|
-
data,
|
|
32
|
-
error
|
|
33
|
-
}) => {
|
|
34
|
-
if (error) {
|
|
35
|
-
_index.Logger.error('[push] the notification task failed', error);
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
await (0, _push.routeTaskPayload)(data);
|
|
39
|
-
});
|
|
40
|
-
void mods.notifications.registerTaskAsync(PUSH_ACTION_TASK).catch(registerError => _index.Logger.error('[push] registering the notification task failed', registerError));
|
|
41
|
-
};
|
|
42
|
-
exports.definePushActionTask = definePushActionTask;
|
|
43
|
-
//# sourceMappingURL=task.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.definePushActionTask=void 0;var _reactNative=require("react-native"),_index=require("../logger/index.js"),_push=require("./push.js");const PUSH_ACTION_TASK="webority-push-action",definePushActionTask=e=>{(0,_push.onAction)(e);const i=(0,_push.resolveModules)();if(!i||"android"!==_reactNative.Platform.OS)return;require("expo-task-manager").defineTask(PUSH_ACTION_TASK,async({data:e,error:i})=>{i?_index.Logger.error("[push] the notification task failed",i):await(0,_push.routeTaskPayload)(e)}),i.notifications.registerTaskAsync(PUSH_ACTION_TASK).catch(e=>_index.Logger.error("[push] registering the notification task failed",e))};exports.definePushActionTask=definePushActionTask;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useSecureScreen=void 0;var _react=require("react"),_reactNative=require("react-native"),_index=require("../logger/index.js");const screenCapture=()=>require("expo-screen-capture"),report=e=>r=>{_index.Logger.error(`[@webority/mobile-core] useSecureScreen could not ${e}.`,r)};let nextKey=0,appSwitcherHolders=0;const useSecureScreen=(e={})=>{const{focused:r=!0}=e,t=(0,_react.useRef)(null);null===t.current&&(nextKey+=1,t.current=`webority-secure-screen-${nextKey}`),(0,_react.useEffect)(()=>{if(!r)return;const e=t.current,c=screenCapture();c.preventScreenCaptureAsync(e).catch(report("block screen capture"));const s="ios"===_reactNative.Platform.OS;return s&&(appSwitcherHolders+=1,1===appSwitcherHolders&&c.enableAppSwitcherProtectionAsync().catch(report("hide the app switcher snapshot"))),()=>{c.allowScreenCaptureAsync(e).catch(report("release screen capture")),s&&(appSwitcherHolders-=1,0===appSwitcherHolders&&c.disableAppSwitcherProtectionAsync().catch(report("restore the app switcher snapshot")))}},[r])};exports.useSecureScreen=useSecureScreen;
|
|
@@ -1,70 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.shareFile = exports.ShareError = void 0;
|
|
7
|
-
/**
|
|
8
|
-
* Opens a downloaded file through the system share sheet, where the person picks
|
|
9
|
-
* a viewer or saves it. A separate entry point because it names expo-sharing, an
|
|
10
|
-
* optional peer: Metro resolves every require reachable from an import, so keeping
|
|
11
|
-
* it off the main barrel and off `/download` lets an app skip the package when it
|
|
12
|
-
* never opens files.
|
|
13
|
-
*
|
|
14
|
-
* The share sheet rather than `Linking.openURL`: Android 7 and later refuse a
|
|
15
|
-
* `file://` link, and a `content://` link sent through Linking carries no read
|
|
16
|
-
* grant, so the OS-open route never reached a viewer there.
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
const PREFIX = '[@webority/mobile-core]';
|
|
20
|
-
/** The one place `expo-sharing` is named, and only this subpath reaches it. */
|
|
21
|
-
const sharing = () => require('expo-sharing');
|
|
22
|
-
|
|
23
|
-
// iOS picks the apps it offers from the UTI, not the MIME type.
|
|
24
|
-
const UTIS = {
|
|
25
|
-
'application/pdf': 'com.adobe.pdf',
|
|
26
|
-
'text/plain': 'public.plain-text',
|
|
27
|
-
'text/csv': 'public.comma-separated-values-text',
|
|
28
|
-
'image/jpeg': 'public.jpeg',
|
|
29
|
-
'image/png': 'public.png'
|
|
30
|
-
};
|
|
31
|
-
class ShareError extends Error {
|
|
32
|
-
constructor(code, message) {
|
|
33
|
-
super(`${PREFIX} ${message}`);
|
|
34
|
-
this.name = 'ShareError';
|
|
35
|
-
this.code = code;
|
|
36
|
-
// Babel's class transform can drop the prototype link, which makes
|
|
37
|
-
// `instanceof ShareError` false in the transpiled build.
|
|
38
|
-
Object.setPrototypeOf(this, ShareError.prototype);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
exports.ShareError = ShareError;
|
|
42
|
-
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Hands a local file (the `path` `downloadFile` returns) to the share sheet.
|
|
46
|
-
* A bare path is given a `file://` scheme. Rejects with `ShareError`: `unavailable`
|
|
47
|
-
* when the device has no share sheet, `failed` when the sheet could not open the file.
|
|
48
|
-
*/
|
|
49
|
-
const shareFile = async (path, options = {}) => {
|
|
50
|
-
const url = HAS_SCHEME.test(path) ? path : `file://${path}`;
|
|
51
|
-
const m = sharing();
|
|
52
|
-
if (!(await m.isAvailableAsync())) {
|
|
53
|
-
throw new ShareError('unavailable', `Sharing is not available on this device, so ${url} cannot be opened.`);
|
|
54
|
-
}
|
|
55
|
-
const {
|
|
56
|
-
mimeType,
|
|
57
|
-
dialogTitle
|
|
58
|
-
} = options;
|
|
59
|
-
try {
|
|
60
|
-
await m.shareAsync(url, {
|
|
61
|
-
mimeType,
|
|
62
|
-
UTI: mimeType ? UTIS[mimeType] : undefined,
|
|
63
|
-
dialogTitle
|
|
64
|
-
});
|
|
65
|
-
} catch (error) {
|
|
66
|
-
throw new ShareError('failed', `${url}${mimeType ? ` (${mimeType})` : ''} could not be shared: ${error instanceof Error ? error.message : String(error)}`);
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
exports.shareFile = shareFile;
|
|
70
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shareFile=exports.ShareError=void 0;const PREFIX="[@webority/mobile-core]",sharing=()=>require("expo-sharing"),UTIS={"application/pdf":"com.adobe.pdf","text/plain":"public.plain-text","text/csv":"public.comma-separated-values-text","image/jpeg":"public.jpeg","image/png":"public.png"};class ShareError extends Error{constructor(e,r){super(`${PREFIX} ${r}`),this.name="ShareError",this.code=e,Object.setPrototypeOf(this,ShareError.prototype)}}exports.ShareError=ShareError;const HAS_SCHEME=/^[a-z][a-z0-9+.-]*:/i,shareFile=async(e,r={})=>{const a=HAS_SCHEME.test(e)?e:`file://${e}`,t=sharing();if(!await t.isAvailableAsync())throw new ShareError("unavailable",`Sharing is not available on this device, so ${a} cannot be opened.`);const{mimeType:o,dialogTitle:i}=r;try{await t.shareAsync(a,{mimeType:o,UTI:o?UTIS[o]:void 0,dialogTitle:i})}catch(e){throw new ShareError("failed",`${a}${o?` (${o})`:""} could not be shared: ${e instanceof Error?e.message:String(e)}`)}};exports.shareFile=shareFile;
|
|
@@ -1,91 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.setSmsRetrieverImplementation = exports.SmsRetriever = void 0;
|
|
7
|
-
var _reactNative = require("react-native");
|
|
8
|
-
var _index = require("../logger/index.js");
|
|
9
|
-
const OTP_EVENT = 'WeborityMobileCoreSmsRetrieved';
|
|
10
|
-
const ERROR_EVENT = 'WeborityMobileCoreSmsRetrieverError';
|
|
11
|
-
let backend = null;
|
|
12
|
-
|
|
13
|
-
/** Test-only injection point. Pass `null` to reset to the native module. */
|
|
14
|
-
const setSmsRetrieverImplementation = impl => {
|
|
15
|
-
backend = impl;
|
|
16
|
-
};
|
|
17
|
-
exports.setSmsRetrieverImplementation = setSmsRetrieverImplementation;
|
|
18
|
-
let nativeModule;
|
|
19
|
-
const resolveNativeModule = () => {
|
|
20
|
-
if (nativeModule !== undefined) {
|
|
21
|
-
return nativeModule;
|
|
22
|
-
}
|
|
23
|
-
if (_reactNative.Platform.OS !== 'android') {
|
|
24
|
-
nativeModule = null;
|
|
25
|
-
return null;
|
|
26
|
-
}
|
|
27
|
-
try {
|
|
28
|
-
nativeModule = require('../specs/NativeSmsRetriever').default ?? null;
|
|
29
|
-
} catch (error) {
|
|
30
|
-
_index.Logger.warn('[smsRetriever] native module not available', error);
|
|
31
|
-
nativeModule = null;
|
|
32
|
-
}
|
|
33
|
-
return nativeModule ?? null;
|
|
34
|
-
};
|
|
35
|
-
const defaultBackend = {
|
|
36
|
-
getAppHash: async () => {
|
|
37
|
-
const m = resolveNativeModule();
|
|
38
|
-
if (!m) {
|
|
39
|
-
throw new Error('[smsRetriever] getAppHash: native module unavailable (Android only).');
|
|
40
|
-
}
|
|
41
|
-
return m.getAppHash();
|
|
42
|
-
},
|
|
43
|
-
startListening: (onMessage, onError) => {
|
|
44
|
-
const m = resolveNativeModule();
|
|
45
|
-
if (!m) {
|
|
46
|
-
onError?.({
|
|
47
|
-
type: 'SERVICE_UNAVAILABLE',
|
|
48
|
-
message: 'SMS Retriever is Android-only, or the native module is not linked.'
|
|
49
|
-
});
|
|
50
|
-
return {
|
|
51
|
-
remove: () => undefined
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
const messageSub = _reactNative.DeviceEventEmitter.addListener(OTP_EVENT, payload => onMessage(payload.message));
|
|
55
|
-
const errorSub = onError ? _reactNative.DeviceEventEmitter.addListener(ERROR_EVENT, payload => onError(payload)) : null;
|
|
56
|
-
try {
|
|
57
|
-
m.startSMSListener();
|
|
58
|
-
} catch (error) {
|
|
59
|
-
_index.Logger.error('[smsRetriever] startSMSListener failed', error);
|
|
60
|
-
}
|
|
61
|
-
return {
|
|
62
|
-
remove: () => {
|
|
63
|
-
messageSub.remove();
|
|
64
|
-
errorSub?.remove();
|
|
65
|
-
try {
|
|
66
|
-
m.stopSMSListener();
|
|
67
|
-
} catch (error) {
|
|
68
|
-
_index.Logger.error('[smsRetriever] stopSMSListener failed', error);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* The Play Services SMS Retriever API — auto-reads an incoming OTP SMS with
|
|
77
|
-
* no SMS permission, matched by an 11-character app-signature hash
|
|
78
|
-
* (`getAppHash`) the backend appends to the message. Android only; every
|
|
79
|
-
* method is safe to call on iOS and resolves/reports unavailable rather than
|
|
80
|
-
* throwing, so a caller doesn't need a platform check at every call site.
|
|
81
|
-
*
|
|
82
|
-
* OTP extraction is left to the caller — `onMessage` receives the raw SMS
|
|
83
|
-
* text, since the expected OTP format (digit count, prefix) is a backend
|
|
84
|
-
* concern, not this module's.
|
|
85
|
-
*/
|
|
86
|
-
const SmsRetriever = exports.SmsRetriever = {
|
|
87
|
-
isAvailable: () => resolveNativeModule() !== null,
|
|
88
|
-
getAppHash: () => (backend ?? defaultBackend).getAppHash(),
|
|
89
|
-
startListening: (onMessage, onError) => (backend ?? defaultBackend).startListening(onMessage, onError)
|
|
90
|
-
};
|
|
91
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.setSmsRetrieverImplementation=exports.SmsRetriever=void 0;var _reactNative=require("react-native"),_index=require("../logger/index.js");const OTP_EVENT="WeborityMobileCoreSmsRetrieved",ERROR_EVENT="WeborityMobileCoreSmsRetrieverError";let backend=null;const setSmsRetrieverImplementation=e=>{backend=e};let nativeModule;exports.setSmsRetrieverImplementation=setSmsRetrieverImplementation;const resolveNativeModule=()=>{if(void 0!==nativeModule)return nativeModule;if("android"!==_reactNative.Platform.OS)return nativeModule=null,null;try{nativeModule=require("../specs/NativeSmsRetriever").default??null}catch(e){_index.Logger.warn("[smsRetriever] native module not available",e),nativeModule=null}return nativeModule??null},defaultBackend={getAppHash:async()=>{const e=resolveNativeModule();if(!e)throw new Error("[smsRetriever] getAppHash: native module unavailable (Android only).");return e.getAppHash()},startListening:(e,t)=>{const r=resolveNativeModule();if(!r)return t?.({type:"SERVICE_UNAVAILABLE",message:"SMS Retriever is Android-only, or the native module is not linked."}),{remove:()=>{}};const i=_reactNative.DeviceEventEmitter.addListener(OTP_EVENT,t=>e(t.message)),n=t?_reactNative.DeviceEventEmitter.addListener(ERROR_EVENT,e=>t(e)):null;try{r.startSMSListener()}catch(e){_index.Logger.error("[smsRetriever] startSMSListener failed",e)}return{remove:()=>{i.remove(),n?.remove();try{r.stopSMSListener()}catch(e){_index.Logger.error("[smsRetriever] stopSMSListener failed",e)}}}}},SmsRetriever=exports.SmsRetriever={isAvailable:()=>null!==resolveNativeModule(),getAppHash:()=>(backend??defaultBackend).getAppHash(),startListening:(e,t)=>(backend??defaultBackend).startListening(e,t)};
|