@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,126 +1 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.adaptExpoLocation = void 0;
7
- /**
8
- * The slice of expo-location this adapter uses. Verified against 57.0.14.
9
- *
10
- * The REQUIRE lives in the entry point beside this file, never here.
11
- */
12
-
13
- /**
14
- * expo-location's Accuracy enum is numeric (`Balanced = 3`, `Highest = 5`,
15
- * verified in Location.types.d.ts). The numbers are inlined rather than
16
- * imported so this file names no expo module and stays bundlable by an app
17
- * without expo installed.
18
- */
19
- const ACCURACY_BALANCED = 3;
20
- const ACCURACY_HIGHEST = 5;
21
- const toExpoOptions = options => {
22
- const expo = {
23
- accuracy: options?.enableHighAccuracy ? ACCURACY_HIGHEST : ACCURACY_BALANCED
24
- };
25
- if (typeof options?.distanceFilter === 'number') {
26
- expo.distanceInterval = options.distanceFilter;
27
- }
28
- return expo;
29
- };
30
-
31
- /**
32
- * expo-location rejects with an Error; the seam expects the W3C-style numeric
33
- * codes the RN geolocation modules use, which the library then maps to its own
34
- * GeolocationError kinds. Classifying here rather than passing the raw Error
35
- * through is what makes an expo-backed app produce the same `permission-denied`
36
- * / `services-disabled` / `timeout` values as a NetInfo-backed one — which is
37
- * the whole point of having a seam.
38
- */
39
- const PERMISSION_PATTERN = /permission|denied|not (been )?granted|authoriz/i;
40
- const SERVICES_PATTERN = /location services|provider|disabled|switched off|turned off/i;
41
- const TIMEOUT_PATTERN = /time ?d? ?out|timeout/i;
42
- const toNativeError = raw => {
43
- const message = raw instanceof Error ? raw.message : String(raw);
44
- if (PERMISSION_PATTERN.test(message)) {
45
- return {
46
- code: 1,
47
- message
48
- };
49
- }
50
- if (TIMEOUT_PATTERN.test(message)) {
51
- return {
52
- code: 3,
53
- message
54
- };
55
- }
56
- // Code 2 covers both "services off" and "no fix". The library separates them
57
- // by reading the message, so the message must travel intact — and where expo
58
- // does not say "location services", the wording is normalised so it can.
59
- if (SERVICES_PATTERN.test(message)) {
60
- return {
61
- code: 2,
62
- message
63
- };
64
- }
65
- return {
66
- code: 2,
67
- message
68
- };
69
- };
70
- const toNativePosition = location => ({
71
- coords: {
72
- latitude: location.coords?.latitude ?? null,
73
- longitude: location.coords?.longitude ?? null,
74
- accuracy: location.coords?.accuracy ?? null,
75
- altitude: location.coords?.altitude ?? null,
76
- heading: location.coords?.heading ?? null,
77
- speed: location.coords?.speed ?? null
78
- },
79
- timestamp: location.timestamp ?? null
80
- });
81
-
82
- /**
83
- * Adapts expo-location to the library's geolocation seam.
84
- *
85
- * The interesting half is `watchPosition`. The seam must hand back a numeric
86
- * watch id SYNCHRONOUSLY, while `watchPositionAsync` only resolves its
87
- * subscription later. So the adapter mints its own id immediately and stores
88
- * the subscription against it on arrival. `clearWatch` called during that
89
- * window records the id as cancelled, and the subscription is removed the
90
- * moment it lands — without that, a screen that unmounts before the watch
91
- * starts leaks a live GPS listener for the rest of the session, which is a
92
- * battery drain nobody would attribute to this code.
93
- */
94
- const adaptExpoLocation = mod => {
95
- const subscriptions = new Map();
96
- let nextWatchId = 1;
97
- return {
98
- getCurrentPosition: (onSuccess, onError, options) => {
99
- mod.getCurrentPositionAsync(toExpoOptions(options)).then(location => onSuccess(toNativePosition(location))).catch(error => onError?.(toNativeError(error)));
100
- },
101
- watchPosition: (onSuccess, onError, options) => {
102
- const watchId = nextWatchId++;
103
- subscriptions.set(watchId, null);
104
- mod.watchPositionAsync(toExpoOptions(options), location => onSuccess(toNativePosition(location))).then(subscription => {
105
- if (!subscriptions.has(watchId)) {
106
- // clearWatch already ran. Remove immediately rather than storing a
107
- // subscription nothing will ever clear.
108
- subscription.remove();
109
- return;
110
- }
111
- subscriptions.set(watchId, subscription);
112
- }).catch(error => {
113
- subscriptions.delete(watchId);
114
- onError?.(toNativeError(error));
115
- });
116
- return watchId;
117
- },
118
- clearWatch: watchId => {
119
- const subscription = subscriptions.get(watchId);
120
- subscriptions.delete(watchId);
121
- subscription?.remove();
122
- }
123
- };
124
- };
125
- exports.adaptExpoLocation = adaptExpoLocation;
126
- //# sourceMappingURL=expoLocation.js.map
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adaptExpoLocation=void 0;const ACCURACY_BALANCED=3,ACCURACY_HIGHEST=5,toExpoOptions=t=>{const e={accuracy:t?.enableHighAccuracy?5:3};return"number"==typeof t?.distanceFilter&&(e.distanceInterval=t.distanceFilter),e},PERMISSION_PATTERN=/permission|denied|not (been )?granted|authoriz/i,SERVICES_PATTERN=/location services|provider|disabled|switched off|turned off/i,TIMEOUT_PATTERN=/time ?d? ?out|timeout/i,toNativeError=t=>{const e=t instanceof Error?t.message:String(t);return PERMISSION_PATTERN.test(e)?{code:1,message:e}:TIMEOUT_PATTERN.test(e)?{code:3,message:e}:(SERVICES_PATTERN.test(e),{code:2,message:e})},toNativePosition=t=>({coords:{latitude:t.coords?.latitude??null,longitude:t.coords?.longitude??null,accuracy:t.coords?.accuracy??null,altitude:t.coords?.altitude??null,heading:t.coords?.heading??null,speed:t.coords?.speed??null},timestamp:t.timestamp??null}),adaptExpoLocation=t=>{const e=new Map;let o=1;return{getCurrentPosition:(e,o,i)=>{t.getCurrentPositionAsync(toExpoOptions(i)).then(t=>e(toNativePosition(t))).catch(t=>o?.(toNativeError(t)))},watchPosition:(i,n,s)=>{const a=o++;return e.set(a,null),t.watchPositionAsync(toExpoOptions(s),t=>i(toNativePosition(t))).then(t=>{e.has(a)?e.set(a,t):t.remove()}).catch(t=>{e.delete(a),n?.(toNativeError(t))}),a},clearWatch:t=>{const o=e.get(t);e.delete(t),o?.remove()}}};exports.adaptExpoLocation=adaptExpoLocation;
@@ -1,355 +1 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.useCurrentPosition = exports.setGeolocationImplementation = exports.GeolocationError = exports.Geolocation = void 0;
7
- var ExpoLocation = _interopRequireWildcard(require("expo-location"));
8
- var _react = require("react");
9
- var _index = require("../logger/index.js");
10
- var _index2 = require("../permissions/index.js");
11
- require("../permissions/location.js");
12
- var _expoLocation2 = require("./adapters/expoLocation.js");
13
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
14
- // expo-location is a REQUIRED peer (unlike the other Expo permission
15
- // packages, which are optional and registered only when an app opts in by
16
- // importing their own entry point) — anything that reaches this module
17
- // already forces Metro to resolve expo-location, so self-registering its
18
- // permission kinds here costs nothing extra and makes Geolocation's
19
- // permission gating work without a separate app-level import.
20
-
21
- const PREFIX = '[@webority/mobile-core]';
22
- class GeolocationError extends Error {
23
- constructor(code, message) {
24
- super(message);
25
- this.name = 'GeolocationError';
26
- this.code = code;
27
- // Babel downlevels `class extends Error`, which breaks `instanceof` for
28
- // subclasses unless the prototype is restored explicitly.
29
- Object.setPrototypeOf(this, GeolocationError.prototype);
30
- }
31
- }
32
-
33
- /** Minimal shape of the native geolocation module we depend on. */
34
- exports.GeolocationError = GeolocationError;
35
- const DEFAULT_TIMEOUT_MS = 15000;
36
- const DEFAULT_RETRIES = 1;
37
- const DEFAULT_RETRY_DELAY_MS = 800;
38
-
39
- /** Only what a test or the showcase injected; null means use expo-location. */
40
- let backend = null;
41
-
42
- /**
43
- * expo-location is a required peer, so the JS module always resolves. What can
44
- * be missing is the NATIVE side: an app that installed the package without
45
- * running the native install gets a module whose calls are absent. Checking the
46
- * two the adapter needs is what lets `isAvailable` mean something and makes the
47
- * error below reachable.
48
- *
49
- * An INJECTED backend is taken on trust, like every other seam in this package.
50
- */
51
- const hasNativeLocation = mod => typeof mod?.getCurrentPositionAsync === 'function' && typeof mod?.watchPositionAsync === 'function';
52
- let expoBackend;
53
- const resolveBackend = () => {
54
- if (backend) {
55
- return backend;
56
- }
57
- if (expoBackend === undefined) {
58
- const mod = ExpoLocation;
59
- expoBackend = hasNativeLocation(mod) ? (0, _expoLocation2.adaptExpoLocation)(mod) : null;
60
- }
61
- return expoBackend;
62
- };
63
-
64
- /**
65
- * Replace the geolocation provider. Intended for TESTS and for the showcase,
66
- * which injects a denying provider to demo the permission and services-off
67
- * errors; an app gets expo-location without wiring anything. Pass `null` to
68
- * restore it.
69
- */
70
- const setGeolocationImplementation = impl => {
71
- backend = impl;
72
- };
73
- exports.setGeolocationImplementation = setGeolocationImplementation;
74
- const requireBackend = op => {
75
- const b = resolveBackend();
76
- if (!b) {
77
- throw new GeolocationError('unsupported', `${PREFIX} No geolocation provider is available; cannot ${op}. ` + 'expo-location did not load, which on a real build means the native ' + 'module was not linked.');
78
- }
79
- return b;
80
- };
81
-
82
- /**
83
- * Android reports "location services are switched off" through the same code 2
84
- * that also covers a genuine failure to fix a position, and the two need
85
- * different handling: one is fixed by the user in system settings, the other is
86
- * worth retrying. The message is the only signal that separates them.
87
- */
88
- const SERVICES_OFF_PATTERN = /(location|gps)[^.]{0,40}(disabled|switched off|turned off|not enabled)|no location provider|settings_not_satisfied|location services (are |is )?off/i;
89
- const toGeoError = raw => {
90
- if (raw instanceof GeolocationError) {
91
- return raw;
92
- }
93
- const native = raw ?? {};
94
- const detail = typeof native.message === 'string' && native.message.length > 0 ? native.message : 'the provider gave no reason';
95
- switch (native.code) {
96
- case 1:
97
- return new GeolocationError('permission-denied', `${PREFIX} Location permission was denied (${detail}). Request the ` + 'location permission before calling, or send the user to settings.');
98
- case 2:
99
- return SERVICES_OFF_PATTERN.test(detail) ? new GeolocationError('services-disabled', `${PREFIX} Location services are switched off (${detail}). Ask the user ` + 'to enable location in system settings; retrying will not help.') : new GeolocationError('position-unavailable', `${PREFIX} No position fix (${detail}).`);
100
- case 3:
101
- return new GeolocationError('timeout', `${PREFIX} Location request timed out (${detail}).`);
102
- case 4:
103
- case 5:
104
- return new GeolocationError('services-disabled', `${PREFIX} Location services are unavailable on this device (${detail}). ` + 'Ask the user to enable location, or install Google Play services.');
105
- default:
106
- return new GeolocationError('position-unavailable', `${PREFIX} Location request failed (${detail}).`);
107
- }
108
- };
109
- const RETRYABLE = ['timeout', 'position-unavailable'];
110
- const normalizeCoords = raw => {
111
- const coords = raw?.coords;
112
- if (!coords || !Number.isFinite(coords.latitude) || !Number.isFinite(coords.longitude)) {
113
- return null;
114
- }
115
- return {
116
- latitude: coords.latitude,
117
- longitude: coords.longitude,
118
- // An absent radius is treated as infinitely bad rather than perfect, so a
119
- // provider that omits it can never satisfy `minimumAccuracyM` by accident.
120
- accuracy: Number.isFinite(coords.accuracy) ? coords.accuracy : Number.POSITIVE_INFINITY,
121
- altitude: Number.isFinite(coords.altitude) ? coords.altitude : null,
122
- heading: Number.isFinite(coords.heading) ? coords.heading : null,
123
- speed: Number.isFinite(coords.speed) ? coords.speed : null
124
- };
125
- };
126
- const normalizePosition = raw => {
127
- const coords = normalizeCoords(raw);
128
- if (!coords) {
129
- return null;
130
- }
131
- return {
132
- coords,
133
- timestamp: Number.isFinite(raw?.timestamp) ? raw?.timestamp : Date.now()
134
- };
135
- };
136
- const toNativeOptions = options => {
137
- const native = {
138
- enableHighAccuracy: (options.accuracy ?? 'fine') === 'fine',
139
- timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
140
- maximumAge: options.maximumAgeMs ?? 0
141
- };
142
- if (options.distanceFilterM !== undefined) {
143
- native.distanceFilter = options.distanceFilterM;
144
- }
145
- return native;
146
- };
147
- const sleep = ms => new Promise(resolve => {
148
- setTimeout(resolve, ms);
149
- });
150
- const ensureLocationPermission = async () => {
151
- const status = await _index2.Permissions.ensure('location');
152
- if (status === 'granted' || status === 'limited') {
153
- return;
154
- }
155
- if (status === 'unavailable') {
156
- _index.Logger.warn(`${PREFIX} Location permission status is unavailable (expo-location is not installed, ` + 'or the check failed); attempting the location request anyway.');
157
- return;
158
- }
159
- throw new GeolocationError('permission-denied', `${PREFIX} Location permission is "${status}". Grant it before requesting a position` + (status === 'blocked' ? ', or call Permissions.openSettings() to let the user fix it.' : '.'));
160
- };
161
- const positionOnce = (b, options) => {
162
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
163
- return new Promise((resolve, reject) => {
164
- let settled = false;
165
- // The native timeout is passed through as well, but a provider that never
166
- // calls back at all would otherwise hang the caller forever.
167
- const timer = setTimeout(() => {
168
- if (settled) {
169
- return;
170
- }
171
- settled = true;
172
- reject(new GeolocationError('timeout', `${PREFIX} Location request timed out after ${timeoutMs}ms. Raise timeoutMs, or use ` + "accuracy: 'coarse' where a network fix is good enough."));
173
- }, timeoutMs);
174
- const settle = run => {
175
- if (settled) {
176
- return;
177
- }
178
- settled = true;
179
- clearTimeout(timer);
180
- run();
181
- };
182
- const onSuccess = raw => settle(() => {
183
- const position = normalizePosition(raw);
184
- if (!position) {
185
- reject(new GeolocationError('position-unavailable', `${PREFIX} The provider returned a fix without usable coordinates.`));
186
- return;
187
- }
188
- const floor = options.minimumAccuracyM;
189
- if (floor !== undefined && position.coords.accuracy > floor) {
190
- reject(new GeolocationError('position-unavailable', `${PREFIX} Fix accuracy ${position.coords.accuracy}m is worse than the required ` + `${floor}m.`));
191
- return;
192
- }
193
- resolve(position);
194
- });
195
- const onError = error => settle(() => reject(toGeoError(error)));
196
- try {
197
- b.getCurrentPosition(onSuccess, onError, toNativeOptions(options));
198
- } catch (error) {
199
- settle(() => reject(toGeoError(error)));
200
- }
201
- });
202
- };
203
- const getCurrentPosition = async (options = {}) => {
204
- const b = requireBackend('get the current position');
205
- await ensureLocationPermission();
206
- const attempts = Math.max(0, Math.trunc(options.retries ?? DEFAULT_RETRIES)) + 1;
207
- const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
208
- let lastError = null;
209
- for (let attempt = 0; attempt < attempts; attempt += 1) {
210
- try {
211
- return await positionOnce(b, options);
212
- } catch (error) {
213
- const geoError = toGeoError(error);
214
- if (!RETRYABLE.includes(geoError.code)) {
215
- throw geoError;
216
- }
217
- lastError = geoError;
218
- if (attempt < attempts - 1 && retryDelayMs > 0) {
219
- await sleep(retryDelayMs);
220
- }
221
- }
222
- }
223
- throw lastError ?? new GeolocationError('position-unavailable', `${PREFIX} Location request failed.`);
224
- };
225
- const watchPosition = (listener, options = {}) => {
226
- const b = requireBackend('watch the position');
227
- let cancelled = false;
228
- let watchId = null;
229
- const stop = () => {
230
- if (cancelled) {
231
- return;
232
- }
233
- cancelled = true;
234
- if (watchId !== null) {
235
- b.clearWatch(watchId);
236
- watchId = null;
237
- }
238
- };
239
- const fail = error => {
240
- const geoError = toGeoError(error);
241
- _index.Logger.error(geoError.message);
242
- options.onError?.(geoError);
243
- };
244
- void ensureLocationPermission().then(() => {
245
- // The caller can unsubscribe while the permission gate is still pending;
246
- // registering afterwards would leak a watch nothing can clear.
247
- if (cancelled) {
248
- return;
249
- }
250
- watchId = b.watchPosition(raw => {
251
- if (cancelled) {
252
- return;
253
- }
254
- const position = normalizePosition(raw);
255
- if (!position) {
256
- return;
257
- }
258
- const floor = options.minimumAccuracyM;
259
- if (floor !== undefined && position.coords.accuracy > floor) {
260
- return;
261
- }
262
- listener(position);
263
- }, error => {
264
- if (!cancelled) {
265
- fail(error);
266
- }
267
- }, toNativeOptions(options));
268
- }).catch(fail);
269
- return stop;
270
- };
271
- const isAvailable = () => resolveBackend() !== null;
272
- const Geolocation = exports.Geolocation = {
273
- getCurrentPosition,
274
- watchPosition,
275
- isAvailable
276
- };
277
- const useCurrentPosition = (options = {}) => {
278
- const {
279
- enabled = true,
280
- accuracy,
281
- timeoutMs,
282
- maximumAgeMs,
283
- retries,
284
- minimumAccuracyM,
285
- retryDelayMs
286
- } = options;
287
- const [state, setState] = (0, _react.useState)({
288
- position: null,
289
- error: null,
290
- loading: enabled
291
- });
292
- const mountedRef = (0, _react.useRef)(true);
293
- // Identifies the in-flight request so a slow earlier fix cannot overwrite the
294
- // result of a later refresh().
295
- const requestRef = (0, _react.useRef)(0);
296
- (0, _react.useEffect)(() => {
297
- mountedRef.current = true;
298
- return () => {
299
- mountedRef.current = false;
300
- };
301
- }, []);
302
-
303
- // Every dependency is a primitive read off `options`, so an inline options
304
- // object (the normal call shape) does not re-create this on every render.
305
- const run = (0, _react.useCallback)(() => {
306
- requestRef.current += 1;
307
- const token = requestRef.current;
308
- setState(prev => prev.loading ? prev : {
309
- ...prev,
310
- loading: true
311
- });
312
- const accept = next => {
313
- if (mountedRef.current && requestRef.current === token) {
314
- setState(next);
315
- }
316
- };
317
- getCurrentPosition({
318
- accuracy,
319
- timeoutMs,
320
- maximumAgeMs,
321
- retries,
322
- minimumAccuracyM,
323
- retryDelayMs
324
- }).then(position => accept({
325
- position,
326
- error: null,
327
- loading: false
328
- }), error => accept({
329
- position: null,
330
- error: toGeoError(error),
331
- loading: false
332
- }));
333
- }, [accuracy, timeoutMs, maximumAgeMs, retries, minimumAccuracyM, retryDelayMs]);
334
- (0, _react.useEffect)(() => {
335
- if (!enabled) {
336
- // Discard any in-flight request so its result cannot land after opting out.
337
- requestRef.current += 1;
338
- setState(prev => prev.loading || prev.position !== null || prev.error !== null ? {
339
- position: null,
340
- error: null,
341
- loading: false
342
- } : prev);
343
- return;
344
- }
345
- run();
346
- }, [enabled, run]);
347
- return {
348
- position: state.position,
349
- error: state.error,
350
- loading: state.loading,
351
- refresh: run
352
- };
353
- };
354
- exports.useCurrentPosition = useCurrentPosition;
355
- //# sourceMappingURL=index.js.map
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useCurrentPosition=exports.setGeolocationImplementation=exports.GeolocationError=exports.Geolocation=void 0;var ExpoLocation=_interopRequireWildcard(require("expo-location")),_react=require("react"),_index=require("../logger/index.js"),_index2=require("../permissions/index.js");require("../permissions/location.js");var _expoLocation2=require("./adapters/expoLocation.js");function _interopRequireWildcard(e,o){if("function"==typeof WeakMap)var t=new WeakMap,i=new WeakMap;return(_interopRequireWildcard=function(e,o){if(!o&&e&&e.__esModule)return e;var r,n,a={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return a;if(r=o?i:t){if(r.has(e))return r.get(e);r.set(e,a)}for(const o in e)"default"!==o&&{}.hasOwnProperty.call(e,o)&&((n=(r=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,o))&&(n.get||n.set)?r(a,o,n):a[o]=e[o]);return a})(e,o)}const PREFIX="[@webority/mobile-core]";class GeolocationError extends Error{constructor(e,o){super(o),this.name="GeolocationError",this.code=e,Object.setPrototypeOf(this,GeolocationError.prototype)}}exports.GeolocationError=GeolocationError;const DEFAULT_TIMEOUT_MS=15e3,DEFAULT_RETRIES=1,DEFAULT_RETRY_DELAY_MS=800;let backend=null;const hasNativeLocation=e=>"function"==typeof e?.getCurrentPositionAsync&&"function"==typeof e?.watchPositionAsync;let expoBackend;const resolveBackend=()=>{if(backend)return backend;if(void 0===expoBackend){const e=ExpoLocation;expoBackend=hasNativeLocation(e)?(0,_expoLocation2.adaptExpoLocation)(e):null}return expoBackend},setGeolocationImplementation=e=>{backend=e};exports.setGeolocationImplementation=setGeolocationImplementation;const requireBackend=e=>{const o=resolveBackend();if(!o)throw new GeolocationError("unsupported",`${PREFIX} No geolocation provider is available; cannot ${e}. expo-location did not load, which on a real build means the native module was not linked.`);return o},SERVICES_OFF_PATTERN=/(location|gps)[^.]{0,40}(disabled|switched off|turned off|not enabled)|no location provider|settings_not_satisfied|location services (are |is )?off/i,toGeoError=e=>{if(e instanceof GeolocationError)return e;const o=e??{},t="string"==typeof o.message&&o.message.length>0?o.message:"the provider gave no reason";switch(o.code){case 1:return new GeolocationError("permission-denied",`${PREFIX} Location permission was denied (${t}). Request the location permission before calling, or send the user to settings.`);case 2:return SERVICES_OFF_PATTERN.test(t)?new GeolocationError("services-disabled",`${PREFIX} Location services are switched off (${t}). Ask the user to enable location in system settings; retrying will not help.`):new GeolocationError("position-unavailable",`${PREFIX} No position fix (${t}).`);case 3:return new GeolocationError("timeout",`${PREFIX} Location request timed out (${t}).`);case 4:case 5:return new GeolocationError("services-disabled",`${PREFIX} Location services are unavailable on this device (${t}). Ask the user to enable location, or install Google Play services.`);default:return new GeolocationError("position-unavailable",`${PREFIX} Location request failed (${t}).`)}},RETRYABLE=["timeout","position-unavailable"],normalizeCoords=e=>{const o=e?.coords;return o&&Number.isFinite(o.latitude)&&Number.isFinite(o.longitude)?{latitude:o.latitude,longitude:o.longitude,accuracy:Number.isFinite(o.accuracy)?o.accuracy:Number.POSITIVE_INFINITY,altitude:Number.isFinite(o.altitude)?o.altitude:null,heading:Number.isFinite(o.heading)?o.heading:null,speed:Number.isFinite(o.speed)?o.speed:null}:null},normalizePosition=e=>{const o=normalizeCoords(e);return o?{coords:o,timestamp:Number.isFinite(e?.timestamp)?e?.timestamp:Date.now()}:null},toNativeOptions=e=>{const o={enableHighAccuracy:"fine"===(e.accuracy??"fine"),timeout:e.timeoutMs??15e3,maximumAge:e.maximumAgeMs??0};return void 0!==e.distanceFilterM&&(o.distanceFilter=e.distanceFilterM),o},sleep=e=>new Promise(o=>{setTimeout(o,e)}),ensureLocationPermission=async()=>{const e=await _index2.Permissions.ensure("location");if("granted"!==e&&"limited"!==e){if("unavailable"!==e)throw new GeolocationError("permission-denied",`${PREFIX} Location permission is "${e}". Grant it before requesting a position`+("blocked"===e?", or call Permissions.openSettings() to let the user fix it.":"."));_index.Logger.warn(`${PREFIX} Location permission status is unavailable (expo-location is not installed, or the check failed); attempting the location request anyway.`)}},positionOnce=(e,o)=>{const t=o.timeoutMs??15e3;return new Promise((i,r)=>{let n=!1;const a=setTimeout(()=>{n||(n=!0,r(new GeolocationError("timeout",`${PREFIX} Location request timed out after ${t}ms. Raise timeoutMs, or use accuracy: 'coarse' where a network fix is good enough.`)))},t),settle=e=>{n||(n=!0,clearTimeout(a),e())},onSuccess=e=>settle(()=>{const t=normalizePosition(e);if(!t)return void r(new GeolocationError("position-unavailable",`${PREFIX} The provider returned a fix without usable coordinates.`));const n=o.minimumAccuracyM;void 0!==n&&t.coords.accuracy>n?r(new GeolocationError("position-unavailable",`${PREFIX} Fix accuracy ${t.coords.accuracy}m is worse than the required ${n}m.`)):i(t)}),onError=e=>settle(()=>r(toGeoError(e)));try{e.getCurrentPosition(onSuccess,onError,toNativeOptions(o))}catch(e){settle(()=>r(toGeoError(e)))}})},getCurrentPosition=async(e={})=>{const o=requireBackend("get the current position");await ensureLocationPermission();const t=Math.max(0,Math.trunc(e.retries??1))+1,i=e.retryDelayMs??800;let r=null;for(let n=0;n<t;n+=1)try{return await positionOnce(o,e)}catch(e){const o=toGeoError(e);if(!RETRYABLE.includes(o.code))throw o;r=o,n<t-1&&i>0&&await sleep(i)}throw r??new GeolocationError("position-unavailable",`${PREFIX} Location request failed.`)},watchPosition=(e,o={})=>{const t=requireBackend("watch the position");let i=!1,r=null;const fail=e=>{const t=toGeoError(e);_index.Logger.error(t.message),o.onError?.(t)};return ensureLocationPermission().then(()=>{i||(r=t.watchPosition(t=>{if(i)return;const r=normalizePosition(t);if(!r)return;const n=o.minimumAccuracyM;void 0!==n&&r.coords.accuracy>n||e(r)},e=>{i||fail(e)},toNativeOptions(o)))}).catch(fail),()=>{i||(i=!0,null!==r&&(t.clearWatch(r),r=null))}},isAvailable=()=>null!==resolveBackend(),Geolocation=exports.Geolocation={getCurrentPosition:getCurrentPosition,watchPosition:watchPosition,isAvailable:isAvailable},useCurrentPosition=(e={})=>{const{enabled:o=!0,accuracy:t,timeoutMs:i,maximumAgeMs:r,retries:n,minimumAccuracyM:a,retryDelayMs:s}=e,[c,l]=(0,_react.useState)({position:null,error:null,loading:o}),u=(0,_react.useRef)(!0),d=(0,_react.useRef)(0);(0,_react.useEffect)(()=>(u.current=!0,()=>{u.current=!1}),[]);const p=(0,_react.useCallback)(()=>{d.current+=1;const e=d.current;l(e=>e.loading?e:{...e,loading:!0});const accept=o=>{u.current&&d.current===e&&l(o)};getCurrentPosition({accuracy:t,timeoutMs:i,maximumAgeMs:r,retries:n,minimumAccuracyM:a,retryDelayMs:s}).then(e=>accept({position:e,error:null,loading:!1}),e=>accept({position:null,error:toGeoError(e),loading:!1}))},[t,i,r,n,a,s]);return(0,_react.useEffect)(()=>{if(!o)return d.current+=1,void l(e=>e.loading||null!==e.position||null!==e.error?{position:null,error:null,loading:!1}:e);p()},[o,p]),{position:c.position,error:c.error,loading:c.loading,refresh:p}};exports.useCurrentPosition=useCurrentPosition;