@ateam-ai-mobile/expo 0.1.5 → 0.1.7

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 (158) hide show
  1. package/android/build.gradle +16 -0
  2. package/android/src/main/java/expo/modules/adavision/AdaVisionModule.kt +75 -0
  3. package/dist/attachmentCache-DhQTqi2E.d.mts +18 -0
  4. package/dist/attachmentCache-DhQTqi2E.d.ts +18 -0
  5. package/dist/bootstrap.d.mts +95 -0
  6. package/dist/bootstrap.d.ts +95 -0
  7. package/dist/bootstrap.js +2473 -0
  8. package/dist/bootstrap.js.map +1 -0
  9. package/dist/bootstrap.mjs +64 -0
  10. package/dist/bootstrap.mjs.map +1 -0
  11. package/dist/chunk-4BMWVN25.mjs +91 -0
  12. package/dist/chunk-4BMWVN25.mjs.map +1 -0
  13. package/dist/chunk-4XYXJYN5.mjs +1513 -0
  14. package/dist/chunk-4XYXJYN5.mjs.map +1 -0
  15. package/dist/chunk-5HM6UA2K.mjs +571 -0
  16. package/dist/chunk-5HM6UA2K.mjs.map +1 -0
  17. package/dist/chunk-6LXF3JVX.mjs +96 -0
  18. package/dist/chunk-6LXF3JVX.mjs.map +1 -0
  19. package/dist/chunk-FF6ZZZXH.mjs +71 -0
  20. package/dist/chunk-FF6ZZZXH.mjs.map +1 -0
  21. package/dist/chunk-KOXF2FZM.mjs +92 -0
  22. package/dist/chunk-KOXF2FZM.mjs.map +1 -0
  23. package/dist/chunk-L4V7OCJ3.mjs +71 -0
  24. package/dist/chunk-L4V7OCJ3.mjs.map +1 -0
  25. package/dist/chunk-TZXWVYYR.mjs +67 -0
  26. package/dist/chunk-TZXWVYYR.mjs.map +1 -0
  27. package/dist/chunk-VQJPSLHP.mjs +1801 -0
  28. package/dist/chunk-VQJPSLHP.mjs.map +1 -0
  29. package/dist/chunk-WMJKH4XE.mjs +34 -0
  30. package/dist/chunk-WMJKH4XE.mjs.map +1 -0
  31. package/dist/chunk-XQSY6MHP.mjs +213 -0
  32. package/dist/chunk-XQSY6MHP.mjs.map +1 -0
  33. package/dist/createBridge.mjs +2 -0
  34. package/dist/createBridge.mjs.map +1 -1
  35. package/dist/device/createDeviceProvider.d.mts +23 -0
  36. package/dist/device/createDeviceProvider.d.ts +23 -0
  37. package/dist/device/createDeviceProvider.js +967 -0
  38. package/dist/device/createDeviceProvider.js.map +1 -0
  39. package/dist/device/createDeviceProvider.mjs +17 -0
  40. package/dist/device/createDeviceProvider.mjs.map +1 -0
  41. package/dist/device-bridge/collectors/appEngagement.d.mts +10 -0
  42. package/dist/device-bridge/collectors/appEngagement.d.ts +10 -0
  43. package/dist/device-bridge/collectors/appEngagement.js +128 -0
  44. package/dist/device-bridge/collectors/appEngagement.js.map +1 -0
  45. package/dist/device-bridge/collectors/appEngagement.mjs +12 -0
  46. package/dist/device-bridge/collectors/appEngagement.mjs.map +1 -0
  47. package/dist/device-bridge/collectors/health.d.mts +24 -0
  48. package/dist/device-bridge/collectors/health.d.ts +24 -0
  49. package/dist/device-bridge/collectors/health.js +238 -0
  50. package/dist/device-bridge/collectors/health.js.map +1 -0
  51. package/dist/device-bridge/collectors/health.mjs +18 -0
  52. package/dist/device-bridge/collectors/health.mjs.map +1 -0
  53. package/dist/device-bridge/cookies.d.mts +49 -0
  54. package/dist/device-bridge/cookies.d.ts +49 -0
  55. package/dist/device-bridge/cookies.js +90 -0
  56. package/dist/device-bridge/cookies.js.map +1 -0
  57. package/dist/device-bridge/cookies.mjs +14 -0
  58. package/dist/device-bridge/cookies.mjs.map +1 -0
  59. package/dist/device-bridge/index.d.mts +483 -0
  60. package/dist/device-bridge/index.d.ts +483 -0
  61. package/dist/device-bridge/index.js +2084 -0
  62. package/dist/device-bridge/index.js.map +1 -0
  63. package/dist/device-bridge/index.mjs +32 -0
  64. package/dist/device-bridge/index.mjs.map +1 -0
  65. package/dist/device-bridge/nfc.d.mts +30 -0
  66. package/dist/device-bridge/nfc.d.ts +30 -0
  67. package/dist/device-bridge/nfc.js +109 -0
  68. package/dist/device-bridge/nfc.js.map +1 -0
  69. package/dist/device-bridge/nfc.mjs +14 -0
  70. package/dist/device-bridge/nfc.mjs.map +1 -0
  71. package/dist/index.d.mts +493 -18
  72. package/dist/index.d.ts +493 -18
  73. package/dist/index.js +1409 -6
  74. package/dist/index.js.map +1 -1
  75. package/dist/index.mjs +23 -194
  76. package/dist/index.mjs.map +1 -1
  77. package/dist/oauth/expoOAuth.d.mts +18 -0
  78. package/dist/oauth/expoOAuth.d.ts +18 -0
  79. package/dist/oauth/expoOAuth.js +102 -0
  80. package/dist/oauth/expoOAuth.js.map +1 -0
  81. package/dist/oauth/expoOAuth.mjs +8 -0
  82. package/dist/oauth/expoOAuth.mjs.map +1 -0
  83. package/dist/types-BRanJYTn.d.mts +138 -0
  84. package/dist/types-BRanJYTn.d.ts +138 -0
  85. package/dist/vision/index.d.mts +81 -0
  86. package/dist/vision/index.d.ts +81 -0
  87. package/dist/vision/index.js +101 -0
  88. package/dist/vision/index.js.map +1 -0
  89. package/dist/vision/index.mjs +28 -0
  90. package/dist/vision/index.mjs.map +1 -0
  91. package/expo-module.config.json +9 -0
  92. package/ios/AdaVision.podspec +28 -0
  93. package/ios/AdaVisionModule.swift +432 -0
  94. package/ios/Resources/yolov8n-oiv7.mlmodelc/analytics/coremldata.bin +0 -0
  95. package/ios/Resources/yolov8n-oiv7.mlmodelc/coremldata.bin +0 -0
  96. package/ios/Resources/yolov8n-oiv7.mlmodelc/metadata.json +773 -0
  97. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/analytics/coremldata.bin +0 -0
  98. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/coremldata.bin +0 -0
  99. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/model.mil +720 -0
  100. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/weights/weight.bin +0 -0
  101. package/ios/Resources/yolov8n-oiv7.mlmodelc/model1/coremldata.bin +0 -0
  102. package/package.json +107 -7
  103. package/src/bootstrap.ts +159 -0
  104. package/src/camera/CameraTaskHost.tsx +175 -0
  105. package/src/camera/cameraTasks.ts +129 -0
  106. package/src/device/createDeviceProvider.ts +832 -0
  107. package/src/device-bridge/actions/calendar-actions.ts +217 -0
  108. package/src/device-bridge/actions/dnd.ts +74 -0
  109. package/src/device-bridge/actions/health-actions.ts +58 -0
  110. package/src/device-bridge/actions/index.ts +12 -0
  111. package/src/device-bridge/actions/messaging.ts +74 -0
  112. package/src/device-bridge/actions/navigation.ts +88 -0
  113. package/src/device-bridge/actions/queue-poller.ts +151 -0
  114. package/src/device-bridge/background.ts +137 -0
  115. package/src/device-bridge/biometrics.ts +64 -0
  116. package/src/device-bridge/capabilities.ts +218 -0
  117. package/src/device-bridge/collectors/appEngagement.ts +120 -0
  118. package/src/device-bridge/collectors/battery.ts +83 -0
  119. package/src/device-bridge/collectors/calendar.ts +162 -0
  120. package/src/device-bridge/collectors/camera.ts +27 -0
  121. package/src/device-bridge/collectors/connectivity.ts +60 -0
  122. package/src/device-bridge/collectors/contacts.ts +200 -0
  123. package/src/device-bridge/collectors/health.ts +299 -0
  124. package/src/device-bridge/collectors/index.ts +12 -0
  125. package/src/device-bridge/collectors/location.ts +224 -0
  126. package/src/device-bridge/collectors/mood.ts +141 -0
  127. package/src/device-bridge/collectors/notifications.ts +70 -0
  128. package/src/device-bridge/cookies.ts +89 -0
  129. package/src/device-bridge/dynamic-connector.ts +422 -0
  130. package/src/device-bridge/index.ts +467 -0
  131. package/src/device-bridge/nfc.ts +85 -0
  132. package/src/device-bridge/plugin.ts +71 -0
  133. package/src/device-bridge/relay-client.ts +237 -0
  134. package/src/device-bridge/scanner.ts +42 -0
  135. package/src/device-bridge/sharing.ts +35 -0
  136. package/src/device-bridge/types.ts +326 -0
  137. package/src/device-state/activityClassifier.ts +151 -0
  138. package/src/device-state/activityEngine.ts +252 -0
  139. package/src/device-state/collectors.ts +31 -0
  140. package/src/device-state/domains/activity.ts +93 -0
  141. package/src/device-state/domains/capability.ts +60 -0
  142. package/src/device-state/domains/connectivity.ts +60 -0
  143. package/src/device-state/domains/deviceContext.ts +55 -0
  144. package/src/device-state/domains/interaction.ts +59 -0
  145. package/src/device-state/domains/spatial.ts +283 -0
  146. package/src/device-state/domains/visual.ts +100 -0
  147. package/src/device-state/headingSource.ts +84 -0
  148. package/src/device-state/index.ts +77 -0
  149. package/src/device-state/quality.ts +60 -0
  150. package/src/device-state/replay.ts +220 -0
  151. package/src/device-state/turnDetector.ts +121 -0
  152. package/src/device-state/visualEngine.ts +341 -0
  153. package/src/haptics.ts +4 -0
  154. package/src/index.ts +37 -0
  155. package/src/oauth/expoOAuth.tsx +113 -0
  156. package/src/vision/analysis.js +80 -0
  157. package/src/vision/index.ts +144 -0
  158. package/src/vision/ring.js +35 -0
@@ -0,0 +1,2473 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/device-bridge/cookies.ts
34
+ var cookies_exports = {};
35
+ __export(cookies_exports, {
36
+ clearAll: () => clearAll,
37
+ get: () => get,
38
+ set: () => set
39
+ });
40
+ async function get(url, includeHttpOnly = true) {
41
+ const raw = await import_cookies.default.get(url, includeHttpOnly);
42
+ const out = [];
43
+ for (const [name, c] of Object.entries(raw || {})) {
44
+ if (!c || typeof c !== "object") continue;
45
+ const value = typeof c.value === "string" ? c.value : String(c.value ?? "");
46
+ const cookie = { name, value };
47
+ if (c.domain) cookie.domain = String(c.domain);
48
+ if (c.path) cookie.path = String(c.path);
49
+ if (c.expires) {
50
+ const t = Date.parse(c.expires);
51
+ if (!Number.isNaN(t)) cookie.expires = Math.floor(t / 1e3);
52
+ }
53
+ if (typeof c.httpOnly === "boolean") cookie.httpOnly = c.httpOnly;
54
+ if (typeof c.secure === "boolean") cookie.secure = c.secure;
55
+ if (c.sameSite === "Lax" || c.sameSite === "Strict" || c.sameSite === "None") {
56
+ cookie.sameSite = c.sameSite;
57
+ }
58
+ out.push(cookie);
59
+ }
60
+ return out;
61
+ }
62
+ async function clearAll() {
63
+ try {
64
+ await import_cookies.default.clearAll(true);
65
+ return { ok: true };
66
+ } catch (e) {
67
+ return { ok: false, error: String(e?.message || e) };
68
+ }
69
+ }
70
+ async function set(url, cookie) {
71
+ try {
72
+ await import_cookies.default.set(url, {
73
+ name: cookie.name,
74
+ value: cookie.value,
75
+ domain: cookie.domain,
76
+ path: cookie.path || "/",
77
+ httpOnly: cookie.httpOnly,
78
+ secure: cookie.secure
79
+ }, true);
80
+ return { ok: true };
81
+ } catch (e) {
82
+ return { ok: false, error: String(e?.message || e) };
83
+ }
84
+ }
85
+ var import_cookies;
86
+ var init_cookies = __esm({
87
+ "src/device-bridge/cookies.ts"() {
88
+ "use strict";
89
+ import_cookies = __toESM(require("@react-native-cookies/cookies"));
90
+ }
91
+ });
92
+
93
+ // src/device-bridge/nfc.ts
94
+ var nfc_exports = {};
95
+ __export(nfc_exports, {
96
+ isEnabled: () => isEnabled,
97
+ isSupported: () => isSupported2,
98
+ readOnce: () => readOnce
99
+ });
100
+ async function ensureInit() {
101
+ if (_initialized) return true;
102
+ try {
103
+ const supported = await import_react_native_nfc_manager.default.isSupported();
104
+ if (!supported) return false;
105
+ await import_react_native_nfc_manager.default.start();
106
+ _initialized = true;
107
+ return true;
108
+ } catch (e) {
109
+ return false;
110
+ }
111
+ }
112
+ async function isSupported2() {
113
+ try {
114
+ return await import_react_native_nfc_manager.default.isSupported();
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+ async function isEnabled() {
120
+ try {
121
+ return await import_react_native_nfc_manager.default.isEnabled();
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+ async function readOnce(timeoutMs = 3e4) {
127
+ const ready = await ensureInit();
128
+ if (!ready) return { ok: false, error: "nfc_unsupported" };
129
+ try {
130
+ const tag = await Promise.race([
131
+ import_react_native_nfc_manager.default.requestTechnology(import_react_native_nfc_manager.NfcTech.Ndef).then(() => import_react_native_nfc_manager.default.getTag()),
132
+ new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs))
133
+ ]);
134
+ if (!tag) {
135
+ try {
136
+ await import_react_native_nfc_manager.default.cancelTechnologyRequest();
137
+ } catch {
138
+ }
139
+ return { ok: false, error: "timeout" };
140
+ }
141
+ const records = [];
142
+ if (tag.ndefMessage) {
143
+ for (const r of tag.ndefMessage) {
144
+ try {
145
+ const type = String.fromCharCode(...r.type || []);
146
+ const payload = import_react_native_nfc_manager.Ndef.text.decodePayload(r.payload || []);
147
+ records.push({ type, payload: String(payload) });
148
+ } catch {
149
+ }
150
+ }
151
+ }
152
+ const tagId = tag.id ? Array.from(tag.id).map((b) => b.toString(16).padStart(2, "0")).join("") : void 0;
153
+ return { ok: true, tagId, records };
154
+ } catch (e) {
155
+ return { ok: false, error: String(e?.message || e) };
156
+ } finally {
157
+ try {
158
+ await import_react_native_nfc_manager.default.cancelTechnologyRequest();
159
+ } catch {
160
+ }
161
+ }
162
+ }
163
+ var import_react_native_nfc_manager, _initialized;
164
+ var init_nfc = __esm({
165
+ "src/device-bridge/nfc.ts"() {
166
+ "use strict";
167
+ import_react_native_nfc_manager = __toESM(require("react-native-nfc-manager"));
168
+ _initialized = false;
169
+ }
170
+ });
171
+
172
+ // src/bootstrap.ts
173
+ var bootstrap_exports = {};
174
+ __export(bootstrap_exports, {
175
+ bootstrapExpoAdas: () => bootstrapExpoAdas
176
+ });
177
+ module.exports = __toCommonJS(bootstrap_exports);
178
+ var import_core2 = require("@ateam-ai-mobile/core");
179
+ var import_plugin_runtime3 = require("@ateam-ai-mobile/plugin-runtime");
180
+ var import_ui2 = require("@ateam-ai-mobile/ui");
181
+
182
+ // src/index.ts
183
+ var ExpoWebBrowser = __toESM(require("expo-web-browser"));
184
+ var ExpoLinking = __toESM(require("expo-linking"));
185
+ var ExpoClipboard = __toESM(require("expo-clipboard"));
186
+ var import_async_storage3 = __toESM(require("@react-native-async-storage/async-storage"));
187
+ var import_core = require("@ateam-ai-mobile/core");
188
+ var import_plugin_runtime2 = require("@ateam-ai-mobile/plugin-runtime");
189
+ var import_ui = require("@ateam-ai-mobile/ui");
190
+
191
+ // src/haptics.ts
192
+ var Haptics = __toESM(require("expo-haptics"));
193
+ var expoHaptics = {
194
+ impact(style) {
195
+ const map = {
196
+ light: Haptics.ImpactFeedbackStyle.Light,
197
+ medium: Haptics.ImpactFeedbackStyle.Medium,
198
+ heavy: Haptics.ImpactFeedbackStyle.Heavy
199
+ };
200
+ Haptics.impactAsync(map[style]).catch(() => {
201
+ });
202
+ },
203
+ notification(type) {
204
+ const map = {
205
+ success: Haptics.NotificationFeedbackType.Success,
206
+ warning: Haptics.NotificationFeedbackType.Warning,
207
+ error: Haptics.NotificationFeedbackType.Error
208
+ };
209
+ Haptics.notificationAsync(map[type]).catch(() => {
210
+ });
211
+ },
212
+ selection() {
213
+ Haptics.selectionAsync().catch(() => {
214
+ });
215
+ },
216
+ // Shorthand for notification('error') — the form plugins actually call.
217
+ error() {
218
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error).catch(() => {
219
+ });
220
+ }
221
+ };
222
+
223
+ // src/bundleStorage.ts
224
+ var FileSystem = __toESM(require("expo-file-system/legacy"));
225
+ var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
226
+ var CACHE_DIR = `${FileSystem.cacheDirectory}plugin-bundles/`;
227
+ var DEFAULT_CACHE_INDEX_KEY = "adas-plugin-bundles-index-v1";
228
+ var ExpoBundleStorage = class {
229
+ /** Pass `indexKey` when migrating from an app that already persisted a
230
+ * bundle index under a different key — keeps the existing cache warm. */
231
+ constructor(opts) {
232
+ this.dirReady = false;
233
+ this.indexKey = opts?.indexKey || DEFAULT_CACHE_INDEX_KEY;
234
+ }
235
+ async ensureDir() {
236
+ if (this.dirReady) return;
237
+ try {
238
+ const info = await FileSystem.getInfoAsync(CACHE_DIR);
239
+ if (!info.exists) {
240
+ await FileSystem.makeDirectoryAsync(CACHE_DIR, { intermediates: true });
241
+ }
242
+ } catch (err) {
243
+ console.warn("[ExpoBundleStorage] cache dir error:", err);
244
+ }
245
+ this.dirReady = true;
246
+ }
247
+ async loadIndex() {
248
+ try {
249
+ const raw = await import_async_storage.default.getItem(this.indexKey);
250
+ return raw ? JSON.parse(raw) : {};
251
+ } catch {
252
+ return {};
253
+ }
254
+ }
255
+ async saveIndex(index) {
256
+ try {
257
+ await import_async_storage.default.setItem(this.indexKey, JSON.stringify(index));
258
+ } catch (err) {
259
+ console.warn("[ExpoBundleStorage] index save error:", err);
260
+ }
261
+ }
262
+ async readBundle(localPath) {
263
+ try {
264
+ const info = await FileSystem.getInfoAsync(localPath);
265
+ if (!info.exists) return null;
266
+ return await FileSystem.readAsStringAsync(localPath);
267
+ } catch {
268
+ return null;
269
+ }
270
+ }
271
+ async writeBundle(key, content) {
272
+ await this.ensureDir();
273
+ const localPath = `${CACHE_DIR}${key}`;
274
+ await FileSystem.writeAsStringAsync(localPath, content);
275
+ return localPath;
276
+ }
277
+ async deleteBundle(localPath) {
278
+ await FileSystem.deleteAsync(localPath, { idempotent: true }).catch(() => {
279
+ });
280
+ }
281
+ async clearAll() {
282
+ await FileSystem.deleteAsync(CACHE_DIR, { idempotent: true }).catch(() => {
283
+ });
284
+ await import_async_storage.default.removeItem(this.indexKey).catch(() => {
285
+ });
286
+ this.dirReady = false;
287
+ }
288
+ };
289
+
290
+ // src/attachmentCache.ts
291
+ var FileSystem2 = __toESM(require("expo-file-system/legacy"));
292
+ var import_async_storage2 = __toESM(require("@react-native-async-storage/async-storage"));
293
+ var DEFAULT_INDEX_KEY = "adas-chat-attachment-index-v1";
294
+ var DIR = `${FileSystem2.documentDirectory}chat-attachments/`;
295
+ var MAX_JOBS = 100;
296
+ var ExpoAttachmentCache = class {
297
+ /** Pass `indexKey` when migrating from an app that already persisted an
298
+ * index under a different AsyncStorage key — otherwise existing users
299
+ * lose every cached preview on upgrade. */
300
+ constructor(opts) {
301
+ this.index = {};
302
+ const indexKey = opts?.indexKey || DEFAULT_INDEX_KEY;
303
+ this.indexKey = indexKey;
304
+ this.loaded = (async () => {
305
+ try {
306
+ const info = await FileSystem2.getInfoAsync(DIR);
307
+ if (!info.exists) await FileSystem2.makeDirectoryAsync(DIR, { intermediates: true });
308
+ const raw = await import_async_storage2.default.getItem(indexKey);
309
+ if (raw) this.index = JSON.parse(raw);
310
+ } catch {
311
+ }
312
+ })();
313
+ }
314
+ async ready() {
315
+ await this.loaded;
316
+ }
317
+ async save(jobId, attachments) {
318
+ await this.loaded;
319
+ const entries = [];
320
+ for (let i = 0; i < attachments.length; i++) {
321
+ const att = attachments[i];
322
+ const ext = att.mimeType.startsWith("image/") ? att.mimeType.split("/")[1] || "jpg" : "bin";
323
+ const filePath = `${DIR}${jobId}_${i}.${ext}`;
324
+ try {
325
+ await FileSystem2.writeAsStringAsync(filePath, att.data, { encoding: FileSystem2.EncodingType.Base64 });
326
+ entries.push({ mimeType: att.mimeType, name: att.name, filePath });
327
+ } catch (err) {
328
+ console.warn("[ExpoAttachmentCache] write failed:", err);
329
+ }
330
+ }
331
+ if (entries.length === 0) return;
332
+ this.index[jobId] = entries;
333
+ const keys = Object.keys(this.index);
334
+ if (keys.length > MAX_JOBS) {
335
+ for (const k of keys.slice(0, keys.length - MAX_JOBS)) {
336
+ const old = this.index[k];
337
+ if (old) for (const o of old) FileSystem2.deleteAsync(o.filePath, { idempotent: true }).catch(() => {
338
+ });
339
+ delete this.index[k];
340
+ }
341
+ }
342
+ try {
343
+ await import_async_storage2.default.setItem(this.indexKey, JSON.stringify(this.index));
344
+ } catch {
345
+ }
346
+ }
347
+ get(jobId) {
348
+ const entries = this.index[jobId];
349
+ if (!entries || entries.length === 0) return void 0;
350
+ return entries.map((e) => ({
351
+ mimeType: e.mimeType,
352
+ name: e.name,
353
+ previewUri: e.filePath
354
+ }));
355
+ }
356
+ };
357
+
358
+ // src/device-state/domains/deviceContext.ts
359
+ var ExpoBattery = __toESM(require("expo-battery"));
360
+
361
+ // src/device-state/quality.ts
362
+ var import_plugin_runtime = require("@ateam-ai-mobile/plugin-runtime");
363
+ var FRESH_MS = 1e4;
364
+ var AGING_MS = 6e4;
365
+ function qualityFrom(observedAt, confidence) {
366
+ const ageMs = Date.now() - observedAt;
367
+ return {
368
+ freshness: {
369
+ state: ageMs < FRESH_MS ? "fresh" : ageMs < AGING_MS ? "aging" : "stale",
370
+ observedAt,
371
+ ageMs
372
+ },
373
+ ...confidence ? { confidence } : {}
374
+ };
375
+ }
376
+ function qualityUnknown() {
377
+ return { freshness: (0, import_plugin_runtime.neverObserved)() };
378
+ }
379
+ function unsupported(what) {
380
+ const err = new Error(
381
+ `${what} is not implemented in this build \u2014 the native engine behind it does not exist yet.`
382
+ );
383
+ err.code = "UNSUPPORTED";
384
+ return err;
385
+ }
386
+
387
+ // src/device-state/domains/deviceContext.ts
388
+ function createDeviceContextDomain() {
389
+ return {
390
+ async getSnapshot() {
391
+ const observedAt = Date.now();
392
+ try {
393
+ const [level, state, lowPower] = await Promise.all([
394
+ ExpoBattery.getBatteryLevelAsync(),
395
+ ExpoBattery.getBatteryStateAsync(),
396
+ ExpoBattery.isLowPowerModeEnabledAsync()
397
+ ]);
398
+ return {
399
+ power: {
400
+ // expo-battery returns -1 when it cannot tell. That is not a level.
401
+ batteryLevel: typeof level === "number" && level >= 0 ? level : null,
402
+ charging: state === ExpoBattery.BatteryState.CHARGING || state === ExpoBattery.BatteryState.FULL,
403
+ lowPowerMode: lowPower
404
+ },
405
+ // No Expo API for either. iOS needs ProcessInfo.thermalState, Android
406
+ // PowerManager.getThermalStatus — a native module that does not exist.
407
+ thermal: { state: "unknown" },
408
+ resources: { memoryPressure: "unknown", storagePressure: "unknown" },
409
+ quality: qualityFrom(observedAt)
410
+ };
411
+ } catch {
412
+ return {
413
+ power: { batteryLevel: null, charging: null, lowPowerMode: null },
414
+ thermal: { state: "unknown" },
415
+ resources: { memoryPressure: "unknown", storagePressure: "unknown" },
416
+ quality: qualityUnknown()
417
+ };
418
+ }
419
+ },
420
+ // Real events, not a placeholder: expo-battery exposes native listeners,
421
+ // so a plugin that subscribes genuinely hears about a change rather than
422
+ // sitting on a subscription that can never fire.
423
+ subscribe(listener) {
424
+ const subs = [
425
+ ExpoBattery.addBatteryLevelListener(() => listener({ type: "batteryLevelChanged" })),
426
+ ExpoBattery.addBatteryStateListener(() => listener({ type: "chargingChanged" }))
427
+ ];
428
+ return { unsubscribe: () => subs.forEach((x) => x?.remove?.()) };
429
+ }
430
+ };
431
+ }
432
+
433
+ // src/device-state/domains/connectivity.ts
434
+ function createConnectivityDomain(collectors) {
435
+ return {
436
+ async getSnapshot() {
437
+ const observedAt = Date.now();
438
+ try {
439
+ if (!collectors.connectivity) throw unsupported("connectivity collector");
440
+ const data = await collectors.connectivity.collectConnectivity();
441
+ const online = data?.is_connected === true;
442
+ const type = String(data?.type || "").toLowerCase();
443
+ return {
444
+ reachability: data?.is_connected == null ? "unknown" : online ? "online" : "offline",
445
+ transport: type === "wifi" ? "wifi" : type === "cellular" ? "cellular" : type === "ethernet" ? "ethernet" : online ? "other" : data?.is_connected === false ? "none" : "unknown",
446
+ // All four below need measurement nobody takes yet. `unknown` is the
447
+ // designed answer — "return unknown rather than stale precision".
448
+ qualityClass: "unknown",
449
+ stability: "unknown",
450
+ latencyMs: null,
451
+ bandwidthClass: "unknown",
452
+ metered: null,
453
+ constrained: null,
454
+ quality: qualityFrom(observedAt)
455
+ };
456
+ } catch {
457
+ return {
458
+ reachability: "unknown",
459
+ transport: "unknown",
460
+ qualityClass: "unknown",
461
+ stability: "unknown",
462
+ latencyMs: null,
463
+ bandwidthClass: "unknown",
464
+ metered: null,
465
+ constrained: null,
466
+ quality: qualityUnknown()
467
+ };
468
+ }
469
+ },
470
+ // Intent selects a native sampling strategy — latency probes, quality
471
+ // classification. Nothing here samples anything, so accepting an intent
472
+ // would be accepting an instruction we do not carry out.
473
+ async start() {
474
+ throw unsupported("connectivity.start");
475
+ },
476
+ async stop() {
477
+ throw unsupported("connectivity.stop");
478
+ },
479
+ // A subscription that can never fire is worse than none: the caller
480
+ // reasonably reads silence as "nothing changed".
481
+ subscribe() {
482
+ throw unsupported("connectivity.subscribe");
483
+ }
484
+ };
485
+ }
486
+
487
+ // src/device-state/domains/capability.ts
488
+ function statusFrom(granted) {
489
+ return {
490
+ support: "unknown",
491
+ permission: granted === null ? "unknown" : granted ? "granted" : "denied",
492
+ availability: "unknown"
493
+ };
494
+ }
495
+ var UNKNOWN_STATUS = {
496
+ support: "unknown",
497
+ permission: "unknown",
498
+ availability: "unknown"
499
+ };
500
+ function createCapabilityDomain(collectors) {
501
+ return {
502
+ async getSnapshot() {
503
+ const observedAt = Date.now();
504
+ const locationGranted = collectors.location ? await collectors.location.hasPermission().catch(() => null) : null;
505
+ return {
506
+ // Only location has a real reader today. The rest are declared by the
507
+ // contract and answered honestly rather than omitted.
508
+ camera: UNKNOWN_STATUS,
509
+ microphone: UNKNOWN_STATUS,
510
+ location: {
511
+ ...statusFrom(locationGranted),
512
+ // iOS 14+ distinguishes precise from approximate; nothing reads it.
513
+ precision: "unknown",
514
+ backgroundPermission: "unknown"
515
+ },
516
+ motion: UNKNOWN_STATUS,
517
+ bluetooth: UNKNOWN_STATUS,
518
+ uwb: UNKNOWN_STATUS,
519
+ nfc: UNKNOWN_STATUS,
520
+ quality: qualityFrom(observedAt)
521
+ };
522
+ },
523
+ // No OS permission-change stream is wired. Same reasoning as connectivity:
524
+ // silence would be indistinguishable from stability.
525
+ subscribe() {
526
+ throw unsupported("capability.subscribe");
527
+ }
528
+ };
529
+ }
530
+
531
+ // src/device-state/domains/interaction.ts
532
+ var import_react_native = require("react-native");
533
+ function createInteractionDomain() {
534
+ const mapState = (s) => s === "active" ? "foreground" : s === "background" ? "background" : s === "inactive" ? "inactive" : "unknown";
535
+ return {
536
+ async getSnapshot() {
537
+ const observedAt = Date.now();
538
+ return {
539
+ lifecycle: {
540
+ appState: mapState(import_react_native.AppState.currentState),
541
+ screenOn: null,
542
+ userActive: null,
543
+ idleDurationMs: null
544
+ },
545
+ audio: {
546
+ captureActive: null,
547
+ playbackActive: null,
548
+ route: "unknown",
549
+ interruption: "unknown"
550
+ },
551
+ // The voice block is OMITTED rather than filled with nulls: the design
552
+ // says a platform that cannot report voice session state leaves the
553
+ // group out instead of guessing `false` for each field. The app's own
554
+ // voice store knows this, but it is not reachable from the SDK.
555
+ quality: qualityFrom(observedAt)
556
+ };
557
+ },
558
+ // Real: AppState genuinely emits on every foreground/background change,
559
+ // which is the one part of this domain that works.
560
+ subscribe(listener) {
561
+ const sub2 = import_react_native.AppState.addEventListener("change", (next) => {
562
+ listener({ type: "appStateChanged", appState: mapState(next) });
563
+ });
564
+ return { unsubscribe: () => sub2.remove() };
565
+ }
566
+ };
567
+ }
568
+
569
+ // src/device-state/visualEngine.ts
570
+ var PROFILES = {
571
+ navigation: { intervalMs: 1e3, windowMs: 5e3 },
572
+ accessibility: { intervalMs: 1e3, windowMs: 5e3 },
573
+ stream: { intervalMs: 500, windowMs: 5e3 },
574
+ inspection: { intervalMs: 2e3, windowMs: 8e3 },
575
+ shopping: { intervalMs: 2e3, windowMs: 5e3 },
576
+ document: { intervalMs: 3e3, windowMs: 3e3 },
577
+ ocr: { intervalMs: 3e3, windowMs: 3e3 },
578
+ highQuality: { intervalMs: 5e3, windowMs: 5e3 }
579
+ };
580
+ var VisualEngine = class {
581
+ constructor() {
582
+ this.frames = [];
583
+ this.session = null;
584
+ this.listeners = /* @__PURE__ */ new Set();
585
+ /** Set by the host component while a camera is actually mounted and ready. */
586
+ this.cameraReady = false;
587
+ /** Optional: supplies heading/position stamped onto each frame. */
588
+ this.context = null;
589
+ // The native ring's actual retention (ms). The engine's effective window is
590
+ // min(intent window, retention) — set by whoever owns the clamp semantics; this
591
+ // just stores the input so that logic has one source of truth to read.
592
+ this._retentionMs = null;
593
+ }
594
+ /** Host DI. Without it frames carry no orientation, and say so with nulls. */
595
+ setContextProvider(p) {
596
+ this.context = p;
597
+ }
598
+ // ── session ──
599
+ startSession(intent) {
600
+ if (this.session) return this.session;
601
+ this.session = {
602
+ id: `visual_${Date.now()}`,
603
+ intent: PROFILES[intent] ? intent : "navigation",
604
+ startedAt: Date.now(),
605
+ suspended: false
606
+ };
607
+ this.notify();
608
+ return this.session;
609
+ }
610
+ stopSession() {
611
+ this.session = null;
612
+ this.frames = [];
613
+ this.cameraReady = false;
614
+ this.notify();
615
+ }
616
+ /**
617
+ * Background: suspend, do not end.
618
+ *
619
+ * iOS tears the camera down when the app leaves the foreground. The session
620
+ * is a STATE that survives that; what does not survive is the claim that the
621
+ * camera is live. While suspended the ring is kept but ages — a read gets
622
+ * old frames clearly marked old, rather than a fresh-looking lie.
623
+ */
624
+ suspend() {
625
+ if (!this.session || this.session.suspended) return;
626
+ this.session.suspended = true;
627
+ this.cameraReady = false;
628
+ this.notify();
629
+ }
630
+ resume() {
631
+ if (!this.session?.suspended) return;
632
+ this.session.suspended = false;
633
+ this.notify();
634
+ }
635
+ getSession() {
636
+ return this.session;
637
+ }
638
+ /** Is a camera mounted and ready right now? Only the host knows. */
639
+ setCameraReady(ready) {
640
+ this.cameraReady = ready;
641
+ this.notify();
642
+ }
643
+ isCameraReady() {
644
+ return this.cameraReady && !this.session?.suspended;
645
+ }
646
+ // ── the ring ──
647
+ profile() {
648
+ const intent = this.session?.intent || "navigation";
649
+ return PROFILES[intent];
650
+ }
651
+ /**
652
+ * Feed from the native vision session (VisionSession, iOS) — the FAST frame
653
+ * source that replaces the takePictureAsync loop. The frame is IN-MEMORY: the
654
+ * native ring holds the pixels keyed by `id`, and native.vision resolves that
655
+ * id inside the trusted layer. No `uri` crosses here; the quality is a REAL
656
+ * measurement (not `unknown`), and `expiresAt` is the ring's real eviction time.
657
+ * The public VisualFrameRef strip to id-only is owned by the device-state session.
658
+ */
659
+ pushFrameMeta(meta) {
660
+ let heading = null;
661
+ try {
662
+ heading = this.context?.heading() ?? null;
663
+ } catch {
664
+ }
665
+ this.frames.push({
666
+ // In-memory: no file. native.vision resolves the id inside the native ring.
667
+ handle: { id: meta.id, mimeType: "image/none", expiresAt: meta.expiresAt ?? null },
668
+ timestamp: meta.timestamp,
669
+ orientation: { headingDeg: heading?.headingDeg ?? null, pitchDeg: null, rollDeg: null },
670
+ quality: meta.quality ?? { blur: "unknown", exposure: "unknown", obstructed: null }
671
+ });
672
+ this.evict();
673
+ this.notify();
674
+ }
675
+ setRetentionMs(ms) {
676
+ this._retentionMs = ms && ms > 0 ? ms : null;
677
+ }
678
+ retentionMs() {
679
+ return this._retentionMs;
680
+ }
681
+ /**
682
+ * How far back the timeline ACTUALLY reaches: `min(intent window, native
683
+ * retention)`.
684
+ *
685
+ * The intent asks for a window; native decides what it can afford to keep.
686
+ * Full-res luma at ~24fps is tens of megabytes for a few seconds, so the ring
687
+ * is memory-bounded and shrinks under pressure — `retentionMs` is native
688
+ * publishing what it is really holding.
689
+ *
690
+ * EVERY FRAME IN THE TIMELINE CAN BE ANALYSED. That is the one sentence a
691
+ * plugin author has to hold, and this clamp is what makes it true. The
692
+ * alternative — listing frames past retention marked "not analysable" — was
693
+ * considered and rejected: a caller would have to check a flag before every
694
+ * use, and forgetting throws mid-guidance on a frame the model can see
695
+ * listed. Present-but-unusable is the same trap as an empty rowset reading
696
+ * as "no rows matched".
697
+ *
698
+ * If per-frame history beyond retention is ever needed, the shape is an
699
+ * AGGREGATE on the snapshot ("the view has been unusable for N ms"), never a
700
+ * per-entry flag.
701
+ */
702
+ effectiveWindowMs() {
703
+ const intent = this.profile().windowMs;
704
+ const retention = this._retentionMs;
705
+ return retention === null ? intent : Math.min(intent, retention);
706
+ }
707
+ /**
708
+ * Time-based, not count-based: the design specifies a rolling WINDOW.
709
+ *
710
+ * Evicts on the EFFECTIVE window, so a frame whose pixels native has already
711
+ * dropped leaves the timeline at the same moment. Without this, `frameById`
712
+ * would start returning null for frames still being listed.
713
+ */
714
+ evict() {
715
+ const cutoff = Date.now() - this.effectiveWindowMs();
716
+ this.frames = this.frames.filter((f) => f.timestamp >= cutoff);
717
+ }
718
+ timeline() {
719
+ this.evict();
720
+ return { windowMs: this.effectiveWindowMs(), frames: [...this.frames] };
721
+ }
722
+ latest() {
723
+ this.evict();
724
+ return this.frames.length ? this.frames[this.frames.length - 1] : null;
725
+ }
726
+ /**
727
+ * Resolve a frame handle id (from a VisualFrameRef) back to the live frame so
728
+ * the mechanical layer — native.vision — can read its on-device file. The
729
+ * whole contract of that layer is that it takes an id, never pixels; this is
730
+ * where an id becomes a `handle.uri` it can open. Returns null when the id is
731
+ * unknown OR its frame has aged out of the rolling window (the cache file may
732
+ * also be gone by then) — a real "I can't look at that frame" answer, which
733
+ * the caller must treat as distinct from "I looked and found nothing".
734
+ */
735
+ frameById(id) {
736
+ this.evict();
737
+ return this.frames.find((f) => f.handle.id === id) ?? null;
738
+ }
739
+ /**
740
+ * Record a MEASURED quality back onto a frame (native.vision.assessQuality).
741
+ * Frames are minted with `quality: unknown` because nothing looks at the
742
+ * pixels at capture time; this is how a real measurement replaces that so a
743
+ * later read of VisualFrameRef.quality reflects it. No-op if the frame has
744
+ * aged out — we never resurrect an evicted frame just to label it.
745
+ */
746
+ setFrameQuality(id, quality) {
747
+ const f = this.frames.find((fr) => fr.handle.id === id);
748
+ if (!f) return;
749
+ f.quality = quality;
750
+ this.notify();
751
+ }
752
+ // ── change notification ──
753
+ subscribe(fn) {
754
+ this.listeners.add(fn);
755
+ return () => this.listeners.delete(fn);
756
+ }
757
+ notify() {
758
+ for (const fn of this.listeners) {
759
+ try {
760
+ fn();
761
+ } catch {
762
+ }
763
+ }
764
+ }
765
+ };
766
+ var visualEngine = new VisualEngine();
767
+ function frameQuality(frame) {
768
+ if (!frame) return { freshness: { state: "unknown", observedAt: null, ageMs: null } };
769
+ const ageMs = Date.now() - frame.timestamp;
770
+ return {
771
+ freshness: {
772
+ // Tighter than the other domains on purpose: a two-second-old frame of a
773
+ // moving scene is not "fresh" in any useful sense.
774
+ state: ageMs < 2e3 ? "fresh" : ageMs < 1e4 ? "aging" : "stale",
775
+ observedAt: frame.timestamp,
776
+ ageMs
777
+ },
778
+ confidence: { level: "unknown" }
779
+ };
780
+ }
781
+
782
+ // src/device-state/headingSource.ts
783
+ var ExpoLocation = __toESM(require("expo-location"));
784
+
785
+ // src/device-state/turnDetector.ts
786
+ function signedDelta(a, b) {
787
+ return (b - a + 540) % 360 - 180;
788
+ }
789
+ var TurnDetector = class {
790
+ constructor(opts = {}) {
791
+ /** The heading currently treated as "straight ahead". */
792
+ this.refDeg = null;
793
+ this.stableSince = 0;
794
+ this.lastTurn = null;
795
+ this.minTurnDeg = opts.minTurnDeg ?? 35;
796
+ this.stableDeg = opts.stableDeg ?? 12;
797
+ this.stableMs = opts.stableMs ?? 2500;
798
+ }
799
+ /** Feed one compass reading. `null` degrees means the compass said nothing. */
800
+ push(deg, now) {
801
+ if (deg === null) return null;
802
+ if (this.refDeg === null) {
803
+ this.refDeg = deg;
804
+ this.stableSince = now;
805
+ return null;
806
+ }
807
+ const delta = signedDelta(this.refDeg, deg);
808
+ if (Math.abs(delta) >= this.minTurnDeg) {
809
+ this.lastTurn = { deg: Math.round(delta), timestamp: now };
810
+ this.refDeg = deg;
811
+ this.stableSince = now;
812
+ return this.lastTurn;
813
+ }
814
+ if (Math.abs(delta) > this.stableDeg) {
815
+ this.stableSince = now;
816
+ return null;
817
+ }
818
+ if (now - this.stableSince >= this.stableMs) {
819
+ this.refDeg = deg;
820
+ this.stableSince = now;
821
+ }
822
+ return null;
823
+ }
824
+ /**
825
+ * The most recent completed turn, or null if none this session.
826
+ *
827
+ * It does NOT expire on its own: the age is derivable from `timestamp`, and
828
+ * "recent enough to mention" is a product judgement this layer must not make
829
+ * on the caller's behalf.
830
+ */
831
+ last() {
832
+ return this.lastTurn;
833
+ }
834
+ reset() {
835
+ this.refDeg = null;
836
+ this.stableSince = 0;
837
+ this.lastTurn = null;
838
+ }
839
+ };
840
+
841
+ // src/device-state/headingSource.ts
842
+ var latest = null;
843
+ var sub = null;
844
+ var turns = new TurnDetector();
845
+ async function startHeading() {
846
+ if (sub) return;
847
+ try {
848
+ sub = await ExpoLocation.watchHeadingAsync((h) => {
849
+ const raw = h.trueHeading >= 0 ? h.trueHeading : h.magHeading;
850
+ const deg = typeof raw === "number" && raw >= 0 ? raw : null;
851
+ const cal = typeof h.accuracy === "number" && h.accuracy >= 0 ? h.accuracy : null;
852
+ latest = { headingDeg: deg, calibration: cal, timestamp: Date.now() };
853
+ turns.push(deg, Date.now());
854
+ });
855
+ } catch {
856
+ sub = null;
857
+ }
858
+ }
859
+ function stopHeading() {
860
+ sub?.remove();
861
+ sub = null;
862
+ latest = null;
863
+ turns.reset();
864
+ }
865
+ function currentHeading() {
866
+ return latest ? { headingDeg: latest.headingDeg } : null;
867
+ }
868
+ function currentHeadingDetail() {
869
+ return latest;
870
+ }
871
+ function lastMeaningfulTurn() {
872
+ return turns.last();
873
+ }
874
+
875
+ // src/device-state/domains/spatial.ts
876
+ function createSpatialDomain(collectors, speedRef) {
877
+ const RECENT_PATH_MAX = 60;
878
+ const STATIONARY_MPS = 0.4;
879
+ let recentPath = [];
880
+ let latest2 = null;
881
+ let latestSpeed = null;
882
+ let latestCourse = null;
883
+ let stopWatch = null;
884
+ let sessionId = null;
885
+ const nonNegative2 = (v) => typeof v === "number" && v >= 0 ? v : null;
886
+ const derivedSpeed = () => {
887
+ if (recentPath.length < 2) return null;
888
+ const b = recentPath[recentPath.length - 1];
889
+ const a = recentPath[recentPath.length - 2];
890
+ const dtS = (b.timestamp - a.timestamp) / 1e3;
891
+ if (dtS <= 0 || dtS > 10) return null;
892
+ return distanceOf([a, b]) / dtS;
893
+ };
894
+ const derivedCourse = () => {
895
+ if (recentPath.length < 2) return null;
896
+ const b = recentPath[recentPath.length - 1];
897
+ const a = recentPath[recentPath.length - 2];
898
+ if (b.timestamp - a.timestamp > 1e4) return null;
899
+ if (distanceOf([a, b]) < 3) return null;
900
+ return bearingBetween(a, b);
901
+ };
902
+ return {
903
+ async getSnapshot() {
904
+ let point = latest2;
905
+ let speedMps = latestSpeed;
906
+ let courseDeg = latestCourse;
907
+ let derived = false;
908
+ if (!point) {
909
+ try {
910
+ if (!collectors.location) throw unsupported("location collector");
911
+ const fix = await collectors.location.getPosition({ accuracy: "low" });
912
+ point = {
913
+ latitude: fix.latitude,
914
+ longitude: fix.longitude,
915
+ altitude: fix.altitude ?? null,
916
+ accuracyM: nonNegative2(fix.accuracy),
917
+ timestamp: fix.timestamp ?? Date.now()
918
+ };
919
+ speedMps = nonNegative2(fix.speed);
920
+ courseDeg = nonNegative2(fix.course);
921
+ } catch {
922
+ return {
923
+ position: null,
924
+ movement: { speedMps: null, bearingDeg: null, distanceRecentM: null, state: "unknown" },
925
+ orientation: { headingDeg: null },
926
+ recentPath: [],
927
+ quality: qualityUnknown()
928
+ };
929
+ }
930
+ }
931
+ if (speedMps === null) {
932
+ const d = derivedSpeed();
933
+ if (d !== null) {
934
+ speedMps = d;
935
+ derived = true;
936
+ }
937
+ }
938
+ if (courseDeg === null) {
939
+ const d = derivedCourse();
940
+ if (d !== null) {
941
+ courseDeg = d;
942
+ derived = true;
943
+ }
944
+ }
945
+ const heading = currentHeadingDetail();
946
+ const turn = lastMeaningfulTurn();
947
+ return {
948
+ position: point,
949
+ movement: {
950
+ speedMps,
951
+ bearingDeg: courseDeg,
952
+ // Needs two points from the SAME session; without a stream there is
953
+ // nothing to measure against, and a distance of 0 would read as
954
+ // "the user has not moved".
955
+ distanceRecentM: recentPath.length >= 2 ? distanceOf(recentPath) : null,
956
+ // Only claim stationary/moving when a speed was actually obtained.
957
+ // With no speed the truthful answer is `unknown`, not `stationary` —
958
+ // "you have stopped" is a false statement, not a neutral default.
959
+ state: speedMps === null ? "unknown" : speedMps < STATIONARY_MPS ? "stationary" : "moving"
960
+ },
961
+ orientation: {
962
+ headingDeg: heading?.headingDeg ?? null,
963
+ // NOT the calibration rank. iOS reports 0–3 (none…high), which is not
964
+ // a number of degrees, and converting one to the other would be an
965
+ // invented error bar. The rank drives `confidence` below instead.
966
+ headingAccuracyDeg: null
967
+ },
968
+ changes: {
969
+ lastMeaningfulTurnDeg: turn ? turn.deg : null,
970
+ timestamp: turn ? turn.timestamp : null
971
+ },
972
+ recentPath: [...recentPath],
973
+ quality: qualityFrom(
974
+ point.timestamp,
975
+ spatialConfidence(point.accuracyM ?? null, heading?.calibration ?? null, derived)
976
+ )
977
+ };
978
+ },
979
+ /**
980
+ * Open the warm window: position stream + compass.
981
+ *
982
+ * The intent is recorded but does NOT yet change sampling — no native
983
+ * strategy layer exists — so it is accepted rather than refused only
984
+ * because the streams it opens are real and useful.
985
+ */
986
+ async start(options) {
987
+ if (stopWatch) return { id: sessionId, intent: options.intent, startedAt: Date.now() };
988
+ sessionId = `spatial_${Date.now()}`;
989
+ if (!collectors.location) throw unsupported("location collector");
990
+ void startHeading();
991
+ stopWatch = collectors.location.watchPosition((pos) => {
992
+ const p = {
993
+ latitude: pos.latitude,
994
+ longitude: pos.longitude,
995
+ altitude: pos.altitude ?? null,
996
+ accuracyM: nonNegative2(pos.accuracy),
997
+ timestamp: pos.timestamp ?? Date.now()
998
+ };
999
+ latest2 = p;
1000
+ latestSpeed = nonNegative2(pos.speed);
1001
+ latestCourse = nonNegative2(pos.course);
1002
+ speedRef.mps = latestSpeed;
1003
+ speedRef.at = p.timestamp;
1004
+ recentPath = [...recentPath, p].slice(-RECENT_PATH_MAX);
1005
+ });
1006
+ return { id: sessionId, intent: options.intent, startedAt: Date.now() };
1007
+ },
1008
+ async stop() {
1009
+ stopWatch?.();
1010
+ stopWatch = null;
1011
+ sessionId = null;
1012
+ recentPath = [];
1013
+ latest2 = null;
1014
+ latestSpeed = null;
1015
+ latestCourse = null;
1016
+ speedRef.mps = null;
1017
+ speedRef.at = 0;
1018
+ if (!visualEngine.getSession()) stopHeading();
1019
+ },
1020
+ // No event vocabulary is frozen for spatial, and inventing names here would
1021
+ // put them in plugins before the freeze can contradict them.
1022
+ subscribe() {
1023
+ throw unsupported("spatial.subscribe");
1024
+ }
1025
+ };
1026
+ }
1027
+ function spatialConfidence(accuracyM, calibration, derived) {
1028
+ const rank = (v) => v === "high" ? 3 : v === "medium" ? 2 : v === "low" ? 1 : 0;
1029
+ const fromFix = accuracyM === null ? "unknown" : accuracyM <= 10 ? "high" : accuracyM <= 50 ? "medium" : "low";
1030
+ const fromCompass = calibration === null ? "unknown" : calibration >= 3 ? "high" : calibration >= 2 ? "medium" : "low";
1031
+ const parts = [fromFix, fromCompass, ...derived ? ["low"] : []];
1032
+ const known = parts.filter((p) => p !== "unknown");
1033
+ if (!known.length) return { level: "unknown" };
1034
+ const worst = known.reduce((a, b) => rank(a) <= rank(b) ? a : b);
1035
+ return { level: worst };
1036
+ }
1037
+ function bearingBetween(a, b) {
1038
+ const toRad = (d) => d * Math.PI / 180;
1039
+ const la1 = toRad(a.latitude), la2 = toRad(b.latitude);
1040
+ const dLon = toRad(b.longitude - a.longitude);
1041
+ const y = Math.sin(dLon) * Math.cos(la2);
1042
+ const x = Math.cos(la1) * Math.sin(la2) - Math.sin(la1) * Math.cos(la2) * Math.cos(dLon);
1043
+ return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
1044
+ }
1045
+ function distanceOf(path) {
1046
+ const R = 6371e3;
1047
+ let total = 0;
1048
+ for (let i = 1; i < path.length; i++) {
1049
+ const a = path[i - 1], b = path[i];
1050
+ const dLat = (b.latitude - a.latitude) * Math.PI / 180;
1051
+ const dLon = (b.longitude - a.longitude) * Math.PI / 180;
1052
+ const la1 = a.latitude * Math.PI / 180, la2 = b.latitude * Math.PI / 180;
1053
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(la1) * Math.cos(la2) * Math.sin(dLon / 2) ** 2;
1054
+ total += 2 * R * Math.asin(Math.sqrt(h));
1055
+ }
1056
+ return Math.round(total);
1057
+ }
1058
+
1059
+ // src/device-state/domains/visual.ts
1060
+ function createVisualDomain() {
1061
+ return {
1062
+ async getSnapshot() {
1063
+ const session = visualEngine.getSession();
1064
+ const latest2 = visualEngine.latest();
1065
+ const timeline = visualEngine.timeline();
1066
+ return {
1067
+ camera: {
1068
+ // `available` = the app could use a camera at all. `active` = one is
1069
+ // running RIGHT NOW. They differ exactly when it matters: a pocketed
1070
+ // phone is available but not active, and answering `true` to both
1071
+ // would let a guide speak about a scene nothing is watching.
1072
+ available: !!session,
1073
+ active: visualEngine.isCameraReady(),
1074
+ facing: session ? "back" : "unknown"
1075
+ },
1076
+ // null, not a stale frame dressed as current. A caller with no usable
1077
+ // frame must see nothing rather than something old.
1078
+ latest: latest2,
1079
+ recentTimeline: timeline,
1080
+ quality: frameQuality(latest2)
1081
+ };
1082
+ },
1083
+ async start(options) {
1084
+ const s = visualEngine.startSession(options?.intent || "navigation");
1085
+ visualEngine.setContextProvider({ heading: currentHeading });
1086
+ void startHeading();
1087
+ return { id: s.id, intent: s.intent, startedAt: s.startedAt };
1088
+ },
1089
+ async stop() {
1090
+ visualEngine.stopSession();
1091
+ visualEngine.setContextProvider(null);
1092
+ stopHeading();
1093
+ },
1094
+ /**
1095
+ * A deliberate one-shot. Distinct from getSnapshot because it is an
1096
+ * OPERATION: it waits for a frame rather than serving the newest one.
1097
+ *
1098
+ * Throws when it cannot, rather than returning an empty result — the
1099
+ * design is explicit that capture is an operation and reads are state.
1100
+ */
1101
+ async capture() {
1102
+ if (!visualEngine.getSession()) {
1103
+ throw unsupported("visual.capture without an open session \u2014 call start({ intent }) first");
1104
+ }
1105
+ if (!visualEngine.isCameraReady()) {
1106
+ const err2 = new Error(
1107
+ "The camera is not running right now \u2014 the app may be in the background."
1108
+ );
1109
+ err2.code = "TEMPORARILY_UNAVAILABLE";
1110
+ throw err2;
1111
+ }
1112
+ const before = visualEngine.latest()?.timestamp ?? 0;
1113
+ const deadline = Date.now() + 4e3;
1114
+ while (Date.now() < deadline) {
1115
+ const f = visualEngine.latest();
1116
+ if (f && f.timestamp > before) return { frame: f };
1117
+ await new Promise((r) => setTimeout(r, 100));
1118
+ }
1119
+ const err = new Error("No frame arrived within 4s.");
1120
+ err.code = "TIMEOUT";
1121
+ throw err;
1122
+ },
1123
+ subscribe(listener) {
1124
+ const off = visualEngine.subscribe(() => {
1125
+ listener({ type: "visualStateChanged" });
1126
+ });
1127
+ return { unsubscribe: off };
1128
+ }
1129
+ };
1130
+ }
1131
+
1132
+ // src/device-state/activityEngine.ts
1133
+ var sensors = null;
1134
+ var sensorsMissing = false;
1135
+ function loadSensors() {
1136
+ if (sensors || sensorsMissing) return sensors;
1137
+ try {
1138
+ sensors = require("expo-sensors");
1139
+ } catch {
1140
+ sensorsMissing = true;
1141
+ sensors = null;
1142
+ }
1143
+ return sensors;
1144
+ }
1145
+ var ACCEL_INTERVAL_MS = 200;
1146
+ var MOTION_WINDOW_MS = 3e3;
1147
+ var STEP_WINDOW_MS = 2e4;
1148
+ var GRAVITY_ALPHA = 0.1;
1149
+ var ActivityEngine = class {
1150
+ constructor() {
1151
+ this.accelSub = null;
1152
+ this.stepSub = null;
1153
+ this.magnitudes = [];
1154
+ this.gravity = null;
1155
+ this.steps = [];
1156
+ this.sessionId = null;
1157
+ this.startedAt = 0;
1158
+ /** When the CURRENT reading last changed — feeds `human.since`. */
1159
+ this.pedometerAvailable = null;
1160
+ // ── transitions ──
1161
+ //
1162
+ // Tracked on a timer inside the engine rather than computed when someone
1163
+ // reads, because a transition is an EVENT: "you started walking" happens
1164
+ // between two reads, and a domain that only classifies on demand reports the
1165
+ // state and loses the moment it changed. `since` has the same problem.
1166
+ this.current = "unknown";
1167
+ this.since = null;
1168
+ this.transitions = [];
1169
+ this.ticker = null;
1170
+ }
1171
+ isRunning() {
1172
+ return this.sessionId !== null;
1173
+ }
1174
+ session() {
1175
+ return this.sessionId ? { id: this.sessionId, startedAt: this.startedAt } : null;
1176
+ }
1177
+ /**
1178
+ * @param classify how to name the current activity — injected so the engine
1179
+ * keeps no opinion of its own and the classifier stays pure and testable.
1180
+ */
1181
+ async start(classify) {
1182
+ if (this.sessionId) return this.session();
1183
+ this.sessionId = `activity_${Date.now()}`;
1184
+ this.startedAt = Date.now();
1185
+ const s = loadSensors();
1186
+ if (!s) {
1187
+ this.pedometerAvailable = false;
1188
+ this.startTicking(classify);
1189
+ return this.session();
1190
+ }
1191
+ const { Accelerometer, Pedometer } = s;
1192
+ Accelerometer.setUpdateInterval(ACCEL_INTERVAL_MS);
1193
+ this.accelSub = Accelerometer.addListener(({ x, y, z }) => {
1194
+ const now = Date.now();
1195
+ this.magnitudes.push({ m: Math.sqrt(x * x + y * y + z * z), t: now });
1196
+ const cutoff = now - MOTION_WINDOW_MS;
1197
+ if (this.magnitudes.length > 8 && this.magnitudes[0].t < cutoff) {
1198
+ this.magnitudes = this.magnitudes.filter((s2) => s2.t >= cutoff);
1199
+ }
1200
+ this.gravity = this.gravity ? {
1201
+ x: this.gravity.x + GRAVITY_ALPHA * (x - this.gravity.x),
1202
+ y: this.gravity.y + GRAVITY_ALPHA * (y - this.gravity.y),
1203
+ z: this.gravity.z + GRAVITY_ALPHA * (z - this.gravity.z)
1204
+ } : { x, y, z };
1205
+ });
1206
+ try {
1207
+ this.pedometerAvailable = await Pedometer.isAvailableAsync();
1208
+ } catch {
1209
+ this.pedometerAvailable = false;
1210
+ }
1211
+ if (this.pedometerAvailable) {
1212
+ try {
1213
+ this.stepSub = Pedometer.watchStepCount(({ steps }) => {
1214
+ this.steps.push({ steps, t: Date.now() });
1215
+ const cutoff = Date.now() - STEP_WINDOW_MS;
1216
+ if (this.steps.length > 2 && this.steps[0].t < cutoff) {
1217
+ this.steps = this.steps.filter((s2) => s2.t >= cutoff);
1218
+ }
1219
+ });
1220
+ } catch {
1221
+ this.stepSub = null;
1222
+ this.pedometerAvailable = false;
1223
+ }
1224
+ }
1225
+ this.startTicking(classify);
1226
+ return this.session();
1227
+ }
1228
+ stop() {
1229
+ this.accelSub?.remove();
1230
+ this.stepSub?.remove();
1231
+ this.accelSub = null;
1232
+ this.stepSub = null;
1233
+ this.sessionId = null;
1234
+ this.stopTicking();
1235
+ this.magnitudes = [];
1236
+ this.steps = [];
1237
+ this.gravity = null;
1238
+ }
1239
+ /** Variance of accelerometer magnitude over the motion window, in g². */
1240
+ accelVariance() {
1241
+ const cutoff = Date.now() - MOTION_WINDOW_MS;
1242
+ const window = this.magnitudes.filter((s) => s.t >= cutoff);
1243
+ if (window.length < 5) return null;
1244
+ const mean = window.reduce((a, s) => a + s.m, 0) / window.length;
1245
+ return window.reduce((a, s) => a + (s.m - mean) ** 2, 0) / window.length;
1246
+ }
1247
+ currentGravity() {
1248
+ return this.gravity;
1249
+ }
1250
+ /**
1251
+ * Steps per minute over the step window.
1252
+ *
1253
+ * Computed from the DIFFERENCE between the first and last cumulative counts,
1254
+ * so it does not matter whether the platform counts from subscription start
1255
+ * or from midnight.
1256
+ *
1257
+ * Returns null — not 0 — when the window is too short to divide by. Zero
1258
+ * steps per minute is a real claim ("standing still") and must only be made
1259
+ * once there is a window long enough to support it.
1260
+ */
1261
+ cadenceSpm() {
1262
+ const cutoff = Date.now() - STEP_WINDOW_MS;
1263
+ const window = this.steps.filter((s) => s.t >= cutoff);
1264
+ if (window.length < 2) {
1265
+ if (this.pedometerAvailable && Date.now() - this.startedAt > STEP_WINDOW_MS) return 0;
1266
+ return null;
1267
+ }
1268
+ const first = window[0], last = window[window.length - 1];
1269
+ const minutes = (last.t - first.t) / 6e4;
1270
+ if (minutes <= 0) return null;
1271
+ return (last.steps - first.steps) / minutes;
1272
+ }
1273
+ /** Whether a pedometer exists and is permitted. Null before `start()`. */
1274
+ hasPedometer() {
1275
+ return this.pedometerAvailable;
1276
+ }
1277
+ /** When the newest sample arrived — what freshness is actually about. */
1278
+ observedAt() {
1279
+ const ts = [
1280
+ this.magnitudes[this.magnitudes.length - 1]?.t,
1281
+ this.steps[this.steps.length - 1]?.t
1282
+ ].filter((t) => typeof t === "number");
1283
+ return ts.length ? Math.max(...ts) : null;
1284
+ }
1285
+ /** Feed the engine its own classification once a second. */
1286
+ startTicking(classify) {
1287
+ this.ticker = setInterval(() => {
1288
+ const next = classify();
1289
+ if (next === this.current) return;
1290
+ this.current = next;
1291
+ this.since = Date.now();
1292
+ this.transitions = [...this.transitions, { name: next, timestamp: this.since }].slice(-10);
1293
+ }, 1e3);
1294
+ }
1295
+ stopTicking() {
1296
+ if (this.ticker) clearInterval(this.ticker);
1297
+ this.ticker = null;
1298
+ this.current = "unknown";
1299
+ this.since = null;
1300
+ this.transitions = [];
1301
+ }
1302
+ /** When the current activity began, or null if it has not been established. */
1303
+ currentSince() {
1304
+ return this.since;
1305
+ }
1306
+ /** Newest last, bounded. Empty is a real answer: nothing has changed yet. */
1307
+ recentTransitions() {
1308
+ return [...this.transitions];
1309
+ }
1310
+ };
1311
+ var activityEngine = new ActivityEngine();
1312
+
1313
+ // src/device-state/activityClassifier.ts
1314
+ var RUN_SPM = 140;
1315
+ var WALK_SPM = 20;
1316
+ var STILL_VAR = 2e-3;
1317
+ var ACTIVE_VAR = 0.02;
1318
+ var VEHICLE_MPS = 3;
1319
+ var AXIS_DOMINANT = 0.75;
1320
+ function classifyActivity(input) {
1321
+ return { human: classifyHuman(input), pose: classifyPose(input) };
1322
+ }
1323
+ function classifyHuman({ cadenceSpm, accelVariance, speedMps }) {
1324
+ if (cadenceSpm !== null && cadenceSpm >= RUN_SPM) {
1325
+ return { state: "running", confidence: { level: "high" } };
1326
+ }
1327
+ if (cadenceSpm !== null && cadenceSpm >= WALK_SPM) {
1328
+ return { state: "walking", confidence: { level: "high" } };
1329
+ }
1330
+ if (speedMps !== null && speedMps >= VEHICLE_MPS) {
1331
+ return { state: "unknown", confidence: { level: "low" } };
1332
+ }
1333
+ if (accelVariance !== null && accelVariance < STILL_VAR && (cadenceSpm === null || cadenceSpm < WALK_SPM)) {
1334
+ return { state: "stationary", confidence: { level: "medium" } };
1335
+ }
1336
+ return { state: "unknown", confidence: { level: "unknown" } };
1337
+ }
1338
+ function classifyPose({ gravity, accelVariance }) {
1339
+ if (!gravity) {
1340
+ return { placement: "unknown", orientation: "unknown", confidence: { level: "unknown" } };
1341
+ }
1342
+ const { x, y, z } = gravity;
1343
+ const orientation = Math.abs(z) >= AXIS_DOMINANT ? "flat" : Math.abs(y) >= AXIS_DOMINANT ? "portrait" : Math.abs(x) >= AXIS_DOMINANT ? "landscape" : "unknown";
1344
+ if (orientation === "flat" && accelVariance !== null && accelVariance < STILL_VAR) {
1345
+ return { placement: "table", orientation, confidence: { level: "high" } };
1346
+ }
1347
+ if (orientation !== "flat" && accelVariance !== null && accelVariance >= ACTIVE_VAR) {
1348
+ return { placement: "handheld", orientation, confidence: { level: "medium" } };
1349
+ }
1350
+ return { placement: "unknown", orientation, confidence: { level: "unknown" } };
1351
+ }
1352
+
1353
+ // src/device-state/domains/activity.ts
1354
+ function createActivityDomain(speedRef) {
1355
+ const SPEED_MAX_AGE_MS = 15e3;
1356
+ const input = () => ({
1357
+ cadenceSpm: activityEngine.cadenceSpm(),
1358
+ accelVariance: activityEngine.accelVariance(),
1359
+ gravity: activityEngine.currentGravity(),
1360
+ speedMps: speedRef.at && Date.now() - speedRef.at < SPEED_MAX_AGE_MS ? speedRef.mps : null
1361
+ });
1362
+ return {
1363
+ async getSnapshot() {
1364
+ if (!activityEngine.isRunning()) {
1365
+ return {
1366
+ human: { state: "unknown", since: null, confidence: { level: "unknown" } },
1367
+ devicePose: { placement: "unknown", orientation: "unknown", confidence: { level: "unknown" } },
1368
+ recentTransitions: [],
1369
+ quality: qualityUnknown()
1370
+ };
1371
+ }
1372
+ const verdict = classifyActivity(input());
1373
+ const observedAt = activityEngine.observedAt();
1374
+ const transitions = activityEngine.recentTransitions();
1375
+ return {
1376
+ human: {
1377
+ state: verdict.human.state,
1378
+ since: activityEngine.currentSince(),
1379
+ confidence: verdict.human.confidence
1380
+ },
1381
+ devicePose: {
1382
+ placement: verdict.pose.placement,
1383
+ orientation: verdict.pose.orientation,
1384
+ confidence: verdict.pose.confidence
1385
+ },
1386
+ transition: {
1387
+ current: verdict.human.state,
1388
+ // A hint, and we have no basis for one. The freeze calls `likelyNext`
1389
+ // advisory; advisory is not licence to invent it.
1390
+ likelyNext: null
1391
+ },
1392
+ recentTransitions: transitions,
1393
+ quality: observedAt === null ? qualityUnknown() : qualityFrom(observedAt, verdict.human.confidence)
1394
+ };
1395
+ },
1396
+ /**
1397
+ * Start sampling. The intent is recorded but does not yet change strategy —
1398
+ * there is no native power-tuning layer for it to reach.
1399
+ */
1400
+ async start(options) {
1401
+ const s = await activityEngine.start(() => classifyActivity(input()).human.state);
1402
+ return { id: s.id, intent: options.intent, startedAt: s.startedAt };
1403
+ },
1404
+ async stop() {
1405
+ activityEngine.stop();
1406
+ },
1407
+ // No activity event vocabulary is frozen — the design notes there is no
1408
+ // "Initial Activity Events" list at all — so naming events here would put
1409
+ // words in plugins that the freeze may contradict.
1410
+ subscribe() {
1411
+ throw unsupported("activity.subscribe");
1412
+ }
1413
+ };
1414
+ }
1415
+
1416
+ // src/device-state/index.ts
1417
+ function createDeviceState(collectors = {}) {
1418
+ const speedRef = { mps: null, at: 0 };
1419
+ return {
1420
+ deviceContext: createDeviceContextDomain(),
1421
+ connectivity: createConnectivityDomain(collectors),
1422
+ capability: createCapabilityDomain(collectors),
1423
+ interaction: createInteractionDomain(),
1424
+ spatial: createSpatialDomain(collectors, speedRef),
1425
+ visual: createVisualDomain(),
1426
+ activity: createActivityDomain(speedRef)
1427
+ };
1428
+ }
1429
+
1430
+ // src/camera/CameraTaskHost.tsx
1431
+ var import_react = require("react");
1432
+ var import_react_native2 = require("react-native");
1433
+ var import_expo_camera = require("expo-camera");
1434
+
1435
+ // src/camera/cameraTasks.ts
1436
+ function cameraError(code, message) {
1437
+ const err = new Error(message);
1438
+ err.code = code;
1439
+ return err;
1440
+ }
1441
+ var CameraTaskBroker = class {
1442
+ constructor() {
1443
+ this.task = null;
1444
+ this.listeners = /* @__PURE__ */ new Set();
1445
+ /** Set by the host while a camera is mounted and ready. */
1446
+ this.hostMounted = false;
1447
+ }
1448
+ current() {
1449
+ return this.task;
1450
+ }
1451
+ subscribe(fn) {
1452
+ this.listeners.add(fn);
1453
+ return () => this.listeners.delete(fn);
1454
+ }
1455
+ /**
1456
+ * Declare that a `CameraTaskHost` exists.
1457
+ *
1458
+ * Without it nothing will ever settle the promise, so a request must fail
1459
+ * IMMEDIATELY and say why. The alternative is a plugin awaiting forever,
1460
+ * which is the worst failure of the set: no error, no timeout, no camera,
1461
+ * and a conversation that simply stops.
1462
+ */
1463
+ setHostMounted(mounted) {
1464
+ this.hostMounted = mounted;
1465
+ if (!mounted) this.fail(cameraError("UNAVAILABLE", "The camera surface was dismissed before the task completed."));
1466
+ this.notify();
1467
+ }
1468
+ isHostMounted() {
1469
+ return this.hostMounted;
1470
+ }
1471
+ /** Enqueue and hand back the promise the plugin awaits. */
1472
+ run(kind, opts) {
1473
+ if (!this.hostMounted) {
1474
+ return Promise.reject(cameraError(
1475
+ "UNAVAILABLE",
1476
+ "No camera surface is mounted in this app, so the camera cannot be shown. The host must render <CameraTaskHost /> once, near the app root."
1477
+ ));
1478
+ }
1479
+ if (this.task) {
1480
+ return Promise.reject(cameraError(
1481
+ "BUSY",
1482
+ `The camera is already in use (${this.task.kind}). Only one camera task can run at a time.`
1483
+ ));
1484
+ }
1485
+ return new Promise((resolve, reject) => {
1486
+ this.task = { kind, opts, resolve, reject };
1487
+ this.notify();
1488
+ });
1489
+ }
1490
+ /** Settle the running task successfully and clear it. */
1491
+ complete(value) {
1492
+ const t = this.task;
1493
+ if (!t) return;
1494
+ this.task = null;
1495
+ this.notify();
1496
+ t.resolve(value);
1497
+ }
1498
+ /** Settle the running task with a failure and clear it. */
1499
+ fail(err) {
1500
+ const t = this.task;
1501
+ if (!t) return;
1502
+ this.task = null;
1503
+ this.notify();
1504
+ t.reject(err);
1505
+ }
1506
+ /**
1507
+ * The user backed out.
1508
+ *
1509
+ * A distinct code, because "the user chose not to" is not a malfunction and
1510
+ * a guide should say something different about it than about a broken lens.
1511
+ */
1512
+ cancel() {
1513
+ this.fail(cameraError("CANCELLED", "Cancelled \u2014 the camera was dismissed before anything was captured."));
1514
+ }
1515
+ notify() {
1516
+ for (const fn of this.listeners) {
1517
+ try {
1518
+ fn();
1519
+ } catch {
1520
+ }
1521
+ }
1522
+ }
1523
+ };
1524
+ var cameraTasks = new CameraTaskBroker();
1525
+
1526
+ // src/camera/CameraTaskHost.tsx
1527
+ var import_jsx_runtime = require("react/jsx-runtime");
1528
+ var styles = import_react_native2.StyleSheet.create({
1529
+ overlay: { ...import_react_native2.StyleSheet.absoluteFillObject, backgroundColor: "#000", zIndex: 9999 },
1530
+ hud: { flex: 1, justifyContent: "space-between", paddingVertical: 64, alignItems: "center" },
1531
+ hint: { color: "#fff", fontSize: 16, textAlign: "center", paddingHorizontal: 24 },
1532
+ cancel: { paddingHorizontal: 28, paddingVertical: 14, borderRadius: 24, backgroundColor: "rgba(255,255,255,0.18)" },
1533
+ cancelText: { color: "#fff", fontSize: 16, fontWeight: "600" }
1534
+ });
1535
+
1536
+ // src/index.ts
1537
+ function setupExpoProviders(opts) {
1538
+ (0, import_plugin_runtime2.setHapticsProvider)(expoHaptics);
1539
+ if (opts?.deviceProvider) (0, import_plugin_runtime2.setPluginNativeProvider)(opts.deviceProvider);
1540
+ (0, import_plugin_runtime2.setBundleStorage)(new ExpoBundleStorage({ indexKey: opts?.bundleIndexKey }));
1541
+ (0, import_ui.setClipboardProvider)({
1542
+ setString: (text) => ExpoClipboard.setStringAsync(text).then(() => {
1543
+ })
1544
+ });
1545
+ (0, import_plugin_runtime2.registerBundleModules)({
1546
+ "expo-web-browser": ExpoWebBrowser,
1547
+ "expo-linking": ExpoLinking,
1548
+ ...opts?.bundleModules || {}
1549
+ });
1550
+ (0, import_core.setAcsCacheStorage)({
1551
+ getItem: (k) => import_async_storage3.default.getItem(k),
1552
+ setItem: (k, v) => import_async_storage3.default.setItem(k, v)
1553
+ });
1554
+ return { attachmentCache: new ExpoAttachmentCache({ indexKey: opts?.attachmentIndexKey }) };
1555
+ }
1556
+
1557
+ // src/device/createDeviceProvider.ts
1558
+ var Haptics2 = __toESM(require("expo-haptics"));
1559
+ var ExpoLocation3 = __toESM(require("expo-location"));
1560
+ var ImagePicker = __toESM(require("expo-image-picker"));
1561
+ var Notifications = __toESM(require("expo-notifications"));
1562
+ var DocumentPicker = __toESM(require("expo-document-picker"));
1563
+ var FS = __toESM(require("expo-file-system"));
1564
+ var SQLite = __toESM(require("expo-sqlite"));
1565
+ var import_async_storage6 = __toESM(require("@react-native-async-storage/async-storage"));
1566
+
1567
+ // src/vision/index.ts
1568
+ var import_expo_modules_core = require("expo-modules-core");
1569
+ var import_expo = require("expo");
1570
+ var CameraPreview = (() => {
1571
+ try {
1572
+ return (0, import_expo.requireNativeView)("AdaVision");
1573
+ } catch {
1574
+ return null;
1575
+ }
1576
+ })();
1577
+ var native = (0, import_expo_modules_core.requireOptionalNativeModule)("AdaVision");
1578
+ function isSupported() {
1579
+ try {
1580
+ return native?.isSupported() ?? false;
1581
+ } catch {
1582
+ return false;
1583
+ }
1584
+ }
1585
+ function qualityById(id) {
1586
+ return native?.qualityById?.(id) ?? null;
1587
+ }
1588
+ async function readText(id, languages) {
1589
+ if (!native) throw new Error("ada-vision native module not present in this build");
1590
+ return native.readText(id, languages ?? null);
1591
+ }
1592
+ async function describe(id, maxLabels = 5) {
1593
+ if (!native) throw new Error("ada-vision native module not present in this build");
1594
+ return native.describe(id, maxLabels);
1595
+ }
1596
+ async function detectObjects(id, maxItems = 10, minConfidence = 0.25) {
1597
+ if (!native) throw new Error("ada-vision native module not present in this build");
1598
+ return native.detectObjects(id, maxItems, minConfidence);
1599
+ }
1600
+
1601
+ // src/device-bridge/actions/messaging.ts
1602
+ var SMS = __toESM(require("expo-sms"));
1603
+
1604
+ // src/device-bridge/actions/calendar-actions.ts
1605
+ var ExpoCalendar = __toESM(require("expo-calendar"));
1606
+
1607
+ // src/device-bridge/actions/navigation.ts
1608
+ var Linking = __toESM(require("expo-linking"));
1609
+ var import_react_native3 = require("react-native");
1610
+
1611
+ // src/device-bridge/collectors/health.ts
1612
+ var import_react_native4 = require("react-native");
1613
+
1614
+ // src/device-bridge/background.ts
1615
+ var TaskManager = __toESM(require("expo-task-manager"));
1616
+ var BackgroundFetch = __toESM(require("expo-background-fetch"));
1617
+
1618
+ // src/device-bridge/collectors/calendar.ts
1619
+ var ExpoCalendar2 = __toESM(require("expo-calendar"));
1620
+
1621
+ // src/device-bridge/collectors/contacts.ts
1622
+ var ExpoContacts = __toESM(require("expo-contacts"));
1623
+ var import_async_storage4 = __toESM(require("@react-native-async-storage/async-storage"));
1624
+
1625
+ // src/device-bridge/collectors/location.ts
1626
+ var location_exports = {};
1627
+ __export(location_exports, {
1628
+ collectCurrent: () => collectCurrent,
1629
+ getPosition: () => getPosition,
1630
+ hasPermission: () => hasPermission,
1631
+ requestPermission: () => requestPermission,
1632
+ watchPosition: () => watchPosition
1633
+ });
1634
+ var ExpoLocation2 = __toESM(require("expo-location"));
1635
+ async function requestPermission() {
1636
+ const { status: fg } = await ExpoLocation2.requestForegroundPermissionsAsync();
1637
+ if (fg !== "granted") return false;
1638
+ try {
1639
+ await ExpoLocation2.requestBackgroundPermissionsAsync();
1640
+ } catch {
1641
+ }
1642
+ return fg === "granted";
1643
+ }
1644
+ async function hasPermission() {
1645
+ const { status } = await ExpoLocation2.getForegroundPermissionsAsync();
1646
+ return status === "granted";
1647
+ }
1648
+ async function collectCurrent() {
1649
+ const location = await ExpoLocation2.getCurrentPositionAsync({
1650
+ accuracy: ExpoLocation2.Accuracy.Balanced
1651
+ });
1652
+ let place = "Current Location";
1653
+ let address = `${location.coords.latitude.toFixed(4)}, ${location.coords.longitude.toFixed(4)}`;
1654
+ let locationType = "unknown";
1655
+ try {
1656
+ const [geocoded] = await ExpoLocation2.reverseGeocodeAsync({
1657
+ latitude: location.coords.latitude,
1658
+ longitude: location.coords.longitude
1659
+ });
1660
+ if (geocoded) {
1661
+ place = geocoded.name || geocoded.street || place;
1662
+ address = [
1663
+ geocoded.streetNumber,
1664
+ geocoded.street,
1665
+ geocoded.city,
1666
+ geocoded.region
1667
+ ].filter(Boolean).join(", ") || address;
1668
+ locationType = classifyLocation(geocoded);
1669
+ }
1670
+ } catch {
1671
+ }
1672
+ return {
1673
+ ok: true,
1674
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1675
+ location: {
1676
+ place,
1677
+ address,
1678
+ lat: location.coords.latitude,
1679
+ lng: location.coords.longitude,
1680
+ type: locationType
1681
+ }
1682
+ };
1683
+ }
1684
+ async function ensurePermission() {
1685
+ if (await hasPermission()) return;
1686
+ const granted = await requestPermission();
1687
+ if (!granted) {
1688
+ throw new Error(
1689
+ "Location permission was not granted. Enable it for this app in iOS Settings > Privacy > Location Services."
1690
+ );
1691
+ }
1692
+ }
1693
+ async function getPosition(opts = {}) {
1694
+ await ensurePermission();
1695
+ const fix = await ExpoLocation2.getCurrentPositionAsync({
1696
+ accuracy: opts.accuracy === "high" ? ExpoLocation2.Accuracy.High : ExpoLocation2.Accuracy.Balanced
1697
+ });
1698
+ return toPosition(fix);
1699
+ }
1700
+ function toPosition(fix) {
1701
+ return {
1702
+ latitude: fix.coords.latitude,
1703
+ longitude: fix.coords.longitude,
1704
+ altitude: fix.coords.altitude ?? void 0,
1705
+ accuracy: nonNegative(fix.coords.accuracy),
1706
+ timestamp: fix.timestamp ?? Date.now(),
1707
+ speed: nonNegative(fix.coords.speed),
1708
+ course: nonNegative(fix.coords.heading)
1709
+ };
1710
+ }
1711
+ function nonNegative(v) {
1712
+ return typeof v === "number" && v >= 0 ? v : void 0;
1713
+ }
1714
+ function watchPosition(cb) {
1715
+ let subscription = null;
1716
+ let cancelled = false;
1717
+ (async () => {
1718
+ try {
1719
+ await ensurePermission();
1720
+ if (cancelled) return;
1721
+ subscription = await ExpoLocation2.watchPositionAsync(
1722
+ { accuracy: ExpoLocation2.Accuracy.Balanced },
1723
+ (fix) => cb(toPosition(fix))
1724
+ );
1725
+ if (cancelled) {
1726
+ subscription?.remove();
1727
+ subscription = null;
1728
+ }
1729
+ } catch (err) {
1730
+ console.warn("[location] watchPosition failed:", err?.message || String(err));
1731
+ }
1732
+ })();
1733
+ return () => {
1734
+ cancelled = true;
1735
+ subscription?.remove();
1736
+ subscription = null;
1737
+ };
1738
+ }
1739
+ function classifyLocation(geocoded) {
1740
+ const name = (geocoded.name || "").toLowerCase();
1741
+ const street = (geocoded.street || "").toLowerCase();
1742
+ if (name.includes("home") || name.includes("residence")) return "home";
1743
+ if (name.includes("office") || name.includes("workplace") || name.includes("tech park")) return "work";
1744
+ if (name.includes("school") || name.includes("elementary") || name.includes("university")) return "school";
1745
+ if (name.includes("gym") || name.includes("fitness")) return "fitness";
1746
+ if (name.includes("hospital") || name.includes("clinic") || name.includes("dental")) return "medical";
1747
+ return "other";
1748
+ }
1749
+
1750
+ // src/device-bridge/collectors/battery.ts
1751
+ var ExpoBattery2 = __toESM(require("expo-battery"));
1752
+
1753
+ // src/device-bridge/collectors/connectivity.ts
1754
+ var connectivity_exports = {};
1755
+ __export(connectivity_exports, {
1756
+ collectConnectivity: () => collectConnectivity
1757
+ });
1758
+ var ExpoNetwork = __toESM(require("expo-network"));
1759
+ async function collectConnectivity() {
1760
+ const networkState = await ExpoNetwork.getNetworkStateAsync();
1761
+ let type = "none";
1762
+ let wifiName;
1763
+ let cellularType;
1764
+ if (networkState.type === ExpoNetwork.NetworkStateType.WIFI) {
1765
+ type = "wifi";
1766
+ try {
1767
+ wifiName = await getWifiName();
1768
+ } catch {
1769
+ wifiName = void 0;
1770
+ }
1771
+ } else if (networkState.type === ExpoNetwork.NetworkStateType.CELLULAR) {
1772
+ type = "cellular";
1773
+ cellularType = getCellularGeneration();
1774
+ }
1775
+ return {
1776
+ ok: true,
1777
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1778
+ connectivity: {
1779
+ type,
1780
+ is_connected: networkState.isConnected ?? false,
1781
+ ...wifiName && { wifi_name: wifiName },
1782
+ ...cellularType && { cellular_type: cellularType }
1783
+ }
1784
+ };
1785
+ }
1786
+ async function getWifiName() {
1787
+ return void 0;
1788
+ }
1789
+ function getCellularGeneration() {
1790
+ return "LTE";
1791
+ }
1792
+
1793
+ // src/device-bridge/collectors/notifications.ts
1794
+ var ExpoNotifications = __toESM(require("expo-notifications"));
1795
+
1796
+ // src/device-bridge/collectors/appEngagement.ts
1797
+ var import_react_native5 = require("react-native");
1798
+ var import_async_storage5 = __toESM(require("@react-native-async-storage/async-storage"));
1799
+
1800
+ // src/device-bridge/collectors/camera.ts
1801
+ var import_expo_camera2 = require("expo-camera");
1802
+
1803
+ // src/device-bridge/biometrics.ts
1804
+ var biometrics_exports = {};
1805
+ __export(biometrics_exports, {
1806
+ authenticate: () => authenticate,
1807
+ capabilities: () => capabilities
1808
+ });
1809
+ var LocalAuthentication = __toESM(require("expo-local-authentication"));
1810
+ async function capabilities() {
1811
+ const [hasHardware, isEnrolled, types] = await Promise.all([
1812
+ LocalAuthentication.hasHardwareAsync(),
1813
+ LocalAuthentication.isEnrolledAsync(),
1814
+ LocalAuthentication.supportedAuthenticationTypesAsync()
1815
+ ]);
1816
+ const supportedTypes = types.map((t) => {
1817
+ if (t === LocalAuthentication.AuthenticationType.FINGERPRINT) return "fingerprint";
1818
+ if (t === LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION) return "face";
1819
+ if (t === LocalAuthentication.AuthenticationType.IRIS) return "iris";
1820
+ return "none";
1821
+ }).filter((t) => t !== "none");
1822
+ return { hasHardware, isEnrolled, supportedTypes };
1823
+ }
1824
+ async function authenticate(opts) {
1825
+ try {
1826
+ const res = await LocalAuthentication.authenticateAsync({
1827
+ promptMessage: opts.reason,
1828
+ cancelLabel: opts.cancelLabel,
1829
+ disableDeviceFallback: opts.fallbackToPasscode === false
1830
+ });
1831
+ if (res.success) return { success: true };
1832
+ return { success: false, error: res.error || "unknown" };
1833
+ } catch (e) {
1834
+ return { success: false, error: String(e?.message || e) };
1835
+ }
1836
+ }
1837
+
1838
+ // src/device-bridge/sharing.ts
1839
+ var sharing_exports = {};
1840
+ __export(sharing_exports, {
1841
+ isAvailable: () => isAvailable,
1842
+ shareFile: () => shareFile
1843
+ });
1844
+ var Sharing = __toESM(require("expo-sharing"));
1845
+ async function shareFile(fileUri, opts = {}) {
1846
+ try {
1847
+ const available = await Sharing.isAvailableAsync();
1848
+ if (!available) return { ok: false, error: "sharing_unavailable" };
1849
+ await Sharing.shareAsync(fileUri, opts);
1850
+ return { ok: true };
1851
+ } catch (e) {
1852
+ return { ok: false, error: String(e?.message || e) };
1853
+ }
1854
+ }
1855
+ async function isAvailable() {
1856
+ return Sharing.isAvailableAsync();
1857
+ }
1858
+
1859
+ // src/device-bridge/scanner.ts
1860
+ var scanner_exports = {};
1861
+ __export(scanner_exports, {
1862
+ CameraView: () => import_expo_camera3.CameraView,
1863
+ normalizeResult: () => normalizeResult,
1864
+ requestPermissions: () => requestPermissions,
1865
+ useCameraPermissions: () => import_expo_camera3.useCameraPermissions
1866
+ });
1867
+ var import_expo_camera3 = require("expo-camera");
1868
+ async function requestPermissions() {
1869
+ const { Camera: Camera2 } = await import("expo-camera");
1870
+ const { status } = await Camera2.requestCameraPermissionsAsync();
1871
+ return { granted: status === "granted", status };
1872
+ }
1873
+ function normalizeResult(r) {
1874
+ return { type: r.type, data: r.data };
1875
+ }
1876
+
1877
+ // src/device/createDeviceProvider.ts
1878
+ function getDeviceCookies() {
1879
+ try {
1880
+ return init_cookies(), __toCommonJS(cookies_exports);
1881
+ } catch {
1882
+ return null;
1883
+ }
1884
+ }
1885
+ function getDeviceNfc() {
1886
+ try {
1887
+ return init_nfc(), __toCommonJS(nfc_exports);
1888
+ } catch {
1889
+ return null;
1890
+ }
1891
+ }
1892
+ var CapabilityUnavailableError = class extends Error {
1893
+ constructor(capability, reason) {
1894
+ super(reason || `${capability} is not yet implemented. Coming in Phase 2.`);
1895
+ this.code = "UNAVAILABLE";
1896
+ this.name = "CapabilityUnavailableError";
1897
+ }
1898
+ };
1899
+ function stubApi(capability) {
1900
+ return new Proxy({}, {
1901
+ get(_target, prop) {
1902
+ if (typeof prop === "string") {
1903
+ return () => {
1904
+ throw new CapabilityUnavailableError(capability);
1905
+ };
1906
+ }
1907
+ }
1908
+ });
1909
+ }
1910
+ function createLocationAPI() {
1911
+ const ensurePermission2 = async () => {
1912
+ const existing = await ExpoLocation3.getForegroundPermissionsAsync();
1913
+ if (existing.status === "granted") return;
1914
+ const asked = await ExpoLocation3.requestForegroundPermissionsAsync();
1915
+ if (asked.status !== "granted") {
1916
+ throw new Error(
1917
+ "Location permission was not granted. Enable it for this app in Settings > Privacy > Location Services."
1918
+ );
1919
+ }
1920
+ };
1921
+ return {
1922
+ async getCurrent(opts) {
1923
+ await ensurePermission2();
1924
+ const fix = await ExpoLocation3.getCurrentPositionAsync({
1925
+ accuracy: opts?.accuracy === "high" ? ExpoLocation3.Accuracy.High : ExpoLocation3.Accuracy.Balanced
1926
+ });
1927
+ return {
1928
+ latitude: fix.coords.latitude,
1929
+ longitude: fix.coords.longitude,
1930
+ altitude: fix.coords.altitude ?? void 0
1931
+ };
1932
+ },
1933
+ watchPosition(cb) {
1934
+ let subscription = null;
1935
+ let cancelled = false;
1936
+ void (async () => {
1937
+ try {
1938
+ await ensurePermission2();
1939
+ if (cancelled) return;
1940
+ subscription = await ExpoLocation3.watchPositionAsync(
1941
+ { accuracy: ExpoLocation3.Accuracy.Balanced },
1942
+ (fix) => cb({ latitude: fix.coords.latitude, longitude: fix.coords.longitude })
1943
+ );
1944
+ if (cancelled) {
1945
+ subscription?.remove();
1946
+ subscription = null;
1947
+ }
1948
+ } catch (err) {
1949
+ console.warn("[location] watchPosition failed:", err?.message || String(err));
1950
+ }
1951
+ })();
1952
+ return () => {
1953
+ cancelled = true;
1954
+ subscription?.remove();
1955
+ subscription = null;
1956
+ };
1957
+ }
1958
+ };
1959
+ }
1960
+ function createCameraAPI() {
1961
+ const ensurePermission2 = async () => {
1962
+ const existing = await ImagePicker.getCameraPermissionsAsync();
1963
+ if (existing.granted) return;
1964
+ const asked = await ImagePicker.requestCameraPermissionsAsync();
1965
+ if (!asked.granted) {
1966
+ throw new Error(
1967
+ "Camera permission was not granted. Enable it for this app in Settings > Privacy > Camera."
1968
+ );
1969
+ }
1970
+ };
1971
+ return {
1972
+ async takePhoto(opts) {
1973
+ await ensurePermission2();
1974
+ const res = await ImagePicker.launchCameraAsync({
1975
+ quality: opts?.quality ?? 0.7,
1976
+ cameraType: opts?.facing === "front" ? ImagePicker.CameraType.front : ImagePicker.CameraType.back
1977
+ });
1978
+ if (res.canceled || !res.assets?.[0]) {
1979
+ throw new Error("No photo taken \u2014 the camera was dismissed.");
1980
+ }
1981
+ const a = res.assets[0];
1982
+ return { uri: a.uri, width: a.width, height: a.height };
1983
+ },
1984
+ async scanBarcode(opts) {
1985
+ throw new CapabilityUnavailableError(
1986
+ "camera.scanBarcode",
1987
+ "Use native.scanner.scanOnce() instead \u2014 scanning needs a mounted camera, which this call cannot provide. Same arguments, and it returns { data, format }." + (opts?.formats?.length ? " Pass your formats through to scanOnce." : "")
1988
+ );
1989
+ },
1990
+ async recordVideo(opts) {
1991
+ return cameraTasks.run("record", {
1992
+ maxDurationMs: opts?.maxDurationMs,
1993
+ withAudio: opts?.withAudio ?? false
1994
+ });
1995
+ },
1996
+ async pickImage(opts) {
1997
+ const existing = await ImagePicker.getMediaLibraryPermissionsAsync();
1998
+ if (!existing.granted) {
1999
+ const asked = await ImagePicker.requestMediaLibraryPermissionsAsync();
2000
+ if (!asked.granted) {
2001
+ throw new Error(
2002
+ "Photo library permission was not granted. Enable it for this app in Settings > Privacy > Photos."
2003
+ );
2004
+ }
2005
+ }
2006
+ const res = await ImagePicker.launchImageLibraryAsync({
2007
+ allowsMultipleSelection: !!opts?.multiple
2008
+ });
2009
+ if (res.canceled) return [];
2010
+ return (res.assets || []).map((a) => ({ uri: a.uri }));
2011
+ }
2012
+ };
2013
+ }
2014
+ var _pluginDbs = /* @__PURE__ */ new Map();
2015
+ function openPluginDb(file) {
2016
+ const existing = _pluginDbs.get(file);
2017
+ if (existing) return existing;
2018
+ const opened = SQLite.openDatabaseAsync(file);
2019
+ _pluginDbs.set(file, opened);
2020
+ return opened;
2021
+ }
2022
+ function sqlLeadingKeyword(sql) {
2023
+ let s = String(sql);
2024
+ for (; ; ) {
2025
+ const before = s;
2026
+ s = s.replace(/^\s+/, "");
2027
+ if (s.startsWith("--")) {
2028
+ const nl = s.indexOf("\n");
2029
+ s = nl === -1 ? "" : s.slice(nl + 1);
2030
+ } else if (s.startsWith("/*")) {
2031
+ const end = s.indexOf("*/");
2032
+ s = end === -1 ? "" : s.slice(end + 2);
2033
+ }
2034
+ if (s === before) break;
2035
+ }
2036
+ const m = s.match(/^[A-Za-z]+/);
2037
+ return m ? m[0].toUpperCase() : "";
2038
+ }
2039
+ function createStorageAPI(pluginId) {
2040
+ const ns = encodeURIComponent(pluginId);
2041
+ const key = (k) => `@plugin:${ns}:${k}`;
2042
+ const dbFile = `plugin-storage-${ns}.db`;
2043
+ return {
2044
+ get: (k) => import_async_storage6.default.getItem(key(k)),
2045
+ set: (k, v) => import_async_storage6.default.setItem(key(k), v),
2046
+ delete: (k) => import_async_storage6.default.removeItem(key(k)),
2047
+ db: {
2048
+ async execute(sql, params) {
2049
+ const verb = sqlLeadingKeyword(sql);
2050
+ if (verb === "ATTACH" || verb === "DETACH" || verb === "VACUUM") {
2051
+ throw new CapabilityUnavailableError(
2052
+ "storage.db",
2053
+ `SQL '${verb}' is not permitted: a plugin's storage is confined to its own database and cannot reach another file.`
2054
+ );
2055
+ }
2056
+ const db = await openPluginDb(dbFile);
2057
+ const returnsRows = verb === "SELECT" || verb === "PRAGMA" || verb === "WITH";
2058
+ if (returnsRows) {
2059
+ const rows = await db.getAllAsync(sql, params ?? []);
2060
+ return { rows, changes: 0 };
2061
+ }
2062
+ const res = await db.runAsync(sql, params ?? []);
2063
+ return { rows: [], changes: res.changes ?? 0 };
2064
+ }
2065
+ }
2066
+ };
2067
+ }
2068
+ function createNotificationsAPI() {
2069
+ return {
2070
+ async schedule({ title, body, trigger }) {
2071
+ const perm = await Notifications.getPermissionsAsync();
2072
+ if (!perm.granted) {
2073
+ const asked = await Notifications.requestPermissionsAsync();
2074
+ if (!asked.granted) {
2075
+ throw new Error(
2076
+ "Notification permission was not granted. Enable it for this app in Settings > Notifications."
2077
+ );
2078
+ }
2079
+ }
2080
+ const when = typeof trigger?.seconds === "number" ? { type: "timeInterval", seconds: trigger.seconds, repeats: false } : trigger?.date ? { type: "date", date: new Date(trigger.date) } : null;
2081
+ if (!when) {
2082
+ throw new Error("schedule() needs trigger.seconds or trigger.date.");
2083
+ }
2084
+ return Notifications.scheduleNotificationAsync({
2085
+ content: { title, body },
2086
+ trigger: when
2087
+ });
2088
+ },
2089
+ cancel: (id) => Notifications.cancelScheduledNotificationAsync(id),
2090
+ onReceived(cb) {
2091
+ const sub2 = Notifications.addNotificationReceivedListener((n) => {
2092
+ cb({
2093
+ id: n.request.identifier,
2094
+ title: n.request.content.title || "",
2095
+ body: n.request.content.body || "",
2096
+ data: n.request.content.data
2097
+ });
2098
+ });
2099
+ return () => sub2.remove();
2100
+ }
2101
+ };
2102
+ }
2103
+ function createFileSystemAPI(pluginId) {
2104
+ let _root = null;
2105
+ const rootDir = () => _root ?? (_root = new FS.Directory(FS.Paths.document, "plugin-files", pluginId));
2106
+ const resolve = (p) => {
2107
+ const root = rootDir();
2108
+ const file = new FS.File(root, p);
2109
+ if (!file.uri.startsWith(root.uri)) {
2110
+ throw new CapabilityUnavailableError(
2111
+ "fileSystem",
2112
+ `Path escapes the plugin's storage area: ${p}. Plugin files live under plugin-files/ and paths cannot traverse out of it.`
2113
+ );
2114
+ }
2115
+ return file;
2116
+ };
2117
+ return {
2118
+ async readFile(path) {
2119
+ const file = resolve(path);
2120
+ if (!file.exists) {
2121
+ throw new CapabilityUnavailableError(
2122
+ "fileSystem.readFile",
2123
+ `No such file: ${path}. Nothing was read.`
2124
+ );
2125
+ }
2126
+ return file.text();
2127
+ },
2128
+ async writeFile(path, content) {
2129
+ const file = resolve(path);
2130
+ const parent = file.parentDirectory;
2131
+ if (!parent.exists) parent.create({ intermediates: true });
2132
+ if (!file.exists) file.create();
2133
+ file.write(content);
2134
+ },
2135
+ async pickDocument(opts) {
2136
+ const res = await DocumentPicker.getDocumentAsync({
2137
+ type: opts?.types?.length ? opts.types : "*/*",
2138
+ copyToCacheDirectory: true
2139
+ });
2140
+ if (res.canceled || !res.assets?.[0]) {
2141
+ throw new Error("No document chosen \u2014 the picker was dismissed.");
2142
+ }
2143
+ const a = res.assets[0];
2144
+ return { uri: a.uri, name: a.name, size: a.size ?? 0 };
2145
+ }
2146
+ };
2147
+ }
2148
+ function createHapticsAPI() {
2149
+ return {
2150
+ impact(style) {
2151
+ const map = {
2152
+ light: Haptics2.ImpactFeedbackStyle.Light,
2153
+ medium: Haptics2.ImpactFeedbackStyle.Medium,
2154
+ heavy: Haptics2.ImpactFeedbackStyle.Heavy
2155
+ };
2156
+ Haptics2.impactAsync(map[style]);
2157
+ },
2158
+ notification(type) {
2159
+ const map = {
2160
+ success: Haptics2.NotificationFeedbackType.Success,
2161
+ warning: Haptics2.NotificationFeedbackType.Warning,
2162
+ error: Haptics2.NotificationFeedbackType.Error
2163
+ };
2164
+ Haptics2.notificationAsync(map[type]);
2165
+ },
2166
+ // Shorthand for notification('error'). Plugins call this; it was never
2167
+ // implemented, and optional chaining meant the failure the user was meant
2168
+ // to FEEL simply did not happen.
2169
+ error() {
2170
+ Haptics2.notificationAsync(Haptics2.NotificationFeedbackType.Error);
2171
+ },
2172
+ selection() {
2173
+ Haptics2.selectionAsync();
2174
+ }
2175
+ };
2176
+ }
2177
+ function createConnectivityAPI(reachabilityUrl) {
2178
+ let online = true;
2179
+ const listeners = /* @__PURE__ */ new Set();
2180
+ let interval = null;
2181
+ const checkOnline = async () => {
2182
+ if (!reachabilityUrl) return true;
2183
+ try {
2184
+ const res = await fetch(reachabilityUrl, {
2185
+ method: "HEAD",
2186
+ signal: AbortSignal.timeout(5e3)
2187
+ });
2188
+ return res.ok;
2189
+ } catch {
2190
+ return false;
2191
+ }
2192
+ };
2193
+ const startPolling = () => {
2194
+ if (!reachabilityUrl) return;
2195
+ if (interval) return;
2196
+ interval = setInterval(async () => {
2197
+ const newState = await checkOnline();
2198
+ if (newState !== online) {
2199
+ online = newState;
2200
+ listeners.forEach((cb) => cb(online));
2201
+ }
2202
+ }, 3e4);
2203
+ };
2204
+ return {
2205
+ isOnline() {
2206
+ return online;
2207
+ },
2208
+ onChange(cb) {
2209
+ listeners.add(cb);
2210
+ startPolling();
2211
+ return () => {
2212
+ listeners.delete(cb);
2213
+ if (listeners.size === 0 && interval) {
2214
+ clearInterval(interval);
2215
+ interval = null;
2216
+ }
2217
+ };
2218
+ }
2219
+ };
2220
+ }
2221
+ function createCookiesAPI() {
2222
+ return {
2223
+ async get(url) {
2224
+ const mod = getDeviceCookies();
2225
+ if (!mod) throw new CapabilityUnavailableError("cookies (native module not available \u2014 use a dev build)");
2226
+ const list = await mod.get(url, true);
2227
+ return list;
2228
+ },
2229
+ async clear(_url) {
2230
+ const mod = getDeviceCookies();
2231
+ if (!mod) throw new CapabilityUnavailableError("cookies (native module not available \u2014 use a dev build)");
2232
+ const r = await mod.clearAll();
2233
+ return { ok: r.ok };
2234
+ }
2235
+ };
2236
+ }
2237
+ function createBiometricsAPIv2() {
2238
+ return {
2239
+ capabilities: () => biometrics_exports.capabilities(),
2240
+ authenticate: (opts) => biometrics_exports.authenticate(opts)
2241
+ };
2242
+ }
2243
+ function createSharingAPI() {
2244
+ return {
2245
+ isAvailable: () => sharing_exports.isAvailable(),
2246
+ shareFile: (fileUri, opts) => sharing_exports.shareFile(fileUri, opts)
2247
+ };
2248
+ }
2249
+ function createScannerAPI() {
2250
+ return {
2251
+ requestPermissions: () => scanner_exports.requestPermissions(),
2252
+ // Raises the shared camera surface and settles on the first code read.
2253
+ // The plugin mounts nothing — that lifecycle is owned once, by
2254
+ // CameraTaskHost, instead of by every plugin that wants to scan.
2255
+ scanOnce: (opts) => cameraTasks.run("scan", {
2256
+ formats: opts?.formats,
2257
+ timeoutMs: opts?.timeoutMs
2258
+ })
2259
+ };
2260
+ }
2261
+ function createNfcAPI() {
2262
+ return {
2263
+ async isSupported() {
2264
+ const mod = getDeviceNfc();
2265
+ if (!mod) return false;
2266
+ return mod.isSupported();
2267
+ },
2268
+ async isEnabled() {
2269
+ const mod = getDeviceNfc();
2270
+ if (!mod) return false;
2271
+ return mod.isEnabled();
2272
+ },
2273
+ readOnce(timeoutMs) {
2274
+ const mod = getDeviceNfc();
2275
+ if (!mod) return Promise.resolve({ ok: false, error: "nfc_unavailable" });
2276
+ return mod.readOnce(timeoutMs);
2277
+ }
2278
+ };
2279
+ }
2280
+ function createBluetoothAPI() {
2281
+ const refuse = (method) => new CapabilityUnavailableError(
2282
+ `bluetooth.${method}`,
2283
+ "Bluetooth is not implemented in this build \u2014 no BLE native module is installed. The capability is declared so it fails by name rather than silently; nothing was scanned."
2284
+ );
2285
+ return {
2286
+ // These two answer `false` rather than throwing, because "is BLE usable?"
2287
+ // is exactly the question a plugin should be allowed to ask before
2288
+ // committing to a flow, and `false` is the true answer here.
2289
+ async isSupported() {
2290
+ return false;
2291
+ },
2292
+ async isEnabled() {
2293
+ return false;
2294
+ },
2295
+ // scan() THROWS, because there is no honest empty result: an empty device
2296
+ // list is a real finding ("nothing is advertising nearby") and returning
2297
+ // one would report a scan that never happened.
2298
+ async scan() {
2299
+ throw refuse("scan");
2300
+ }
2301
+ };
2302
+ }
2303
+ function createVisionAPI() {
2304
+ return {
2305
+ // "Can I see?" — true once the native module is present in the binary. On a
2306
+ // build without it, adaVision.isSupported() answers false, and assessQuality
2307
+ // below refuses cleanly (no crash), exactly the pre-module behaviour.
2308
+ async isSupported() {
2309
+ return isSupported();
2310
+ },
2311
+ // readText: on-device OCR on a published frame (native resolves the id →
2312
+ // pixels). [] = looked, found no text (a real finding); throws = could not
2313
+ // look (unknown/aged-out id). describe (VNClassifyImage) is the next pass.
2314
+ async readText(frameId, opts) {
2315
+ return readText(frameId, opts?.languages);
2316
+ },
2317
+ // describe: on-device labels (VNClassifyImage), not prose — the sentence is
2318
+ // the skill's job. [] = looked, recognised nothing.
2319
+ async describe(frameId, opts) {
2320
+ return describe(frameId, opts?.maxLabels ?? 5);
2321
+ },
2322
+ // detectObjects: on-device located objects (bundled detector), each with a
2323
+ // box — what a guidance loop reads to say WHERE a thing is, not just that the
2324
+ // scene contains it. [] = looked, found nothing; throws = could not look.
2325
+ async detectObjects(frameId, opts) {
2326
+ return detectObjects(frameId, opts?.maxItems ?? 10, opts?.minConfidence ?? 0.25);
2327
+ },
2328
+ // assessQuality: resolve the frame id to its LOCAL file, measure on-device,
2329
+ // and record the result back onto the frame so a later read of
2330
+ // VisualFrameRef.quality reflects it. Throwing here means "could not look"
2331
+ // (unknown/aged-out id, or no native module) — never a measured verdict.
2332
+ async assessQuality(frameId) {
2333
+ const q = qualityById(frameId);
2334
+ if (!q) {
2335
+ throw new CapabilityUnavailableError(
2336
+ "vision.assessQuality",
2337
+ `No frame for id "${frameId}" \u2014 unknown or aged out of the ring. This is "could not look", not a measurement.`
2338
+ );
2339
+ }
2340
+ return q;
2341
+ }
2342
+ };
2343
+ }
2344
+ function createDeviceProvider(config) {
2345
+ const connectivity = createConnectivityAPI(config?.reachabilityUrl);
2346
+ return {
2347
+ camera: createCameraAPI(),
2348
+ location: createLocationAPI(),
2349
+ // Only the per-plugin storageFor/fileSystemFor are exposed — NO shared
2350
+ // `storage`/`fileSystem` bucket. The gate scopes by pluginId and fails
2351
+ // closed without one, so a shared instance would be an unreachable
2352
+ // (and dangerous) fallback. Each plugin gets its own namespace + db file /
2353
+ // sandbox directory, or nothing.
2354
+ storageFor: (pluginId) => createStorageAPI(pluginId),
2355
+ biometrics: stubApi("biometrics"),
2356
+ biometricsV2: createBiometricsAPIv2(),
2357
+ notifications: createNotificationsAPI(),
2358
+ haptics: createHapticsAPI(),
2359
+ connectivity,
2360
+ fileSystemFor: (pluginId) => createFileSystemAPI(pluginId),
2361
+ cookies: createCookiesAPI(),
2362
+ sharing: createSharingAPI(),
2363
+ scanner: createScannerAPI(),
2364
+ nfc: createNfcAPI(),
2365
+ bluetooth: createBluetoothAPI(),
2366
+ vision: createVisionAPI()
2367
+ };
2368
+ }
2369
+
2370
+ // src/oauth/expoOAuth.tsx
2371
+ var import_react_native6 = require("react-native");
2372
+ var import_google_signin = require("@react-native-google-signin/google-signin");
2373
+ var AppleAuthentication = __toESM(require("expo-apple-authentication"));
2374
+ var import_jsx_runtime2 = require("react/jsx-runtime");
2375
+ var NOOP = () => {
2376
+ };
2377
+ function createExpoOAuthProvider(host = {}) {
2378
+ return {
2379
+ async signInWithGoogle(cfg) {
2380
+ const webClientId = cfg?.webClientId || host.googleWebClientId || "";
2381
+ const iosClientId = cfg?.iosClientId || host.googleIosClientId || "";
2382
+ const params = { webClientId };
2383
+ if (iosClientId) params.iosClientId = iosClientId;
2384
+ import_google_signin.GoogleSignin.configure(params);
2385
+ try {
2386
+ await import_google_signin.GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
2387
+ const result = await import_google_signin.GoogleSignin.signIn();
2388
+ return result?.data?.idToken || result?.idToken || null;
2389
+ } catch (err) {
2390
+ const code = err?.code;
2391
+ if (code === import_google_signin.statusCodes.SIGN_IN_CANCELLED || code === import_google_signin.statusCodes.IN_PROGRESS) {
2392
+ return null;
2393
+ }
2394
+ throw err;
2395
+ }
2396
+ },
2397
+ async signInWithApple() {
2398
+ try {
2399
+ const credential = await AppleAuthentication.signInAsync({
2400
+ requestedScopes: [
2401
+ AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
2402
+ AppleAuthentication.AppleAuthenticationScope.EMAIL
2403
+ ]
2404
+ });
2405
+ return credential.identityToken || null;
2406
+ } catch (err) {
2407
+ if (err?.code === "ERR_REQUEST_CANCELED") return null;
2408
+ throw err;
2409
+ }
2410
+ },
2411
+ async isAppleAvailable() {
2412
+ if (import_react_native6.Platform.OS !== "ios") return false;
2413
+ try {
2414
+ return await AppleAuthentication.isAvailableAsync();
2415
+ } catch {
2416
+ return false;
2417
+ }
2418
+ },
2419
+ renderAppleButton({ onPress, disabled, style }) {
2420
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2421
+ AppleAuthentication.AppleAuthenticationButton,
2422
+ {
2423
+ buttonType: AppleAuthentication.AppleAuthenticationButtonType.CONTINUE,
2424
+ buttonStyle: AppleAuthentication.AppleAuthenticationButtonStyle.BLACK,
2425
+ cornerRadius: 999,
2426
+ style,
2427
+ onPress: disabled ? NOOP : onPress
2428
+ }
2429
+ );
2430
+ }
2431
+ };
2432
+ }
2433
+
2434
+ // src/bootstrap.ts
2435
+ function bootstrapExpoAdas(opts) {
2436
+ const { attachmentCache } = setupExpoProviders({
2437
+ bundleModules: opts.bundleModules,
2438
+ attachmentIndexKey: opts.storageKeys?.attachmentIndex,
2439
+ bundleIndexKey: opts.storageKeys?.bundleIndex,
2440
+ deviceProvider: createDeviceProvider({ reachabilityUrl: opts.reachabilityUrl })
2441
+ });
2442
+ for (const plugin of opts.nativePlugins ?? []) {
2443
+ for (const id of plugin.ids) (0, import_plugin_runtime3.registerNativePlugin)(id, plugin.resolver);
2444
+ }
2445
+ const relay = opts.urls.relay;
2446
+ (0, import_ui2.setPluginWebViewExtraHosts)(() => relay ? [relay()] : []);
2447
+ (0, import_ui2.setOAuthProvider)(createExpoOAuthProvider({ googleIosClientId: opts.googleIosClientId }));
2448
+ if (opts.onReachabilityChange) {
2449
+ const onReach = opts.onReachabilityChange;
2450
+ (0, import_core2.setAcsReachabilityReporter)({ up: () => onReach(true), down: () => onReach(false) });
2451
+ }
2452
+ (0, import_plugin_runtime3.setDeviceStateProvider)(
2453
+ createDeviceState({ connectivity: connectivity_exports, location: location_exports })
2454
+ );
2455
+ (0, import_plugin_runtime3.registerPlatformDeviceTools)();
2456
+ (0, import_ui2.setUIActionNavigator)(opts.navigateToPlugin);
2457
+ (0, import_core2.initAdas)({
2458
+ coreUrl: opts.urls.core,
2459
+ ...opts.urls.voice ? { voiceUrl: opts.urls.voice } : {},
2460
+ ...opts.urls.consumerAuth ? { consumerAuthUrl: opts.urls.consumerAuth } : {},
2461
+ ...opts.onSession ? { onSession: opts.onSession } : {},
2462
+ ...opts.tenant ? { tenant: opts.tenant } : {},
2463
+ getUser: opts.getUser,
2464
+ tokenProvider: opts.tokenProvider,
2465
+ attachmentCache
2466
+ });
2467
+ return { attachmentCache };
2468
+ }
2469
+ // Annotate the CommonJS export names for ESM import in node:
2470
+ 0 && (module.exports = {
2471
+ bootstrapExpoAdas
2472
+ });
2473
+ //# sourceMappingURL=bootstrap.js.map