@webority/mobile-core 0.0.29 → 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.
Files changed (139) hide show
  1. package/lib/commonjs/api/baseUrl.js +1 -34
  2. package/lib/commonjs/api/curl.js +1 -109
  3. package/lib/commonjs/api/multipart.js +1 -21
  4. package/lib/commonjs/api/publicClient.js +1 -79
  5. package/lib/commonjs/api/responseBodyText.js +1 -0
  6. package/lib/commonjs/api/retry.js +1 -91
  7. package/lib/commonjs/api/tokenRefresh.js +1 -205
  8. package/lib/commonjs/api/userClient.js +1 -265
  9. package/lib/commonjs/auth/authStore.js +1 -265
  10. package/lib/commonjs/auth/index.js +1 -44
  11. package/lib/commonjs/auth/jwt.js +1 -112
  12. package/lib/commonjs/config/index.js +1 -72
  13. package/lib/commonjs/deepLink/index.js +1 -286
  14. package/lib/commonjs/download/adapters/expoFs.js +1 -69
  15. package/lib/commonjs/download/adapters/shared.js +1 -13
  16. package/lib/commonjs/download/index.js +1 -250
  17. package/lib/commonjs/formatters/currency.js +1 -70
  18. package/lib/commonjs/formatters/date.js +1 -167
  19. package/lib/commonjs/formatters/dateMath.js +1 -311
  20. package/lib/commonjs/formatters/index.js +1 -246
  21. package/lib/commonjs/formatters/initials.js +1 -32
  22. package/lib/commonjs/formatters/intlCache.js +1 -37
  23. package/lib/commonjs/formatters/number.js +1 -89
  24. package/lib/commonjs/formatters/phone.js +1 -369
  25. package/lib/commonjs/formatters/windowsToIanaTable.js +1 -164
  26. package/lib/commonjs/geolocation/adapters/expoLocation.js +1 -126
  27. package/lib/commonjs/geolocation/index.js +1 -355
  28. package/lib/commonjs/index.js +1 -644
  29. package/lib/commonjs/initSDK.js +1 -66
  30. package/lib/commonjs/initUserAuth.js +1 -37
  31. package/lib/commonjs/logger/crashlytics.js +1 -0
  32. package/lib/commonjs/logger/index.js +1 -301
  33. package/lib/commonjs/logger/redact.js +1 -50
  34. package/lib/commonjs/network/index.js +1 -31
  35. package/lib/commonjs/network/networkStatus.js +1 -171
  36. package/lib/commonjs/permissions/calendar.js +1 -14
  37. package/lib/commonjs/permissions/camera.js +1 -14
  38. package/lib/commonjs/permissions/contacts.js +1 -10
  39. package/lib/commonjs/permissions/index.js +1 -133
  40. package/lib/commonjs/permissions/location.js +1 -14
  41. package/lib/commonjs/permissions/mediaLibrary.js +1 -10
  42. package/lib/commonjs/permissions/notifications.js +1 -10
  43. package/lib/commonjs/permissions/photos.js +1 -14
  44. package/lib/commonjs/phone/countries.js +1 -265
  45. package/lib/commonjs/push/index.js +1 -61
  46. package/lib/commonjs/push/push.js +1 -468
  47. package/lib/commonjs/push/status.js +1 -0
  48. package/lib/commonjs/push/task.js +1 -43
  49. package/lib/commonjs/secureScreen/index.js +1 -0
  50. package/lib/commonjs/share/index.js +1 -70
  51. package/lib/commonjs/smsRetriever/index.js +1 -91
  52. package/lib/commonjs/specs/NativeSmsRetriever.js +1 -15
  53. package/lib/commonjs/sqlite/adapters/expo.js +1 -53
  54. package/lib/commonjs/sqlite/index.js +1 -604
  55. package/lib/commonjs/storage/index.js +1 -214
  56. package/lib/commonjs/types/axios.js +1 -4
  57. package/lib/commonjs/types/globals.d.js +1 -6
  58. package/lib/commonjs/utils/base64.js +1 -24
  59. package/lib/commonjs/utils/imageCompression.js +1 -389
  60. package/lib/commonjs/utils/index.js +1 -19
  61. package/lib/commonjs/validators/index.js +1 -227
  62. package/lib/commonjs/versionCheck/index.js +1 -419
  63. package/lib/module/api/baseUrl.js +1 -30
  64. package/lib/module/api/curl.js +1 -104
  65. package/lib/module/api/multipart.js +1 -16
  66. package/lib/module/api/publicClient.js +1 -75
  67. package/lib/module/api/responseBodyText.js +1 -0
  68. package/lib/module/api/retry.js +1 -85
  69. package/lib/module/api/tokenRefresh.js +1 -192
  70. package/lib/module/api/userClient.js +1 -243
  71. package/lib/module/auth/authStore.js +1 -257
  72. package/lib/module/auth/index.js +1 -5
  73. package/lib/module/auth/jwt.js +1 -106
  74. package/lib/module/config/index.js +1 -64
  75. package/lib/module/deepLink/index.js +1 -280
  76. package/lib/module/download/adapters/expoFs.js +1 -64
  77. package/lib/module/download/adapters/shared.js +1 -8
  78. package/lib/module/download/index.js +1 -242
  79. package/lib/module/formatters/currency.js +1 -65
  80. package/lib/module/formatters/date.js +1 -159
  81. package/lib/module/formatters/dateMath.js +1 -295
  82. package/lib/module/formatters/index.js +1 -9
  83. package/lib/module/formatters/initials.js +1 -27
  84. package/lib/module/formatters/intlCache.js +1 -30
  85. package/lib/module/formatters/number.js +1 -82
  86. package/lib/module/formatters/phone.js +1 -302
  87. package/lib/module/formatters/windowsToIanaTable.js +1 -160
  88. package/lib/module/geolocation/adapters/expoLocation.js +1 -121
  89. package/lib/module/geolocation/index.js +1 -347
  90. package/lib/module/index.js +1 -57
  91. package/lib/module/initSDK.js +1 -61
  92. package/lib/module/initUserAuth.js +1 -33
  93. package/lib/module/logger/crashlytics.js +1 -0
  94. package/lib/module/logger/index.js +1 -295
  95. package/lib/module/logger/redact.js +1 -44
  96. package/lib/module/network/index.js +1 -4
  97. package/lib/module/network/networkStatus.js +1 -161
  98. package/lib/module/permissions/calendar.js +1 -15
  99. package/lib/module/permissions/camera.js +1 -15
  100. package/lib/module/permissions/contacts.js +1 -11
  101. package/lib/module/permissions/index.js +1 -128
  102. package/lib/module/permissions/location.js +1 -15
  103. package/lib/module/permissions/mediaLibrary.js +1 -11
  104. package/lib/module/permissions/notifications.js +1 -11
  105. package/lib/module/permissions/photos.js +1 -15
  106. package/lib/module/phone/countries.js +1 -261
  107. package/lib/module/push/index.js +1 -4
  108. package/lib/module/push/push.js +1 -452
  109. package/lib/module/push/status.js +1 -0
  110. package/lib/module/push/task.js +1 -38
  111. package/lib/module/secureScreen/index.js +1 -0
  112. package/lib/module/share/index.js +1 -64
  113. package/lib/module/smsRetriever/index.js +1 -86
  114. package/lib/module/specs/NativeSmsRetriever.js +1 -13
  115. package/lib/module/sqlite/adapters/expo.js +1 -48
  116. package/lib/module/sqlite/index.js +1 -594
  117. package/lib/module/storage/index.js +1 -208
  118. package/lib/module/types/axios.js +1 -4
  119. package/lib/module/types/globals.d.js +1 -10
  120. package/lib/module/utils/base64.js +1 -19
  121. package/lib/module/utils/imageCompression.js +1 -383
  122. package/lib/module/utils/index.js +1 -4
  123. package/lib/module/validators/index.js +1 -205
  124. package/lib/module/versionCheck/index.js +1 -413
  125. package/lib/typescript/commonjs/api/responseBodyText.d.ts +6 -0
  126. package/lib/typescript/commonjs/index.d.ts +5 -0
  127. package/lib/typescript/commonjs/logger/crashlytics.d.ts +31 -0
  128. package/lib/typescript/commonjs/push/index.d.ts +3 -1
  129. package/lib/typescript/commonjs/push/push.d.ts +1 -1
  130. package/lib/typescript/commonjs/push/status.d.ts +9 -0
  131. package/lib/typescript/commonjs/secureScreen/index.d.ts +25 -0
  132. package/lib/typescript/module/api/responseBodyText.d.ts +6 -0
  133. package/lib/typescript/module/index.d.ts +5 -0
  134. package/lib/typescript/module/logger/crashlytics.d.ts +31 -0
  135. package/lib/typescript/module/push/index.d.ts +3 -1
  136. package/lib/typescript/module/push/push.d.ts +1 -1
  137. package/lib/typescript/module/push/status.d.ts +9 -0
  138. package/lib/typescript/module/secureScreen/index.d.ts +25 -0
  139. package/package.json +23 -4
@@ -1,468 +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 contentData = 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
-
132
- /**
133
- * expo-notifications fills iOS `content.data` only from a `body` object, but our
134
- * servers send raw APNs with the app's keys at the top level beside `aps`.
135
- */
136
- const triggerData = response => {
137
- const trigger = response.notification.request.trigger;
138
- const extra = {
139
- ...(trigger?.remoteMessage?.data ?? {})
140
- };
141
- for (const [key, value] of Object.entries(trigger?.payload ?? {})) {
142
- // A `body` object is what expo already turned into content.data.
143
- if (key === 'aps' || key === 'body' && typeof value === 'object') {
144
- continue;
145
- }
146
- extra[key] = value;
147
- }
148
- return toStringData(extra);
149
- };
150
-
151
- /** The push's own data merged over the raw remote payload's keys, so content.data wins a conflict. */
152
- const responseData = response => ({
153
- ...triggerData(response),
154
- ...contentData(response)
155
- });
156
- const toPushAction = response => ({
157
- actionId: response.actionIdentifier,
158
- ...(response.userText ? {
159
- userText: response.userText
160
- } : {}),
161
- data: responseData(response),
162
- notificationId: response.notification.request.identifier
163
- });
164
- exports.toPushAction = toPushAction;
165
- const toNotificationActions = actions => actions.map(action => ({
166
- identifier: action.id,
167
- buttonTitle: action.title,
168
- ...(action.textInput ? {
169
- textInput: {
170
- submitButtonTitle: action.textInput.submitTitle,
171
- placeholder: action.textInput.placeholder
172
- }
173
- } : {}),
174
- options: {
175
- opensAppToForeground: action.opensApp ?? true,
176
- isDestructive: action.destructive ?? false,
177
- isAuthenticationRequired: action.authenticationRequired ?? false
178
- }
179
- }));
180
-
181
- /**
182
- * Sends a button tap to the action handler and a plain tap to `onOpen`. A
183
- * button tap with no action handler opens like a plain tap. Resolves once the
184
- * handler has finished, so a background task stays alive for its request.
185
- */
186
- exports.toNotificationActions = toNotificationActions;
187
- const routeResponse = async (m, response) => {
188
- const key = `${response.notification.request.identifier}:${response.actionIdentifier}`;
189
- const last = routedAt.get(key);
190
- if (last !== undefined && Date.now() - last < REPEAT_WINDOW_MS) {
191
- return;
192
- }
193
- const isAction = response.actionIdentifier !== m.DEFAULT_ACTION_IDENTIFIER;
194
- if (isAction && actionHandler) {
195
- routedAt.set(key, Date.now());
196
- try {
197
- await actionHandler(toPushAction(response));
198
- } catch (error) {
199
- _index.Logger.error('[push] onAction threw', error);
200
- }
201
- return;
202
- }
203
- if (!config) {
204
- pendingResponses.push(response);
205
- return;
206
- }
207
- routedAt.set(key, Date.now());
208
- try {
209
- config.onOpen(responseData(response));
210
- } catch (error) {
211
- _index.Logger.error('[push] onOpen threw', error);
212
- }
213
- };
214
- const drainPending = async m => {
215
- const queued = pendingResponses.splice(0);
216
- for (const response of queued) {
217
- await routeResponse(m, response);
218
- }
219
- };
220
-
221
- /** Follows taps and button taps, including the one that launched the app. Wired once per process. */
222
- const listenForResponses = m => {
223
- if (listening) {
224
- return;
225
- }
226
- listening = true;
227
- m.addNotificationResponseReceivedListener(response => {
228
- void routeResponse(m, response);
229
- });
230
- void m.getLastNotificationResponseAsync().then(async response => {
231
- if (response) {
232
- await routeResponse(m, response);
233
- }
234
- return m.clearLastNotificationResponseAsync?.();
235
- }).catch(error => _index.Logger.error('[push] reading the launch notification failed', error));
236
- };
237
-
238
- /** The payload of the background notification task: routes button taps, ignores received pushes. */
239
- const routeTaskPayload = async payload => {
240
- const mods = resolveModules();
241
- const response = payload;
242
- if (!mods || typeof response?.actionIdentifier !== 'string' || typeof response.notification?.request?.identifier !== 'string') {
243
- return;
244
- }
245
- await routeResponse(mods.notifications, response);
246
- };
247
- exports.routeTaskPayload = routeTaskPayload;
248
- const createChannels = async (m, channels) => {
249
- for (const channel of channels) {
250
- try {
251
- await m.setNotificationChannelAsync(channel.id, {
252
- name: channel.name,
253
- importance: channel.importance === 'high' ? m.AndroidImportance.HIGH : m.AndroidImportance.DEFAULT
254
- });
255
- } catch (error) {
256
- _index.Logger.error(`[push] creating channel ${channel.id} failed`, error);
257
- }
258
- }
259
- };
260
- const toDevice = async (token, applicationId) => {
261
- const platform = token.type === 'android' ? 'Fcm' : token.type === 'ios' ? 'Apns' : null;
262
- if (!platform || typeof token.data !== 'string') {
263
- return null;
264
- }
265
- if (!applicationId) {
266
- throw new Error('[@webority/mobile-core] push needs the app bundle id from expo-application.');
267
- }
268
- const installationId = await requireConfig().getInstallationId();
269
- return {
270
- installationId,
271
- platform,
272
- token: token.data,
273
- appId: applicationId
274
- };
275
- };
276
-
277
- /**
278
- * Wires push at startup: the foreground handler, Android channels, and tap
279
- * handling, including the tap that launched the app. Calling it again only
280
- * replaces the config.
281
- */
282
- const initPush = next => {
283
- const first = config === null;
284
- config = next;
285
- if (!first) {
286
- return;
287
- }
288
- const mods = resolveModules();
289
- if (!mods) {
290
- setState({
291
- status: 'unavailable'
292
- });
293
- return;
294
- }
295
- const m = mods.notifications;
296
- m.setNotificationHandler({
297
- handleNotification: async () => {
298
- const show = config?.showInForeground?.() ?? true;
299
- return {
300
- shouldShowBanner: show,
301
- shouldShowList: show,
302
- shouldPlaySound: show && (config?.playSoundInForeground?.() ?? true),
303
- shouldSetBadge: true
304
- };
305
- }
306
- });
307
- if (_reactNative.Platform.OS === 'android' && next.androidChannels?.length) {
308
- channelsReady = createChannels(m, next.androidChannels);
309
- }
310
- listenForResponses(m);
311
- void drainPending(m);
312
- void m.getPermissionsAsync().then(response => setState({
313
- status: toPermissionStatus(response)
314
- })).catch(error => _index.Logger.error('[push] permission check failed', error));
315
- };
316
-
317
- /**
318
- * Asks for permission, reads the native device token and registers it through
319
- * `config.register`, then re-registers whenever the OS rotates the token.
320
- */
321
- exports.initPush = initPush;
322
- const enablePush = async () => {
323
- requireConfig();
324
- const mods = resolveModules();
325
- if (!mods) {
326
- setState({
327
- status: 'unavailable'
328
- });
329
- return 'unavailable';
330
- }
331
- const m = mods.notifications;
332
-
333
- // Android 13 shows the permission prompt only once a channel exists.
334
- await channelsReady;
335
- let permission = await m.getPermissionsAsync();
336
- if (!permission.granted) {
337
- permission = await m.requestPermissionsAsync();
338
- }
339
- if (!permission.granted) {
340
- setState({
341
- status: 'denied'
342
- });
343
- return 'denied';
344
- }
345
- const device = await toDevice(await m.getDevicePushTokenAsync(), mods.applicationId);
346
- if (!device) {
347
- setState({
348
- status: 'unavailable'
349
- });
350
- return 'unavailable';
351
- }
352
- await requireConfig().register(device);
353
- tokenSubscription?.remove();
354
- tokenSubscription = m.addPushTokenListener(token => {
355
- 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));
356
- });
357
- setState({
358
- status: 'granted',
359
- enabled: true
360
- });
361
- return 'granted';
362
- };
363
-
364
- /**
365
- * Unregisters the device through `config.unregister` and stops following token
366
- * changes. Taps on notifications already delivered still reach `onOpen`.
367
- */
368
- exports.enablePush = enablePush;
369
- const disablePush = async () => {
370
- const current = requireConfig();
371
- // Stop following token changes first, so a failed unregister cannot re-register the phone.
372
- tokenSubscription?.remove();
373
- tokenSubscription = null;
374
- setState({
375
- enabled: false
376
- });
377
- await current.unregister(await current.getInstallationId());
378
- };
379
-
380
- /** Sets the app icon badge; a no-op where push is unavailable or the launcher has no badge. */
381
- exports.disablePush = disablePush;
382
- const setBadgeCount = async count => {
383
- const mods = resolveModules();
384
- if (!mods) {
385
- return;
386
- }
387
- await mods.notifications.setBadgeCountAsync(count);
388
- };
389
-
390
- /**
391
- * Registers the button sets a push can name by category id. Call it at every
392
- * start, with the same ids on both platforms. On Android the buttons show only
393
- * on notifications expo-notifications draws, such as `notifyLocal`.
394
- */
395
- exports.setBadgeCount = setBadgeCount;
396
- const setCategories = async categories => {
397
- const mods = resolveModules();
398
- if (!mods) {
399
- return;
400
- }
401
- for (const category of categories) {
402
- await mods.notifications.setNotificationCategoryAsync(category.id, toNotificationActions(category.actions));
403
- }
404
- };
405
-
406
- /**
407
- * Handles button taps while JavaScript is running; a plain tap still goes to
408
- * `onOpen`. For taps on a killed app use `definePushActionTask` from
409
- * `/push/task`, which sets this handler too. Returns a function that removes it.
410
- */
411
- exports.setCategories = setCategories;
412
- const onAction = handler => {
413
- actionHandler = handler;
414
- const mods = resolveModules();
415
- if (mods) {
416
- listenForResponses(mods.notifications);
417
- void drainPending(mods.notifications);
418
- }
419
- return () => {
420
- if (actionHandler === handler) {
421
- actionHandler = null;
422
- }
423
- };
424
- };
425
-
426
- /** Shows a notification from the phone itself, for example when a button's request failed. */
427
- exports.onAction = onAction;
428
- const notifyLocal = async ({
429
- title,
430
- body,
431
- data
432
- }) => {
433
- const mods = resolveModules();
434
- if (!mods) {
435
- return;
436
- }
437
- await mods.notifications.scheduleNotificationAsync({
438
- content: {
439
- title,
440
- body,
441
- data: data ?? {}
442
- },
443
- trigger: null
444
- });
445
- };
446
- exports.notifyLocal = notifyLocal;
447
- const subscribe = notify => {
448
- subscribers.add(notify);
449
- return () => {
450
- subscribers.delete(notify);
451
- };
452
- };
453
- const getSnapshot = () => state;
454
- const enable = async () => {
455
- await enablePush();
456
- };
457
-
458
- /** Push status for a settings switch, re-rendering when it changes. */
459
- const usePush = () => {
460
- const snapshot = (0, _react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
461
- return {
462
- ...snapshot,
463
- enable,
464
- disable: disablePush
465
- };
466
- };
467
- exports.usePush = usePush;
468
- //# 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;