@ateam-ai-mobile/expo 0.1.5 → 0.1.8

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 (179) 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 +2991 -0
  8. package/dist/bootstrap.js.map +1 -0
  9. package/dist/bootstrap.mjs +66 -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-6LXF3JVX.mjs +96 -0
  14. package/dist/chunk-6LXF3JVX.mjs.map +1 -0
  15. package/dist/chunk-7FWYEHN5.mjs +203 -0
  16. package/dist/chunk-7FWYEHN5.mjs.map +1 -0
  17. package/dist/chunk-C7M5WAHA.mjs +1798 -0
  18. package/dist/chunk-C7M5WAHA.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-GF2MPTAB.mjs +647 -0
  22. package/dist/chunk-GF2MPTAB.mjs.map +1 -0
  23. package/dist/chunk-J6XRNX7P.mjs +19 -0
  24. package/dist/chunk-J6XRNX7P.mjs.map +1 -0
  25. package/dist/chunk-KOXF2FZM.mjs +92 -0
  26. package/dist/chunk-KOXF2FZM.mjs.map +1 -0
  27. package/dist/chunk-L4V7OCJ3.mjs +71 -0
  28. package/dist/chunk-L4V7OCJ3.mjs.map +1 -0
  29. package/dist/chunk-PCAEUX2N.mjs +67 -0
  30. package/dist/chunk-PCAEUX2N.mjs.map +1 -0
  31. package/dist/chunk-WMJKH4XE.mjs +34 -0
  32. package/dist/chunk-WMJKH4XE.mjs.map +1 -0
  33. package/dist/chunk-XQSY6MHP.mjs +213 -0
  34. package/dist/chunk-XQSY6MHP.mjs.map +1 -0
  35. package/dist/chunk-Z5AI2SXX.mjs +1810 -0
  36. package/dist/chunk-Z5AI2SXX.mjs.map +1 -0
  37. package/dist/createBridge.js +41 -10
  38. package/dist/createBridge.js.map +1 -1
  39. package/dist/createBridge.mjs +7 -1
  40. package/dist/createBridge.mjs.map +1 -1
  41. package/dist/device/createDeviceProvider.d.mts +23 -0
  42. package/dist/device/createDeviceProvider.d.ts +23 -0
  43. package/dist/device/createDeviceProvider.js +1228 -0
  44. package/dist/device/createDeviceProvider.js.map +1 -0
  45. package/dist/device/createDeviceProvider.mjs +19 -0
  46. package/dist/device/createDeviceProvider.mjs.map +1 -0
  47. package/dist/device-bridge/collectors/appEngagement.d.mts +10 -0
  48. package/dist/device-bridge/collectors/appEngagement.d.ts +10 -0
  49. package/dist/device-bridge/collectors/appEngagement.js +128 -0
  50. package/dist/device-bridge/collectors/appEngagement.js.map +1 -0
  51. package/dist/device-bridge/collectors/appEngagement.mjs +12 -0
  52. package/dist/device-bridge/collectors/appEngagement.mjs.map +1 -0
  53. package/dist/device-bridge/collectors/health.d.mts +24 -0
  54. package/dist/device-bridge/collectors/health.d.ts +24 -0
  55. package/dist/device-bridge/collectors/health.js +238 -0
  56. package/dist/device-bridge/collectors/health.js.map +1 -0
  57. package/dist/device-bridge/collectors/health.mjs +18 -0
  58. package/dist/device-bridge/collectors/health.mjs.map +1 -0
  59. package/dist/device-bridge/cookies.d.mts +49 -0
  60. package/dist/device-bridge/cookies.d.ts +49 -0
  61. package/dist/device-bridge/cookies.js +90 -0
  62. package/dist/device-bridge/cookies.js.map +1 -0
  63. package/dist/device-bridge/cookies.mjs +14 -0
  64. package/dist/device-bridge/cookies.mjs.map +1 -0
  65. package/dist/device-bridge/index.d.mts +495 -0
  66. package/dist/device-bridge/index.d.ts +495 -0
  67. package/dist/device-bridge/index.js +2121 -0
  68. package/dist/device-bridge/index.js.map +1 -0
  69. package/dist/device-bridge/index.mjs +34 -0
  70. package/dist/device-bridge/index.mjs.map +1 -0
  71. package/dist/device-bridge/nfc.d.mts +30 -0
  72. package/dist/device-bridge/nfc.d.ts +30 -0
  73. package/dist/device-bridge/nfc.js +109 -0
  74. package/dist/device-bridge/nfc.js.map +1 -0
  75. package/dist/device-bridge/nfc.mjs +14 -0
  76. package/dist/device-bridge/nfc.mjs.map +1 -0
  77. package/dist/index.d.mts +509 -18
  78. package/dist/index.d.ts +509 -18
  79. package/dist/index.js +1706 -6
  80. package/dist/index.js.map +1 -1
  81. package/dist/index.mjs +24 -194
  82. package/dist/index.mjs.map +1 -1
  83. package/dist/maps/index.d.mts +56 -0
  84. package/dist/maps/index.d.ts +56 -0
  85. package/dist/maps/index.js +95 -0
  86. package/dist/maps/index.js.map +1 -0
  87. package/dist/maps/index.mjs +17 -0
  88. package/dist/maps/index.mjs.map +1 -0
  89. package/dist/oauth/expoOAuth.d.mts +18 -0
  90. package/dist/oauth/expoOAuth.d.ts +18 -0
  91. package/dist/oauth/expoOAuth.js +102 -0
  92. package/dist/oauth/expoOAuth.js.map +1 -0
  93. package/dist/oauth/expoOAuth.mjs +8 -0
  94. package/dist/oauth/expoOAuth.mjs.map +1 -0
  95. package/dist/types-BRanJYTn.d.mts +138 -0
  96. package/dist/types-BRanJYTn.d.ts +138 -0
  97. package/dist/vision/index.d.mts +83 -0
  98. package/dist/vision/index.d.ts +83 -0
  99. package/dist/vision/index.js +101 -0
  100. package/dist/vision/index.js.map +1 -0
  101. package/dist/vision/index.mjs +28 -0
  102. package/dist/vision/index.mjs.map +1 -0
  103. package/expo-module.config.json +9 -0
  104. package/ios/AdaMaps/AdaMapsModule.swift +180 -0
  105. package/ios/AdaMaps.podspec +25 -0
  106. package/ios/AdaVision.podspec +32 -0
  107. package/ios/AdaVisionModule.swift +486 -0
  108. package/ios/Resources/yolov8n-oiv7.mlmodelc/analytics/coremldata.bin +0 -0
  109. package/ios/Resources/yolov8n-oiv7.mlmodelc/coremldata.bin +0 -0
  110. package/ios/Resources/yolov8n-oiv7.mlmodelc/metadata.json +773 -0
  111. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/analytics/coremldata.bin +0 -0
  112. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/coremldata.bin +0 -0
  113. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/model.mil +720 -0
  114. package/ios/Resources/yolov8n-oiv7.mlmodelc/model0/weights/weight.bin +0 -0
  115. package/ios/Resources/yolov8n-oiv7.mlmodelc/model1/coremldata.bin +0 -0
  116. package/package.json +113 -7
  117. package/src/args.ts +56 -0
  118. package/src/bootstrap.ts +159 -0
  119. package/src/camera/CameraTaskHost.tsx +175 -0
  120. package/src/camera/cameraTasks.ts +129 -0
  121. package/src/createBridge.ts +3 -1
  122. package/src/device/createDeviceProvider.ts +917 -0
  123. package/src/device-bridge/actions/calendar-actions.ts +217 -0
  124. package/src/device-bridge/actions/dnd.ts +74 -0
  125. package/src/device-bridge/actions/health-actions.ts +58 -0
  126. package/src/device-bridge/actions/index.ts +12 -0
  127. package/src/device-bridge/actions/messaging.ts +74 -0
  128. package/src/device-bridge/actions/navigation.ts +88 -0
  129. package/src/device-bridge/actions/queue-poller.ts +151 -0
  130. package/src/device-bridge/background.ts +137 -0
  131. package/src/device-bridge/biometrics.ts +64 -0
  132. package/src/device-bridge/capabilities.ts +218 -0
  133. package/src/device-bridge/collectors/appEngagement.ts +120 -0
  134. package/src/device-bridge/collectors/battery.ts +83 -0
  135. package/src/device-bridge/collectors/calendar.ts +162 -0
  136. package/src/device-bridge/collectors/camera.ts +27 -0
  137. package/src/device-bridge/collectors/connectivity.ts +60 -0
  138. package/src/device-bridge/collectors/contacts.ts +200 -0
  139. package/src/device-bridge/collectors/health.ts +299 -0
  140. package/src/device-bridge/collectors/index.ts +12 -0
  141. package/src/device-bridge/collectors/location.ts +236 -0
  142. package/src/device-bridge/collectors/mood.ts +141 -0
  143. package/src/device-bridge/collectors/notifications.ts +70 -0
  144. package/src/device-bridge/cookies.ts +89 -0
  145. package/src/device-bridge/dynamic-connector.ts +422 -0
  146. package/src/device-bridge/index.ts +467 -0
  147. package/src/device-bridge/nfc.ts +85 -0
  148. package/src/device-bridge/plugin.ts +71 -0
  149. package/src/device-bridge/relay-client.ts +237 -0
  150. package/src/device-bridge/scanner.ts +42 -0
  151. package/src/device-bridge/sharing.ts +35 -0
  152. package/src/device-bridge/types.ts +326 -0
  153. package/src/device-state/activityClassifier.ts +151 -0
  154. package/src/device-state/activityEngine.ts +252 -0
  155. package/src/device-state/collectors.ts +35 -0
  156. package/src/device-state/domains/activity.ts +93 -0
  157. package/src/device-state/domains/capability.ts +60 -0
  158. package/src/device-state/domains/connectivity.ts +60 -0
  159. package/src/device-state/domains/deviceContext.ts +57 -0
  160. package/src/device-state/domains/interaction.ts +60 -0
  161. package/src/device-state/domains/spatial.ts +367 -0
  162. package/src/device-state/domains/visual.ts +121 -0
  163. package/src/device-state/events.ts +49 -0
  164. package/src/device-state/headingSource.ts +119 -0
  165. package/src/device-state/index.ts +78 -0
  166. package/src/device-state/quality.ts +60 -0
  167. package/src/device-state/replay.ts +285 -0
  168. package/src/device-state/spatialEvents.ts +300 -0
  169. package/src/device-state/turnDetector.ts +121 -0
  170. package/src/device-state/visualEngine.ts +341 -0
  171. package/src/geo.ts +23 -0
  172. package/src/haptics.ts +4 -0
  173. package/src/index.ts +37 -0
  174. package/src/maps/index.ts +81 -0
  175. package/src/maps/normalize.ts +225 -0
  176. package/src/oauth/expoOAuth.tsx +113 -0
  177. package/src/vision/analysis.js +80 -0
  178. package/src/vision/index.ts +146 -0
  179. package/src/vision/ring.js +35 -0
package/dist/index.js CHANGED
@@ -30,10 +30,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ CameraTaskHost: () => CameraTaskHost,
33
34
  ExpoAttachmentCache: () => ExpoAttachmentCache,
34
35
  ExpoBundleStorage: () => ExpoBundleStorage,
36
+ IMPLEMENTED_DOMAINS: () => IMPLEMENTED_DOMAINS,
37
+ cameraTasks: () => cameraTasks,
38
+ createDeviceState: () => createDeviceState,
39
+ createReplayDeviceState: () => createReplayDeviceState,
35
40
  expoHaptics: () => expoHaptics,
36
- setupExpoProviders: () => setupExpoProviders
41
+ parseWalkJsonl: () => parseWalkJsonl,
42
+ setupExpoProviders: () => setupExpoProviders,
43
+ visualEngine: () => visualEngine
37
44
  });
38
45
  module.exports = __toCommonJS(index_exports);
39
46
  var ExpoWebBrowser = __toESM(require("expo-web-browser"));
@@ -41,7 +48,7 @@ var ExpoLinking = __toESM(require("expo-linking"));
41
48
  var ExpoClipboard = __toESM(require("expo-clipboard"));
42
49
  var import_async_storage3 = __toESM(require("@react-native-async-storage/async-storage"));
43
50
  var import_core = require("@ateam-ai-mobile/core");
44
- var import_plugin_runtime = require("@ateam-ai-mobile/plugin-runtime");
51
+ var import_plugin_runtime2 = require("@ateam-ai-mobile/plugin-runtime");
45
52
  var import_ui = require("@ateam-ai-mobile/ui");
46
53
 
47
54
  // src/haptics.ts
@@ -68,6 +75,11 @@ var expoHaptics = {
68
75
  selection() {
69
76
  Haptics.selectionAsync().catch(() => {
70
77
  });
78
+ },
79
+ // Shorthand for notification('error') — the form plugins actually call.
80
+ error() {
81
+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error).catch(() => {
82
+ });
71
83
  }
72
84
  };
73
85
 
@@ -206,15 +218,1696 @@ var ExpoAttachmentCache = class {
206
218
  }
207
219
  };
208
220
 
221
+ // src/device-state/domains/deviceContext.ts
222
+ var ExpoBattery = __toESM(require("expo-battery"));
223
+
224
+ // src/device-state/quality.ts
225
+ var import_plugin_runtime = require("@ateam-ai-mobile/plugin-runtime");
226
+ var FRESH_MS = 1e4;
227
+ var AGING_MS = 6e4;
228
+ function qualityFrom(observedAt, confidence) {
229
+ const ageMs = Date.now() - observedAt;
230
+ return {
231
+ freshness: {
232
+ state: ageMs < FRESH_MS ? "fresh" : ageMs < AGING_MS ? "aging" : "stale",
233
+ observedAt,
234
+ ageMs
235
+ },
236
+ ...confidence ? { confidence } : {}
237
+ };
238
+ }
239
+ function qualityUnknown() {
240
+ return { freshness: (0, import_plugin_runtime.neverObserved)() };
241
+ }
242
+ function unsupported(what) {
243
+ const err = new Error(
244
+ `${what} is not implemented in this build \u2014 the native engine behind it does not exist yet.`
245
+ );
246
+ err.code = "UNSUPPORTED";
247
+ return err;
248
+ }
249
+
250
+ // src/device-state/events.ts
251
+ function stateEvent(domain, name, payload, timestamp = Date.now()) {
252
+ return payload === void 0 ? { domain, name, timestamp } : { domain, name, timestamp, payload };
253
+ }
254
+ function listenerSet() {
255
+ const listeners = /* @__PURE__ */ new Set();
256
+ return {
257
+ add(fn) {
258
+ listeners.add(fn);
259
+ return { unsubscribe: () => {
260
+ listeners.delete(fn);
261
+ } };
262
+ },
263
+ emit(event) {
264
+ for (const fn of listeners) {
265
+ try {
266
+ fn(event);
267
+ } catch {
268
+ }
269
+ }
270
+ }
271
+ };
272
+ }
273
+
274
+ // src/device-state/domains/deviceContext.ts
275
+ function createDeviceContextDomain() {
276
+ return {
277
+ async getSnapshot() {
278
+ const observedAt = Date.now();
279
+ try {
280
+ const [level, state, lowPower] = await Promise.all([
281
+ ExpoBattery.getBatteryLevelAsync(),
282
+ ExpoBattery.getBatteryStateAsync(),
283
+ ExpoBattery.isLowPowerModeEnabledAsync()
284
+ ]);
285
+ return {
286
+ power: {
287
+ // expo-battery returns -1 when it cannot tell. That is not a level.
288
+ batteryLevel: typeof level === "number" && level >= 0 ? level : null,
289
+ charging: state === ExpoBattery.BatteryState.CHARGING || state === ExpoBattery.BatteryState.FULL,
290
+ lowPowerMode: lowPower
291
+ },
292
+ // No Expo API for either. iOS needs ProcessInfo.thermalState, Android
293
+ // PowerManager.getThermalStatus — a native module that does not exist.
294
+ thermal: { state: "unknown" },
295
+ resources: { memoryPressure: "unknown", storagePressure: "unknown" },
296
+ quality: qualityFrom(observedAt)
297
+ };
298
+ } catch {
299
+ return {
300
+ power: { batteryLevel: null, charging: null, lowPowerMode: null },
301
+ thermal: { state: "unknown" },
302
+ resources: { memoryPressure: "unknown", storagePressure: "unknown" },
303
+ quality: qualityUnknown()
304
+ };
305
+ }
306
+ },
307
+ // Real events, not a placeholder: expo-battery exposes native listeners,
308
+ // so a plugin that subscribes genuinely hears about a change rather than
309
+ // sitting on a subscription that can never fire. Nudges without a payload:
310
+ // no Device Context payload schema is decided, so the subscriber re-reads.
311
+ subscribe(listener) {
312
+ const subs = [
313
+ ExpoBattery.addBatteryLevelListener(() => listener(stateEvent("deviceContext", "batteryLevelChanged"))),
314
+ ExpoBattery.addBatteryStateListener(() => listener(stateEvent("deviceContext", "chargingChanged")))
315
+ ];
316
+ return { unsubscribe: () => subs.forEach((x) => x?.remove?.()) };
317
+ }
318
+ };
319
+ }
320
+
321
+ // src/device-state/domains/connectivity.ts
322
+ function createConnectivityDomain(collectors) {
323
+ return {
324
+ async getSnapshot() {
325
+ const observedAt = Date.now();
326
+ try {
327
+ if (!collectors.connectivity) throw unsupported("connectivity collector");
328
+ const data = await collectors.connectivity.collectConnectivity();
329
+ const online = data?.is_connected === true;
330
+ const type = String(data?.type || "").toLowerCase();
331
+ return {
332
+ reachability: data?.is_connected == null ? "unknown" : online ? "online" : "offline",
333
+ transport: type === "wifi" ? "wifi" : type === "cellular" ? "cellular" : type === "ethernet" ? "ethernet" : online ? "other" : data?.is_connected === false ? "none" : "unknown",
334
+ // All four below need measurement nobody takes yet. `unknown` is the
335
+ // designed answer — "return unknown rather than stale precision".
336
+ qualityClass: "unknown",
337
+ stability: "unknown",
338
+ latencyMs: null,
339
+ bandwidthClass: "unknown",
340
+ metered: null,
341
+ constrained: null,
342
+ quality: qualityFrom(observedAt)
343
+ };
344
+ } catch {
345
+ return {
346
+ reachability: "unknown",
347
+ transport: "unknown",
348
+ qualityClass: "unknown",
349
+ stability: "unknown",
350
+ latencyMs: null,
351
+ bandwidthClass: "unknown",
352
+ metered: null,
353
+ constrained: null,
354
+ quality: qualityUnknown()
355
+ };
356
+ }
357
+ },
358
+ // Intent selects a native sampling strategy — latency probes, quality
359
+ // classification. Nothing here samples anything, so accepting an intent
360
+ // would be accepting an instruction we do not carry out.
361
+ async start() {
362
+ throw unsupported("connectivity.start");
363
+ },
364
+ async stop() {
365
+ throw unsupported("connectivity.stop");
366
+ },
367
+ // A subscription that can never fire is worse than none: the caller
368
+ // reasonably reads silence as "nothing changed".
369
+ subscribe() {
370
+ throw unsupported("connectivity.subscribe");
371
+ }
372
+ };
373
+ }
374
+
375
+ // src/device-state/domains/capability.ts
376
+ function statusFrom(granted) {
377
+ return {
378
+ support: "unknown",
379
+ permission: granted === null ? "unknown" : granted ? "granted" : "denied",
380
+ availability: "unknown"
381
+ };
382
+ }
383
+ var UNKNOWN_STATUS = {
384
+ support: "unknown",
385
+ permission: "unknown",
386
+ availability: "unknown"
387
+ };
388
+ function createCapabilityDomain(collectors) {
389
+ return {
390
+ async getSnapshot() {
391
+ const observedAt = Date.now();
392
+ const locationGranted = collectors.location ? await collectors.location.hasPermission().catch(() => null) : null;
393
+ return {
394
+ // Only location has a real reader today. The rest are declared by the
395
+ // contract and answered honestly rather than omitted.
396
+ camera: UNKNOWN_STATUS,
397
+ microphone: UNKNOWN_STATUS,
398
+ location: {
399
+ ...statusFrom(locationGranted),
400
+ // iOS 14+ distinguishes precise from approximate; nothing reads it.
401
+ precision: "unknown",
402
+ backgroundPermission: "unknown"
403
+ },
404
+ motion: UNKNOWN_STATUS,
405
+ bluetooth: UNKNOWN_STATUS,
406
+ uwb: UNKNOWN_STATUS,
407
+ nfc: UNKNOWN_STATUS,
408
+ quality: qualityFrom(observedAt)
409
+ };
410
+ },
411
+ // No OS permission-change stream is wired. Same reasoning as connectivity:
412
+ // silence would be indistinguishable from stability.
413
+ subscribe() {
414
+ throw unsupported("capability.subscribe");
415
+ }
416
+ };
417
+ }
418
+
419
+ // src/device-state/domains/interaction.ts
420
+ var import_react_native = require("react-native");
421
+ function createInteractionDomain() {
422
+ const mapState = (s) => s === "active" ? "foreground" : s === "background" ? "background" : s === "inactive" ? "inactive" : "unknown";
423
+ return {
424
+ async getSnapshot() {
425
+ const observedAt = Date.now();
426
+ return {
427
+ lifecycle: {
428
+ appState: mapState(import_react_native.AppState.currentState),
429
+ screenOn: null,
430
+ userActive: null,
431
+ idleDurationMs: null
432
+ },
433
+ audio: {
434
+ captureActive: null,
435
+ playbackActive: null,
436
+ route: "unknown",
437
+ interruption: "unknown"
438
+ },
439
+ // The voice block is OMITTED rather than filled with nulls: the design
440
+ // says a platform that cannot report voice session state leaves the
441
+ // group out instead of guessing `false` for each field. The app's own
442
+ // voice store knows this, but it is not reachable from the SDK.
443
+ quality: qualityFrom(observedAt)
444
+ };
445
+ },
446
+ // Real: AppState genuinely emits on every foreground/background change,
447
+ // which is the one part of this domain that works.
448
+ subscribe(listener) {
449
+ const sub2 = import_react_native.AppState.addEventListener("change", (next) => {
450
+ listener(stateEvent("interaction", "appStateChanged", { appState: mapState(next) }));
451
+ });
452
+ return { unsubscribe: () => sub2.remove() };
453
+ }
454
+ };
455
+ }
456
+
457
+ // src/device-state/headingSource.ts
458
+ var ExpoLocation = __toESM(require("expo-location"));
459
+
460
+ // src/device-state/turnDetector.ts
461
+ function signedDelta(a, b) {
462
+ return (b - a + 540) % 360 - 180;
463
+ }
464
+ var TurnDetector = class {
465
+ constructor(opts = {}) {
466
+ /** The heading currently treated as "straight ahead". */
467
+ this.refDeg = null;
468
+ this.stableSince = 0;
469
+ this.lastTurn = null;
470
+ this.minTurnDeg = opts.minTurnDeg ?? 35;
471
+ this.stableDeg = opts.stableDeg ?? 12;
472
+ this.stableMs = opts.stableMs ?? 2500;
473
+ }
474
+ /** Feed one compass reading. `null` degrees means the compass said nothing. */
475
+ push(deg, now) {
476
+ if (deg === null) return null;
477
+ if (this.refDeg === null) {
478
+ this.refDeg = deg;
479
+ this.stableSince = now;
480
+ return null;
481
+ }
482
+ const delta = signedDelta(this.refDeg, deg);
483
+ if (Math.abs(delta) >= this.minTurnDeg) {
484
+ this.lastTurn = { deg: Math.round(delta), timestamp: now };
485
+ this.refDeg = deg;
486
+ this.stableSince = now;
487
+ return this.lastTurn;
488
+ }
489
+ if (Math.abs(delta) > this.stableDeg) {
490
+ this.stableSince = now;
491
+ return null;
492
+ }
493
+ if (now - this.stableSince >= this.stableMs) {
494
+ this.refDeg = deg;
495
+ this.stableSince = now;
496
+ }
497
+ return null;
498
+ }
499
+ /**
500
+ * The most recent completed turn, or null if none this session.
501
+ *
502
+ * It does NOT expire on its own: the age is derivable from `timestamp`, and
503
+ * "recent enough to mention" is a product judgement this layer must not make
504
+ * on the caller's behalf.
505
+ */
506
+ last() {
507
+ return this.lastTurn;
508
+ }
509
+ reset() {
510
+ this.refDeg = null;
511
+ this.stableSince = 0;
512
+ this.lastTurn = null;
513
+ }
514
+ };
515
+
516
+ // src/device-state/headingSource.ts
517
+ var latest = null;
518
+ var sub = null;
519
+ var opening = null;
520
+ var owners = /* @__PURE__ */ new Set();
521
+ var turns = new TurnDetector();
522
+ var turnListeners = listenerSet();
523
+ function startHeading(owner) {
524
+ owners.add(owner);
525
+ if (sub) return Promise.resolve();
526
+ opening ?? (opening = open().finally(() => {
527
+ opening = null;
528
+ }));
529
+ return opening;
530
+ }
531
+ async function open() {
532
+ try {
533
+ const s = await ExpoLocation.watchHeadingAsync((h) => {
534
+ if (!owners.size) return;
535
+ const raw = h.trueHeading >= 0 ? h.trueHeading : h.magHeading;
536
+ const deg = typeof raw === "number" && raw >= 0 ? raw : null;
537
+ const cal = typeof h.accuracy === "number" && h.accuracy >= 0 ? h.accuracy : null;
538
+ const now = Date.now();
539
+ latest = { headingDeg: deg, calibration: cal, timestamp: now };
540
+ const turn = turns.push(deg, now);
541
+ if (turn) turnListeners.emit(turn);
542
+ });
543
+ if (!owners.size) {
544
+ s.remove();
545
+ return;
546
+ }
547
+ sub = s;
548
+ } catch {
549
+ sub = null;
550
+ }
551
+ }
552
+ function stopHeading(owner) {
553
+ owners.delete(owner);
554
+ if (owners.size) return;
555
+ sub?.remove();
556
+ sub = null;
557
+ latest = null;
558
+ turns.reset();
559
+ }
560
+ function onTurn(fn) {
561
+ return turnListeners.add(fn);
562
+ }
563
+ function currentHeading() {
564
+ return latest ? { headingDeg: latest.headingDeg } : null;
565
+ }
566
+ function currentHeadingDetail() {
567
+ return latest;
568
+ }
569
+ function lastMeaningfulTurn() {
570
+ return turns.last();
571
+ }
572
+
573
+ // src/geo.ts
574
+ function distanceOf(path) {
575
+ const R = 6371e3;
576
+ let total = 0;
577
+ for (let i = 1; i < path.length; i++) {
578
+ const a = path[i - 1], b = path[i];
579
+ const dLat = (b.latitude - a.latitude) * Math.PI / 180;
580
+ const dLon = (b.longitude - a.longitude) * Math.PI / 180;
581
+ const la1 = a.latitude * Math.PI / 180, la2 = b.latitude * Math.PI / 180;
582
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(la1) * Math.cos(la2) * Math.sin(dLon / 2) ** 2;
583
+ total += 2 * R * Math.asin(Math.sqrt(h));
584
+ }
585
+ return Math.round(total);
586
+ }
587
+
588
+ // src/device-state/spatialEvents.ts
589
+ var STATIONARY_MPS = 0.4;
590
+ function movementStateOf(speedMps) {
591
+ return speedMps === null ? "unknown" : speedMps < STATIONARY_MPS ? "stationary" : "moving";
592
+ }
593
+ function fixConfidence(accuracyM) {
594
+ return accuracyM === null ? "unknown" : accuracyM <= 10 ? "high" : accuracyM <= 50 ? "medium" : "low";
595
+ }
596
+ var SPATIAL_EVENT_PROFILES = {
597
+ navigation: { movingHoldMs: 3e3, stoppedHoldMs: 5e3, confidenceHoldMs: 3e3, minMoveM: 10 },
598
+ fitness: { movingHoldMs: 3e3, stoppedHoldMs: 5e3, confidenceHoldMs: 5e3, minMoveM: 10 },
599
+ preciseLocate: { movingHoldMs: 2e3, stoppedHoldMs: 3e3, confidenceHoldMs: 2e3, minMoveM: 3 },
600
+ geofence: { movingHoldMs: 1e4, stoppedHoldMs: 3e4, confidenceHoldMs: 1e4, minMoveM: 25 },
601
+ lowPowerTracking: { movingHoldMs: 1e4, stoppedHoldMs: 3e4, confidenceHoldMs: 1e4, minMoveM: 50 }
602
+ };
603
+ function moveThresholdM(anchor, fix) {
604
+ const a = anchor.accuracyM ?? 0, b = fix.accuracyM ?? 0;
605
+ return 2 * Math.sqrt(a * a + b * b);
606
+ }
607
+ function spatialEventProfile(intent) {
608
+ return SPATIAL_EVENT_PROFILES[intent] ?? SPATIAL_EVENT_PROFILES.navigation;
609
+ }
610
+ var RANK = { high: 3, medium: 2, low: 1 };
611
+ var MIN_FIXES = 2;
612
+ function extend(run, state, fixAt2, now) {
613
+ if (!run || run.state !== state) return { state, since: now, fixAt: fixAt2, fixes: fixAt2 === null ? 0 : 1 };
614
+ if (fixAt2 !== null && fixAt2 !== run.fixAt) {
615
+ run.fixAt = fixAt2;
616
+ run.fixes++;
617
+ }
618
+ return run;
619
+ }
620
+ var settled = (run, now, holdMs) => run.fixes >= MIN_FIXES && now - run.since >= holdMs;
621
+ var fixAt = (s) => s.position?.timestamp ?? null;
622
+ var SpatialEventDetector = class {
623
+ constructor(profile = SPATIAL_EVENT_PROFILES.navigation) {
624
+ /** The movement state last settled on. Only MEASURED states settle. */
625
+ this.movement = "unknown";
626
+ this.run = null;
627
+ /** The completed turn already on record — reported turns, and the one the
628
+ * session opened onto. Only a turn with a new timestamp is news. */
629
+ this.lastTurnAt = null;
630
+ /** The GPS band last settled on; null until the session's first band. */
631
+ this.band = null;
632
+ this.bandRun = null;
633
+ /** The last position REPORTED — distance is measured from here, not from
634
+ * the previous fix, so a slow walk still adds up to a change. */
635
+ this.anchor = null;
636
+ this.staleArmed = true;
637
+ this.profile = profile;
638
+ }
639
+ /**
640
+ * Forget everything — a new session, or replay seeking backwards. Emits
641
+ * nothing. `turnOnRecordAt` is the timestamp of the turn already completed
642
+ * when the session opens (a visual session shares the compass): history, not
643
+ * news. Seeded from the turn itself rather than compared against a clock, so
644
+ * it holds whichever clock the turn was stamped with — epoch live, the
645
+ * recording's epoch in replay, where `now` is virtual.
646
+ */
647
+ reset(profile, turnOnRecordAt = null) {
648
+ if (profile) this.profile = profile;
649
+ this.movement = "unknown";
650
+ this.run = null;
651
+ this.lastTurnAt = turnOnRecordAt;
652
+ this.band = null;
653
+ this.bandRun = null;
654
+ this.anchor = null;
655
+ this.staleArmed = true;
656
+ }
657
+ /**
658
+ * Feed the newest snapshot. Returns what changed since the last one, in this
659
+ * order: movement, turn, position, confidence, staleness. Fields are read
660
+ * defensively — replay hands over recorded snapshots verbatim, and a recording
661
+ * may lack a block the live engine always fills.
662
+ */
663
+ push(snapshot, now) {
664
+ const out = [];
665
+ const emit = (name, payload) => {
666
+ out.push(stateEvent("spatial", name, payload, now));
667
+ };
668
+ this.movementFrom(snapshot, now, emit);
669
+ this.turnFrom(snapshot, emit);
670
+ this.positionFrom(snapshot, emit);
671
+ this.confidenceFrom(snapshot, now, emit);
672
+ this.staleFrom(snapshot, emit);
673
+ return out;
674
+ }
675
+ movementFrom(s, now, emit) {
676
+ const state = s.movement?.state ?? "unknown";
677
+ this.run = extend(this.run, state, fixAt(s), now);
678
+ if (state === this.movement) return;
679
+ if (state === "moving" && settled(this.run, now, this.profile.movingHoldMs)) {
680
+ emit("movementStarted", {
681
+ previous: this.movement === "stationary" ? "stationary" : "unknown",
682
+ speedMps: s.movement?.speedMps ?? null,
683
+ bearingDeg: s.movement?.bearingDeg ?? null,
684
+ since: this.run.since
685
+ });
686
+ this.movement = "moving";
687
+ } else if (state === "stationary" && settled(this.run, now, this.profile.stoppedHoldMs)) {
688
+ if (this.movement === "moving") emit("movementStopped", { previous: "moving", since: this.run.since });
689
+ this.movement = "stationary";
690
+ }
691
+ }
692
+ turnFrom(s, emit) {
693
+ const at = s.changes?.timestamp ?? null;
694
+ const deg = s.changes?.lastMeaningfulTurnDeg ?? null;
695
+ if (at === null || deg === null || at === this.lastTurnAt) return;
696
+ this.lastTurnAt = at;
697
+ emit("lastMeaningfulTurnChanged", { lastMeaningfulTurnDeg: deg, timestamp: at });
698
+ }
699
+ positionFrom(s, emit) {
700
+ const p = s.position ?? null;
701
+ if (!p) return;
702
+ if (!this.anchor) {
703
+ emit("positionChanged", { position: { ...p }, previous: null, distanceM: null });
704
+ this.anchor = p;
705
+ return;
706
+ }
707
+ const d = distanceOf([this.anchor, p]);
708
+ if (d < Math.max(this.profile.minMoveM, moveThresholdM(this.anchor, p))) {
709
+ const aNew = p.accuracyM ?? null, aOld = this.anchor.accuracyM ?? null;
710
+ if (aNew != null && aOld != null && aNew * 2 < aOld) this.anchor = p;
711
+ return;
712
+ }
713
+ emit("positionChanged", { position: { ...p }, previous: { ...this.anchor }, distanceM: d });
714
+ this.anchor = p;
715
+ }
716
+ confidenceFrom(s, now, emit) {
717
+ const p = s.position ?? null;
718
+ if (!p) return;
719
+ const level = fixConfidence(p.accuracyM ?? null);
720
+ if (level === "unknown") return;
721
+ if (this.band === null) {
722
+ this.band = level;
723
+ return;
724
+ }
725
+ if (level === this.band) {
726
+ this.bandRun = null;
727
+ return;
728
+ }
729
+ this.bandRun = extend(this.bandRun, level, fixAt(s), now);
730
+ if (!settled(this.bandRun, now, this.profile.confidenceHoldMs)) return;
731
+ emit("positionConfidenceChanged", {
732
+ level,
733
+ previous: this.band,
734
+ accuracyM: p.accuracyM ?? null,
735
+ direction: RANK[level] < RANK[this.band] ? "dropped" : "recovered"
736
+ });
737
+ this.band = level;
738
+ this.bandRun = null;
739
+ }
740
+ staleFrom(s, emit) {
741
+ const f = s.quality?.freshness;
742
+ if (!f) return;
743
+ if (f.state === "fresh") {
744
+ this.staleArmed = true;
745
+ return;
746
+ }
747
+ if (f.state !== "stale" || !this.staleArmed) return;
748
+ emit("spatialStateStale", { observedAt: f.observedAt, ageMs: f.ageMs });
749
+ this.staleArmed = false;
750
+ }
751
+ };
752
+
753
+ // src/device-state/domains/spatial.ts
754
+ var WATCH_ACCURACY = {
755
+ navigation: "navigation",
756
+ preciseLocate: "high",
757
+ fitness: "high",
758
+ geofence: "balanced",
759
+ lowPowerTracking: "low"
760
+ };
761
+ function createSpatialDomain(collectors, speedRef) {
762
+ const RECENT_PATH_MAX = 60;
763
+ let recentPath = [];
764
+ let latest2 = null;
765
+ let latestSpeed = null;
766
+ let latestCourse = null;
767
+ let stopWatch = null;
768
+ let session = null;
769
+ const detector = new SpatialEventDetector();
770
+ const listeners = listenerSet();
771
+ let ticker = null;
772
+ let turnSub = null;
773
+ const nonNegative = (v) => typeof v === "number" && v >= 0 ? v : null;
774
+ const derivedSpeed = () => {
775
+ if (recentPath.length < 2) return null;
776
+ const b = recentPath[recentPath.length - 1];
777
+ const a = recentPath[recentPath.length - 2];
778
+ const dtS = (b.timestamp - a.timestamp) / 1e3;
779
+ if (dtS <= 0 || dtS > 10) return null;
780
+ return distanceOf([a, b]) / dtS;
781
+ };
782
+ const derivedCourse = () => {
783
+ if (recentPath.length < 2) return null;
784
+ const b = recentPath[recentPath.length - 1];
785
+ const a = recentPath[recentPath.length - 2];
786
+ if (b.timestamp - a.timestamp > 1e4) return null;
787
+ if (distanceOf([a, b]) < 3) return null;
788
+ return bearingBetween(a, b);
789
+ };
790
+ const snapshotFrom = (point, measuredSpeed, measuredCourse) => {
791
+ let speedMps = measuredSpeed;
792
+ let courseDeg = measuredCourse;
793
+ let derived = false;
794
+ if (speedMps === null) {
795
+ const d = derivedSpeed();
796
+ if (d !== null) {
797
+ speedMps = d;
798
+ derived = true;
799
+ }
800
+ }
801
+ if (courseDeg === null) {
802
+ const d = derivedCourse();
803
+ if (d !== null) {
804
+ courseDeg = d;
805
+ derived = true;
806
+ }
807
+ }
808
+ const heading = currentHeadingDetail();
809
+ const turn = lastMeaningfulTurn();
810
+ return {
811
+ position: point,
812
+ movement: {
813
+ speedMps,
814
+ bearingDeg: courseDeg,
815
+ // Needs two points from the SAME session; without a stream there is
816
+ // nothing to measure against, and a distance of 0 would read as
817
+ // "the user has not moved".
818
+ distanceRecentM: recentPath.length >= 2 ? distanceOf(recentPath) : null,
819
+ state: movementStateOf(speedMps)
820
+ },
821
+ orientation: {
822
+ headingDeg: heading?.headingDeg ?? null,
823
+ // NOT the calibration rank. iOS reports 0–3 (none…high), which is not
824
+ // a number of degrees, and converting one to the other would be an
825
+ // invented error bar. The rank drives `confidence` below instead.
826
+ headingAccuracyDeg: null
827
+ },
828
+ changes: {
829
+ lastMeaningfulTurnDeg: turn ? turn.deg : null,
830
+ timestamp: turn ? turn.timestamp : null
831
+ },
832
+ recentPath: [...recentPath],
833
+ quality: qualityFrom(
834
+ point.timestamp,
835
+ spatialConfidence(point.accuracyM ?? null, heading?.calibration ?? null, derived)
836
+ )
837
+ };
838
+ };
839
+ const noFix = () => ({
840
+ position: null,
841
+ movement: { speedMps: null, bearingDeg: null, distanceRecentM: null, state: "unknown" },
842
+ orientation: { headingDeg: currentHeadingDetail()?.headingDeg ?? null },
843
+ recentPath: [],
844
+ quality: qualityUnknown()
845
+ });
846
+ const warmSnapshot = () => latest2 ? snapshotFrom(latest2, latestSpeed, latestCourse) : null;
847
+ const observe = () => {
848
+ const snapshot = warmSnapshot();
849
+ if (!snapshot) return;
850
+ for (const event of detector.push(snapshot, Date.now())) listeners.emit(event);
851
+ };
852
+ const startTicking = () => {
853
+ ticker = setInterval(observe, 1e3);
854
+ };
855
+ const stopTicking = () => {
856
+ if (ticker) clearInterval(ticker);
857
+ ticker = null;
858
+ };
859
+ return {
860
+ async getSnapshot() {
861
+ const warm = warmSnapshot();
862
+ if (warm) return warm;
863
+ if (session) return noFix();
864
+ let point;
865
+ let speedMps;
866
+ let courseDeg;
867
+ try {
868
+ if (!collectors.location) throw unsupported("location collector");
869
+ const fix = await collectors.location.getPosition({ accuracy: "low" });
870
+ point = {
871
+ latitude: fix.latitude,
872
+ longitude: fix.longitude,
873
+ altitude: fix.altitude ?? null,
874
+ accuracyM: nonNegative(fix.accuracy),
875
+ timestamp: fix.timestamp ?? Date.now()
876
+ };
877
+ speedMps = nonNegative(fix.speed);
878
+ courseDeg = nonNegative(fix.course);
879
+ } catch {
880
+ return noFix();
881
+ }
882
+ return snapshotFrom(point, speedMps, courseDeg);
883
+ },
884
+ /**
885
+ * Open the warm window: position stream + compass + event feed.
886
+ *
887
+ * The intent selects how eager the EVENTS are (spatialEvents.ts profiles)
888
+ * and the GPS TIER the stream runs at (WATCH_ACCURACY): navigation pays the
889
+ * battery for BestForNavigation; low-power tracking does not.
890
+ *
891
+ * A second `start()` while one is open joins the running session and is
892
+ * told ITS intent, not handed back the one it asked for: answering with the
893
+ * caller's intent would claim a profile that is not in force.
894
+ */
895
+ async start(options) {
896
+ if (session) return { ...session };
897
+ if (!collectors.location) throw unsupported("location collector");
898
+ const startedAt = Date.now();
899
+ session = { id: `spatial_${startedAt}`, intent: options.intent, startedAt };
900
+ detector.reset(spatialEventProfile(options.intent), lastMeaningfulTurn()?.timestamp ?? null);
901
+ void startHeading("spatial");
902
+ turnSub = onTurn(observe);
903
+ stopWatch = collectors.location.watchPosition((pos) => {
904
+ const p = {
905
+ latitude: pos.latitude,
906
+ longitude: pos.longitude,
907
+ altitude: pos.altitude ?? null,
908
+ accuracyM: nonNegative(pos.accuracy),
909
+ timestamp: pos.timestamp ?? Date.now()
910
+ };
911
+ latest2 = p;
912
+ latestSpeed = nonNegative(pos.speed);
913
+ latestCourse = nonNegative(pos.course);
914
+ speedRef.mps = latestSpeed;
915
+ speedRef.at = p.timestamp;
916
+ recentPath = [...recentPath, p].slice(-RECENT_PATH_MAX);
917
+ observe();
918
+ }, { accuracy: WATCH_ACCURACY[options.intent] ?? "balanced" });
919
+ startTicking();
920
+ return { ...session };
921
+ },
922
+ async stop() {
923
+ stopWatch?.();
924
+ stopWatch = null;
925
+ session = null;
926
+ stopTicking();
927
+ turnSub?.unsubscribe();
928
+ turnSub = null;
929
+ detector.reset();
930
+ recentPath = [];
931
+ latest2 = null;
932
+ latestSpeed = null;
933
+ latestCourse = null;
934
+ speedRef.mps = null;
935
+ speedRef.at = 0;
936
+ stopHeading("spatial");
937
+ },
938
+ /**
939
+ * The six spatial events (see `SpatialEvent`). Subscribing opens no sensor:
940
+ * events flow only while a session is open, and a subscription made before
941
+ * `start()` hears that session from its first fix.
942
+ */
943
+ subscribe(listener) {
944
+ return listeners.add(listener);
945
+ }
946
+ };
947
+ }
948
+ function spatialConfidence(accuracyM, calibration, derived) {
949
+ const rank = (v) => v === "high" ? 3 : v === "medium" ? 2 : v === "low" ? 1 : 0;
950
+ const fromFix = fixConfidence(accuracyM);
951
+ const fromCompass = calibration === null ? "unknown" : calibration >= 3 ? "high" : calibration >= 2 ? "medium" : "low";
952
+ const parts = [fromFix, fromCompass, ...derived ? ["low"] : []];
953
+ const known = parts.filter((p) => p !== "unknown");
954
+ if (!known.length) return { level: "unknown" };
955
+ const worst = known.reduce((a, b) => rank(a) <= rank(b) ? a : b);
956
+ return { level: worst };
957
+ }
958
+ function bearingBetween(a, b) {
959
+ const toRad = (d) => d * Math.PI / 180;
960
+ const la1 = toRad(a.latitude), la2 = toRad(b.latitude);
961
+ const dLon = toRad(b.longitude - a.longitude);
962
+ const y = Math.sin(dLon) * Math.cos(la2);
963
+ const x = Math.cos(la1) * Math.sin(la2) - Math.sin(la1) * Math.cos(la2) * Math.cos(dLon);
964
+ return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
965
+ }
966
+
967
+ // src/device-state/visualEngine.ts
968
+ var PROFILES = {
969
+ navigation: { intervalMs: 1e3, windowMs: 5e3 },
970
+ accessibility: { intervalMs: 1e3, windowMs: 5e3 },
971
+ stream: { intervalMs: 500, windowMs: 5e3 },
972
+ inspection: { intervalMs: 2e3, windowMs: 8e3 },
973
+ shopping: { intervalMs: 2e3, windowMs: 5e3 },
974
+ document: { intervalMs: 3e3, windowMs: 3e3 },
975
+ ocr: { intervalMs: 3e3, windowMs: 3e3 },
976
+ highQuality: { intervalMs: 5e3, windowMs: 5e3 }
977
+ };
978
+ var VisualEngine = class {
979
+ constructor() {
980
+ this.frames = [];
981
+ this.session = null;
982
+ this.listeners = /* @__PURE__ */ new Set();
983
+ /** Set by the host component while a camera is actually mounted and ready. */
984
+ this.cameraReady = false;
985
+ /** Optional: supplies heading/position stamped onto each frame. */
986
+ this.context = null;
987
+ // The native ring's actual retention (ms). The engine's effective window is
988
+ // min(intent window, retention) — set by whoever owns the clamp semantics; this
989
+ // just stores the input so that logic has one source of truth to read.
990
+ this._retentionMs = null;
991
+ }
992
+ /** Host DI. Without it frames carry no orientation, and say so with nulls. */
993
+ setContextProvider(p) {
994
+ this.context = p;
995
+ }
996
+ // ── session ──
997
+ startSession(intent) {
998
+ if (this.session) return this.session;
999
+ this.session = {
1000
+ id: `visual_${Date.now()}`,
1001
+ intent: PROFILES[intent] ? intent : "navigation",
1002
+ startedAt: Date.now(),
1003
+ suspended: false
1004
+ };
1005
+ this.notify();
1006
+ return this.session;
1007
+ }
1008
+ stopSession() {
1009
+ this.session = null;
1010
+ this.frames = [];
1011
+ this.cameraReady = false;
1012
+ this.notify();
1013
+ }
1014
+ /**
1015
+ * Background: suspend, do not end.
1016
+ *
1017
+ * iOS tears the camera down when the app leaves the foreground. The session
1018
+ * is a STATE that survives that; what does not survive is the claim that the
1019
+ * camera is live. While suspended the ring is kept but ages — a read gets
1020
+ * old frames clearly marked old, rather than a fresh-looking lie.
1021
+ */
1022
+ suspend() {
1023
+ if (!this.session || this.session.suspended) return;
1024
+ this.session.suspended = true;
1025
+ this.cameraReady = false;
1026
+ this.notify();
1027
+ }
1028
+ resume() {
1029
+ if (!this.session?.suspended) return;
1030
+ this.session.suspended = false;
1031
+ this.notify();
1032
+ }
1033
+ getSession() {
1034
+ return this.session;
1035
+ }
1036
+ /** Is a camera mounted and ready right now? Only the host knows. */
1037
+ setCameraReady(ready) {
1038
+ this.cameraReady = ready;
1039
+ this.notify();
1040
+ }
1041
+ isCameraReady() {
1042
+ return this.cameraReady && !this.session?.suspended;
1043
+ }
1044
+ // ── the ring ──
1045
+ profile() {
1046
+ const intent = this.session?.intent || "navigation";
1047
+ return PROFILES[intent];
1048
+ }
1049
+ /**
1050
+ * Feed from the native vision session (VisionSession, iOS) — the FAST frame
1051
+ * source that replaces the takePictureAsync loop. The frame is IN-MEMORY: the
1052
+ * native ring holds the pixels keyed by `id`, and native.vision resolves that
1053
+ * id inside the trusted layer. No `uri` crosses here; the quality is a REAL
1054
+ * measurement (not `unknown`), and `expiresAt` is the ring's real eviction time.
1055
+ * The public VisualFrameRef strip to id-only is owned by the device-state session.
1056
+ */
1057
+ pushFrameMeta(meta) {
1058
+ let heading = null;
1059
+ try {
1060
+ heading = this.context?.heading() ?? null;
1061
+ } catch {
1062
+ }
1063
+ this.frames.push({
1064
+ // In-memory: no file. native.vision resolves the id inside the native ring.
1065
+ handle: { id: meta.id, mimeType: "image/none", expiresAt: meta.expiresAt ?? null },
1066
+ timestamp: meta.timestamp,
1067
+ orientation: { headingDeg: heading?.headingDeg ?? null, pitchDeg: null, rollDeg: null },
1068
+ quality: meta.quality ?? { blur: "unknown", exposure: "unknown", obstructed: null }
1069
+ });
1070
+ this.evict();
1071
+ this.notify();
1072
+ }
1073
+ setRetentionMs(ms) {
1074
+ this._retentionMs = ms && ms > 0 ? ms : null;
1075
+ }
1076
+ retentionMs() {
1077
+ return this._retentionMs;
1078
+ }
1079
+ /**
1080
+ * How far back the timeline ACTUALLY reaches: `min(intent window, native
1081
+ * retention)`.
1082
+ *
1083
+ * The intent asks for a window; native decides what it can afford to keep.
1084
+ * Full-res luma at ~24fps is tens of megabytes for a few seconds, so the ring
1085
+ * is memory-bounded and shrinks under pressure — `retentionMs` is native
1086
+ * publishing what it is really holding.
1087
+ *
1088
+ * EVERY FRAME IN THE TIMELINE CAN BE ANALYSED. That is the one sentence a
1089
+ * plugin author has to hold, and this clamp is what makes it true. The
1090
+ * alternative — listing frames past retention marked "not analysable" — was
1091
+ * considered and rejected: a caller would have to check a flag before every
1092
+ * use, and forgetting throws mid-guidance on a frame the model can see
1093
+ * listed. Present-but-unusable is the same trap as an empty rowset reading
1094
+ * as "no rows matched".
1095
+ *
1096
+ * If per-frame history beyond retention is ever needed, the shape is an
1097
+ * AGGREGATE on the snapshot ("the view has been unusable for N ms"), never a
1098
+ * per-entry flag.
1099
+ */
1100
+ effectiveWindowMs() {
1101
+ const intent = this.profile().windowMs;
1102
+ const retention = this._retentionMs;
1103
+ return retention === null ? intent : Math.min(intent, retention);
1104
+ }
1105
+ /**
1106
+ * Time-based, not count-based: the design specifies a rolling WINDOW.
1107
+ *
1108
+ * Evicts on the EFFECTIVE window, so a frame whose pixels native has already
1109
+ * dropped leaves the timeline at the same moment. Without this, `frameById`
1110
+ * would start returning null for frames still being listed.
1111
+ */
1112
+ evict() {
1113
+ const cutoff = Date.now() - this.effectiveWindowMs();
1114
+ this.frames = this.frames.filter((f) => f.timestamp >= cutoff);
1115
+ }
1116
+ timeline() {
1117
+ this.evict();
1118
+ return { windowMs: this.effectiveWindowMs(), frames: [...this.frames] };
1119
+ }
1120
+ latest() {
1121
+ this.evict();
1122
+ return this.frames.length ? this.frames[this.frames.length - 1] : null;
1123
+ }
1124
+ /**
1125
+ * Resolve a frame handle id (from a VisualFrameRef) back to the live frame so
1126
+ * the mechanical layer — native.vision — can read its on-device file. The
1127
+ * whole contract of that layer is that it takes an id, never pixels; this is
1128
+ * where an id becomes a `handle.uri` it can open. Returns null when the id is
1129
+ * unknown OR its frame has aged out of the rolling window (the cache file may
1130
+ * also be gone by then) — a real "I can't look at that frame" answer, which
1131
+ * the caller must treat as distinct from "I looked and found nothing".
1132
+ */
1133
+ frameById(id) {
1134
+ this.evict();
1135
+ return this.frames.find((f) => f.handle.id === id) ?? null;
1136
+ }
1137
+ /**
1138
+ * Record a MEASURED quality back onto a frame (native.vision.assessQuality).
1139
+ * Frames are minted with `quality: unknown` because nothing looks at the
1140
+ * pixels at capture time; this is how a real measurement replaces that so a
1141
+ * later read of VisualFrameRef.quality reflects it. No-op if the frame has
1142
+ * aged out — we never resurrect an evicted frame just to label it.
1143
+ */
1144
+ setFrameQuality(id, quality) {
1145
+ const f = this.frames.find((fr) => fr.handle.id === id);
1146
+ if (!f) return;
1147
+ f.quality = quality;
1148
+ this.notify();
1149
+ }
1150
+ // ── change notification ──
1151
+ subscribe(fn) {
1152
+ this.listeners.add(fn);
1153
+ return () => this.listeners.delete(fn);
1154
+ }
1155
+ notify() {
1156
+ for (const fn of this.listeners) {
1157
+ try {
1158
+ fn();
1159
+ } catch {
1160
+ }
1161
+ }
1162
+ }
1163
+ };
1164
+ var visualEngine = new VisualEngine();
1165
+ function frameQuality(frame) {
1166
+ if (!frame) return { freshness: { state: "unknown", observedAt: null, ageMs: null } };
1167
+ const ageMs = Date.now() - frame.timestamp;
1168
+ return {
1169
+ freshness: {
1170
+ // Tighter than the other domains on purpose: a two-second-old frame of a
1171
+ // moving scene is not "fresh" in any useful sense.
1172
+ state: ageMs < 2e3 ? "fresh" : ageMs < 1e4 ? "aging" : "stale",
1173
+ observedAt: frame.timestamp,
1174
+ ageMs
1175
+ },
1176
+ confidence: { level: "unknown" }
1177
+ };
1178
+ }
1179
+
1180
+ // src/device-state/domains/visual.ts
1181
+ function cameraState() {
1182
+ const session = visualEngine.getSession();
1183
+ return {
1184
+ // `available` = the app could use a camera at all. `active` = one is
1185
+ // running RIGHT NOW. They differ exactly when it matters: a pocketed
1186
+ // phone is available but not active, and answering `true` to both
1187
+ // would let a guide speak about a scene nothing is watching.
1188
+ available: !!session,
1189
+ active: visualEngine.isCameraReady(),
1190
+ facing: session ? "back" : "unknown"
1191
+ };
1192
+ }
1193
+ function createVisualDomain() {
1194
+ return {
1195
+ async getSnapshot() {
1196
+ const latest2 = visualEngine.latest();
1197
+ const timeline = visualEngine.timeline();
1198
+ return {
1199
+ camera: cameraState(),
1200
+ // null, not a stale frame dressed as current. A caller with no usable
1201
+ // frame must see nothing rather than something old.
1202
+ latest: latest2,
1203
+ recentTimeline: timeline,
1204
+ quality: frameQuality(latest2)
1205
+ };
1206
+ },
1207
+ async start(options) {
1208
+ const s = visualEngine.startSession(options?.intent || "navigation");
1209
+ visualEngine.setContextProvider({ heading: currentHeading });
1210
+ void startHeading("visual");
1211
+ return { id: s.id, intent: s.intent, startedAt: s.startedAt };
1212
+ },
1213
+ async stop() {
1214
+ visualEngine.stopSession();
1215
+ visualEngine.setContextProvider(null);
1216
+ stopHeading("visual");
1217
+ },
1218
+ /**
1219
+ * A deliberate one-shot. Distinct from getSnapshot because it is an
1220
+ * OPERATION: it waits for a frame rather than serving the newest one.
1221
+ *
1222
+ * Throws when it cannot, rather than returning an empty result — the
1223
+ * design is explicit that capture is an operation and reads are state.
1224
+ */
1225
+ async capture() {
1226
+ if (!visualEngine.getSession()) {
1227
+ throw unsupported("visual.capture without an open session \u2014 call start({ intent }) first");
1228
+ }
1229
+ if (!visualEngine.isCameraReady()) {
1230
+ const err2 = new Error(
1231
+ "The camera is not running right now \u2014 the app may be in the background."
1232
+ );
1233
+ err2.code = "TEMPORARILY_UNAVAILABLE";
1234
+ throw err2;
1235
+ }
1236
+ const before = visualEngine.latest()?.timestamp ?? 0;
1237
+ const deadline = Date.now() + 4e3;
1238
+ while (Date.now() < deadline) {
1239
+ const f = visualEngine.latest();
1240
+ if (f && f.timestamp > before) return { frame: f };
1241
+ await new Promise((r) => setTimeout(r, 100));
1242
+ }
1243
+ const err = new Error("No frame arrived within 4s.");
1244
+ err.code = "TIMEOUT";
1245
+ throw err;
1246
+ },
1247
+ /**
1248
+ * Fires when the CAMERA block changes — a session opening or closing, the
1249
+ * camera coming up or going down. The engine notifies on every frame too,
1250
+ * and forwarding that made this a raw frame stream, which the freeze's core
1251
+ * rule 4 forbids. A frame arriving is what `getSnapshot()` is for.
1252
+ */
1253
+ subscribe(listener) {
1254
+ let last = JSON.stringify(cameraState());
1255
+ const off = visualEngine.subscribe(() => {
1256
+ const camera = cameraState();
1257
+ const key = JSON.stringify(camera);
1258
+ if (key === last) return;
1259
+ last = key;
1260
+ listener(stateEvent("visual", "visualStateChanged", { camera }));
1261
+ });
1262
+ return { unsubscribe: off };
1263
+ }
1264
+ };
1265
+ }
1266
+
1267
+ // src/device-state/activityEngine.ts
1268
+ var sensors = null;
1269
+ var sensorsMissing = false;
1270
+ function loadSensors() {
1271
+ if (sensors || sensorsMissing) return sensors;
1272
+ try {
1273
+ sensors = require("expo-sensors");
1274
+ } catch {
1275
+ sensorsMissing = true;
1276
+ sensors = null;
1277
+ }
1278
+ return sensors;
1279
+ }
1280
+ var ACCEL_INTERVAL_MS = 200;
1281
+ var MOTION_WINDOW_MS = 3e3;
1282
+ var STEP_WINDOW_MS = 2e4;
1283
+ var GRAVITY_ALPHA = 0.1;
1284
+ var ActivityEngine = class {
1285
+ constructor() {
1286
+ this.accelSub = null;
1287
+ this.stepSub = null;
1288
+ this.magnitudes = [];
1289
+ this.gravity = null;
1290
+ this.steps = [];
1291
+ this.sessionId = null;
1292
+ this.startedAt = 0;
1293
+ /** When the CURRENT reading last changed — feeds `human.since`. */
1294
+ this.pedometerAvailable = null;
1295
+ // ── transitions ──
1296
+ //
1297
+ // Tracked on a timer inside the engine rather than computed when someone
1298
+ // reads, because a transition is an EVENT: "you started walking" happens
1299
+ // between two reads, and a domain that only classifies on demand reports the
1300
+ // state and loses the moment it changed. `since` has the same problem.
1301
+ this.current = "unknown";
1302
+ this.since = null;
1303
+ this.transitions = [];
1304
+ this.ticker = null;
1305
+ }
1306
+ isRunning() {
1307
+ return this.sessionId !== null;
1308
+ }
1309
+ session() {
1310
+ return this.sessionId ? { id: this.sessionId, startedAt: this.startedAt } : null;
1311
+ }
1312
+ /**
1313
+ * @param classify how to name the current activity — injected so the engine
1314
+ * keeps no opinion of its own and the classifier stays pure and testable.
1315
+ */
1316
+ async start(classify) {
1317
+ if (this.sessionId) return this.session();
1318
+ this.sessionId = `activity_${Date.now()}`;
1319
+ this.startedAt = Date.now();
1320
+ const s = loadSensors();
1321
+ if (!s) {
1322
+ this.pedometerAvailable = false;
1323
+ this.startTicking(classify);
1324
+ return this.session();
1325
+ }
1326
+ const { Accelerometer, Pedometer } = s;
1327
+ Accelerometer.setUpdateInterval(ACCEL_INTERVAL_MS);
1328
+ this.accelSub = Accelerometer.addListener(({ x, y, z }) => {
1329
+ const now = Date.now();
1330
+ this.magnitudes.push({ m: Math.sqrt(x * x + y * y + z * z), t: now });
1331
+ const cutoff = now - MOTION_WINDOW_MS;
1332
+ if (this.magnitudes.length > 8 && this.magnitudes[0].t < cutoff) {
1333
+ this.magnitudes = this.magnitudes.filter((s2) => s2.t >= cutoff);
1334
+ }
1335
+ this.gravity = this.gravity ? {
1336
+ x: this.gravity.x + GRAVITY_ALPHA * (x - this.gravity.x),
1337
+ y: this.gravity.y + GRAVITY_ALPHA * (y - this.gravity.y),
1338
+ z: this.gravity.z + GRAVITY_ALPHA * (z - this.gravity.z)
1339
+ } : { x, y, z };
1340
+ });
1341
+ try {
1342
+ this.pedometerAvailable = await Pedometer.isAvailableAsync();
1343
+ } catch {
1344
+ this.pedometerAvailable = false;
1345
+ }
1346
+ if (this.pedometerAvailable) {
1347
+ try {
1348
+ this.stepSub = Pedometer.watchStepCount(({ steps }) => {
1349
+ this.steps.push({ steps, t: Date.now() });
1350
+ const cutoff = Date.now() - STEP_WINDOW_MS;
1351
+ if (this.steps.length > 2 && this.steps[0].t < cutoff) {
1352
+ this.steps = this.steps.filter((s2) => s2.t >= cutoff);
1353
+ }
1354
+ });
1355
+ } catch {
1356
+ this.stepSub = null;
1357
+ this.pedometerAvailable = false;
1358
+ }
1359
+ }
1360
+ this.startTicking(classify);
1361
+ return this.session();
1362
+ }
1363
+ stop() {
1364
+ this.accelSub?.remove();
1365
+ this.stepSub?.remove();
1366
+ this.accelSub = null;
1367
+ this.stepSub = null;
1368
+ this.sessionId = null;
1369
+ this.stopTicking();
1370
+ this.magnitudes = [];
1371
+ this.steps = [];
1372
+ this.gravity = null;
1373
+ }
1374
+ /** Variance of accelerometer magnitude over the motion window, in g². */
1375
+ accelVariance() {
1376
+ const cutoff = Date.now() - MOTION_WINDOW_MS;
1377
+ const window = this.magnitudes.filter((s) => s.t >= cutoff);
1378
+ if (window.length < 5) return null;
1379
+ const mean = window.reduce((a, s) => a + s.m, 0) / window.length;
1380
+ return window.reduce((a, s) => a + (s.m - mean) ** 2, 0) / window.length;
1381
+ }
1382
+ currentGravity() {
1383
+ return this.gravity;
1384
+ }
1385
+ /**
1386
+ * Steps per minute over the step window.
1387
+ *
1388
+ * Computed from the DIFFERENCE between the first and last cumulative counts,
1389
+ * so it does not matter whether the platform counts from subscription start
1390
+ * or from midnight.
1391
+ *
1392
+ * Returns null — not 0 — when the window is too short to divide by. Zero
1393
+ * steps per minute is a real claim ("standing still") and must only be made
1394
+ * once there is a window long enough to support it.
1395
+ */
1396
+ cadenceSpm() {
1397
+ const cutoff = Date.now() - STEP_WINDOW_MS;
1398
+ const window = this.steps.filter((s) => s.t >= cutoff);
1399
+ if (window.length < 2) {
1400
+ if (this.pedometerAvailable && Date.now() - this.startedAt > STEP_WINDOW_MS) return 0;
1401
+ return null;
1402
+ }
1403
+ const first = window[0], last = window[window.length - 1];
1404
+ const minutes = (last.t - first.t) / 6e4;
1405
+ if (minutes <= 0) return null;
1406
+ return (last.steps - first.steps) / minutes;
1407
+ }
1408
+ /** Whether a pedometer exists and is permitted. Null before `start()`. */
1409
+ hasPedometer() {
1410
+ return this.pedometerAvailable;
1411
+ }
1412
+ /** When the newest sample arrived — what freshness is actually about. */
1413
+ observedAt() {
1414
+ const ts = [
1415
+ this.magnitudes[this.magnitudes.length - 1]?.t,
1416
+ this.steps[this.steps.length - 1]?.t
1417
+ ].filter((t) => typeof t === "number");
1418
+ return ts.length ? Math.max(...ts) : null;
1419
+ }
1420
+ /** Feed the engine its own classification once a second. */
1421
+ startTicking(classify) {
1422
+ this.ticker = setInterval(() => {
1423
+ const next = classify();
1424
+ if (next === this.current) return;
1425
+ this.current = next;
1426
+ this.since = Date.now();
1427
+ this.transitions = [...this.transitions, { name: next, timestamp: this.since }].slice(-10);
1428
+ }, 1e3);
1429
+ }
1430
+ stopTicking() {
1431
+ if (this.ticker) clearInterval(this.ticker);
1432
+ this.ticker = null;
1433
+ this.current = "unknown";
1434
+ this.since = null;
1435
+ this.transitions = [];
1436
+ }
1437
+ /** When the current activity began, or null if it has not been established. */
1438
+ currentSince() {
1439
+ return this.since;
1440
+ }
1441
+ /** Newest last, bounded. Empty is a real answer: nothing has changed yet. */
1442
+ recentTransitions() {
1443
+ return [...this.transitions];
1444
+ }
1445
+ };
1446
+ var activityEngine = new ActivityEngine();
1447
+
1448
+ // src/device-state/activityClassifier.ts
1449
+ var RUN_SPM = 140;
1450
+ var WALK_SPM = 20;
1451
+ var STILL_VAR = 2e-3;
1452
+ var ACTIVE_VAR = 0.02;
1453
+ var VEHICLE_MPS = 3;
1454
+ var AXIS_DOMINANT = 0.75;
1455
+ function classifyActivity(input) {
1456
+ return { human: classifyHuman(input), pose: classifyPose(input) };
1457
+ }
1458
+ function classifyHuman({ cadenceSpm, accelVariance, speedMps }) {
1459
+ if (cadenceSpm !== null && cadenceSpm >= RUN_SPM) {
1460
+ return { state: "running", confidence: { level: "high" } };
1461
+ }
1462
+ if (cadenceSpm !== null && cadenceSpm >= WALK_SPM) {
1463
+ return { state: "walking", confidence: { level: "high" } };
1464
+ }
1465
+ if (speedMps !== null && speedMps >= VEHICLE_MPS) {
1466
+ return { state: "unknown", confidence: { level: "low" } };
1467
+ }
1468
+ if (accelVariance !== null && accelVariance < STILL_VAR && (cadenceSpm === null || cadenceSpm < WALK_SPM)) {
1469
+ return { state: "stationary", confidence: { level: "medium" } };
1470
+ }
1471
+ return { state: "unknown", confidence: { level: "unknown" } };
1472
+ }
1473
+ function classifyPose({ gravity, accelVariance }) {
1474
+ if (!gravity) {
1475
+ return { placement: "unknown", orientation: "unknown", confidence: { level: "unknown" } };
1476
+ }
1477
+ const { x, y, z } = gravity;
1478
+ const orientation = Math.abs(z) >= AXIS_DOMINANT ? "flat" : Math.abs(y) >= AXIS_DOMINANT ? "portrait" : Math.abs(x) >= AXIS_DOMINANT ? "landscape" : "unknown";
1479
+ if (orientation === "flat" && accelVariance !== null && accelVariance < STILL_VAR) {
1480
+ return { placement: "table", orientation, confidence: { level: "high" } };
1481
+ }
1482
+ if (orientation !== "flat" && accelVariance !== null && accelVariance >= ACTIVE_VAR) {
1483
+ return { placement: "handheld", orientation, confidence: { level: "medium" } };
1484
+ }
1485
+ return { placement: "unknown", orientation, confidence: { level: "unknown" } };
1486
+ }
1487
+
1488
+ // src/device-state/domains/activity.ts
1489
+ function createActivityDomain(speedRef) {
1490
+ const SPEED_MAX_AGE_MS = 15e3;
1491
+ const input = () => ({
1492
+ cadenceSpm: activityEngine.cadenceSpm(),
1493
+ accelVariance: activityEngine.accelVariance(),
1494
+ gravity: activityEngine.currentGravity(),
1495
+ speedMps: speedRef.at && Date.now() - speedRef.at < SPEED_MAX_AGE_MS ? speedRef.mps : null
1496
+ });
1497
+ return {
1498
+ async getSnapshot() {
1499
+ if (!activityEngine.isRunning()) {
1500
+ return {
1501
+ human: { state: "unknown", since: null, confidence: { level: "unknown" } },
1502
+ devicePose: { placement: "unknown", orientation: "unknown", confidence: { level: "unknown" } },
1503
+ recentTransitions: [],
1504
+ quality: qualityUnknown()
1505
+ };
1506
+ }
1507
+ const verdict = classifyActivity(input());
1508
+ const observedAt = activityEngine.observedAt();
1509
+ const transitions = activityEngine.recentTransitions();
1510
+ return {
1511
+ human: {
1512
+ state: verdict.human.state,
1513
+ since: activityEngine.currentSince(),
1514
+ confidence: verdict.human.confidence
1515
+ },
1516
+ devicePose: {
1517
+ placement: verdict.pose.placement,
1518
+ orientation: verdict.pose.orientation,
1519
+ confidence: verdict.pose.confidence
1520
+ },
1521
+ transition: {
1522
+ current: verdict.human.state,
1523
+ // A hint, and we have no basis for one. The freeze calls `likelyNext`
1524
+ // advisory; advisory is not licence to invent it.
1525
+ likelyNext: null
1526
+ },
1527
+ recentTransitions: transitions,
1528
+ quality: observedAt === null ? qualityUnknown() : qualityFrom(observedAt, verdict.human.confidence)
1529
+ };
1530
+ },
1531
+ /**
1532
+ * Start sampling. The intent is recorded but does not yet change strategy —
1533
+ * there is no native power-tuning layer for it to reach.
1534
+ */
1535
+ async start(options) {
1536
+ const s = await activityEngine.start(() => classifyActivity(input()).human.state);
1537
+ return { id: s.id, intent: options.intent, startedAt: s.startedAt };
1538
+ },
1539
+ async stop() {
1540
+ activityEngine.stop();
1541
+ },
1542
+ // No activity event vocabulary is frozen — the design notes there is no
1543
+ // "Initial Activity Events" list at all — so naming events here would put
1544
+ // words in plugins that the freeze may contradict.
1545
+ subscribe() {
1546
+ throw unsupported("activity.subscribe");
1547
+ }
1548
+ };
1549
+ }
1550
+
1551
+ // src/device-state/index.ts
1552
+ function createDeviceState(collectors = {}) {
1553
+ const speedRef = { mps: null, at: 0 };
1554
+ return {
1555
+ deviceContext: createDeviceContextDomain(),
1556
+ connectivity: createConnectivityDomain(collectors),
1557
+ capability: createCapabilityDomain(collectors),
1558
+ interaction: createInteractionDomain(),
1559
+ spatial: createSpatialDomain(collectors, speedRef),
1560
+ visual: createVisualDomain(),
1561
+ activity: createActivityDomain(speedRef)
1562
+ };
1563
+ }
1564
+ var IMPLEMENTED_DOMAINS = [
1565
+ "deviceContext",
1566
+ "connectivity",
1567
+ "capability",
1568
+ "interaction",
1569
+ "spatial",
1570
+ "visual",
1571
+ "activity"
1572
+ ];
1573
+
1574
+ // src/camera/CameraTaskHost.tsx
1575
+ var import_react = require("react");
1576
+ var import_react_native2 = require("react-native");
1577
+ var import_expo_camera = require("expo-camera");
1578
+
1579
+ // src/camera/cameraTasks.ts
1580
+ function cameraError(code, message) {
1581
+ const err = new Error(message);
1582
+ err.code = code;
1583
+ return err;
1584
+ }
1585
+ var CameraTaskBroker = class {
1586
+ constructor() {
1587
+ this.task = null;
1588
+ this.listeners = /* @__PURE__ */ new Set();
1589
+ /** Set by the host while a camera is mounted and ready. */
1590
+ this.hostMounted = false;
1591
+ }
1592
+ current() {
1593
+ return this.task;
1594
+ }
1595
+ subscribe(fn) {
1596
+ this.listeners.add(fn);
1597
+ return () => this.listeners.delete(fn);
1598
+ }
1599
+ /**
1600
+ * Declare that a `CameraTaskHost` exists.
1601
+ *
1602
+ * Without it nothing will ever settle the promise, so a request must fail
1603
+ * IMMEDIATELY and say why. The alternative is a plugin awaiting forever,
1604
+ * which is the worst failure of the set: no error, no timeout, no camera,
1605
+ * and a conversation that simply stops.
1606
+ */
1607
+ setHostMounted(mounted) {
1608
+ this.hostMounted = mounted;
1609
+ if (!mounted) this.fail(cameraError("UNAVAILABLE", "The camera surface was dismissed before the task completed."));
1610
+ this.notify();
1611
+ }
1612
+ isHostMounted() {
1613
+ return this.hostMounted;
1614
+ }
1615
+ /** Enqueue and hand back the promise the plugin awaits. */
1616
+ run(kind, opts) {
1617
+ if (!this.hostMounted) {
1618
+ return Promise.reject(cameraError(
1619
+ "UNAVAILABLE",
1620
+ "No camera surface is mounted in this app, so the camera cannot be shown. The host must render <CameraTaskHost /> once, near the app root."
1621
+ ));
1622
+ }
1623
+ if (this.task) {
1624
+ return Promise.reject(cameraError(
1625
+ "BUSY",
1626
+ `The camera is already in use (${this.task.kind}). Only one camera task can run at a time.`
1627
+ ));
1628
+ }
1629
+ return new Promise((resolve, reject) => {
1630
+ this.task = { kind, opts, resolve, reject };
1631
+ this.notify();
1632
+ });
1633
+ }
1634
+ /** Settle the running task successfully and clear it. */
1635
+ complete(value) {
1636
+ const t = this.task;
1637
+ if (!t) return;
1638
+ this.task = null;
1639
+ this.notify();
1640
+ t.resolve(value);
1641
+ }
1642
+ /** Settle the running task with a failure and clear it. */
1643
+ fail(err) {
1644
+ const t = this.task;
1645
+ if (!t) return;
1646
+ this.task = null;
1647
+ this.notify();
1648
+ t.reject(err);
1649
+ }
1650
+ /**
1651
+ * The user backed out.
1652
+ *
1653
+ * A distinct code, because "the user chose not to" is not a malfunction and
1654
+ * a guide should say something different about it than about a broken lens.
1655
+ */
1656
+ cancel() {
1657
+ this.fail(cameraError("CANCELLED", "Cancelled \u2014 the camera was dismissed before anything was captured."));
1658
+ }
1659
+ notify() {
1660
+ for (const fn of this.listeners) {
1661
+ try {
1662
+ fn();
1663
+ } catch {
1664
+ }
1665
+ }
1666
+ }
1667
+ };
1668
+ var cameraTasks = new CameraTaskBroker();
1669
+
1670
+ // src/camera/CameraTaskHost.tsx
1671
+ var import_jsx_runtime = require("react/jsx-runtime");
1672
+ var SCAN_TIMEOUT_MS = 3e4;
1673
+ var MAX_RECORD_MS = 6e4;
1674
+ function CameraTaskHost() {
1675
+ const [task, setTask] = (0, import_react.useState)(cameraTasks.current());
1676
+ const [camPermission, requestCamPermission] = (0, import_expo_camera.useCameraPermissions)();
1677
+ const [micPermission, requestMicPermission] = (0, import_expo_camera.useMicrophonePermissions)();
1678
+ const cameraRef = (0, import_react.useRef)(null);
1679
+ const settling = (0, import_react.useRef)(false);
1680
+ (0, import_react.useEffect)(() => {
1681
+ cameraTasks.setHostMounted(true);
1682
+ return () => cameraTasks.setHostMounted(false);
1683
+ }, []);
1684
+ (0, import_react.useEffect)(() => cameraTasks.subscribe(() => {
1685
+ settling.current = false;
1686
+ setTask(cameraTasks.current());
1687
+ }), []);
1688
+ (0, import_react.useEffect)(() => {
1689
+ if (!task) return;
1690
+ let cancelled = false;
1691
+ void (async () => {
1692
+ const cam = camPermission?.granted ? camPermission : await requestCamPermission();
1693
+ if (cancelled) return;
1694
+ if (!cam?.granted) {
1695
+ cameraTasks.fail(cameraError(
1696
+ "PERMISSION_DENIED",
1697
+ "Camera permission was not granted. Enable it for this app in Settings > Privacy > Camera."
1698
+ ));
1699
+ return;
1700
+ }
1701
+ if (task.kind === "record" && task.opts.withAudio) {
1702
+ const mic = micPermission?.granted ? micPermission : await requestMicPermission();
1703
+ if (cancelled) return;
1704
+ if (!mic?.granted) {
1705
+ cameraTasks.fail(cameraError(
1706
+ "PERMISSION_DENIED",
1707
+ "Microphone permission was not granted, so a video with sound cannot be recorded."
1708
+ ));
1709
+ }
1710
+ }
1711
+ })();
1712
+ return () => {
1713
+ cancelled = true;
1714
+ };
1715
+ }, [task]);
1716
+ (0, import_react.useEffect)(() => {
1717
+ if (task?.kind !== "scan") return;
1718
+ const ms = task.opts.timeoutMs ?? SCAN_TIMEOUT_MS;
1719
+ const t = setTimeout(() => {
1720
+ cameraTasks.fail(cameraError("TIMEOUT", `No barcode was found within ${Math.round(ms / 1e3)}s.`));
1721
+ }, ms);
1722
+ return () => clearTimeout(t);
1723
+ }, [task]);
1724
+ (0, import_react.useEffect)(() => {
1725
+ if (task?.kind !== "record" || !camPermission?.granted) return;
1726
+ let cancelled = false;
1727
+ const maxMs = Math.min(task.opts.maxDurationMs ?? 15e3, MAX_RECORD_MS);
1728
+ const startedAt = Date.now();
1729
+ void (async () => {
1730
+ await new Promise((r) => setTimeout(r, 50));
1731
+ if (cancelled || !cameraRef.current) return;
1732
+ try {
1733
+ const video = await cameraRef.current.recordAsync({ maxDuration: Math.ceil(maxMs / 1e3) });
1734
+ if (cancelled) return;
1735
+ if (!video?.uri) {
1736
+ cameraTasks.fail(cameraError("INTERNAL", "Recording finished but produced no file."));
1737
+ return;
1738
+ }
1739
+ cameraTasks.complete({ uri: video.uri, durationMs: Date.now() - startedAt });
1740
+ } catch (err) {
1741
+ if (!cancelled) cameraTasks.fail(cameraError("INTERNAL", err?.message || "Recording failed."));
1742
+ }
1743
+ })();
1744
+ return () => {
1745
+ cancelled = true;
1746
+ try {
1747
+ cameraRef.current?.stopRecording();
1748
+ } catch {
1749
+ }
1750
+ };
1751
+ }, [task, camPermission?.granted]);
1752
+ if (!task || !camPermission?.granted) return null;
1753
+ const isScan = task.kind === "scan";
1754
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native2.View, { style: styles.overlay, children: [
1755
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1756
+ import_expo_camera.CameraView,
1757
+ {
1758
+ ref: cameraRef,
1759
+ style: import_react_native2.StyleSheet.absoluteFill,
1760
+ facing: "back",
1761
+ mode: isScan ? "picture" : "video",
1762
+ barcodeScannerSettings: isScan && task.opts.formats?.length ? { barcodeTypes: task.opts.formats } : void 0,
1763
+ onBarcodeScanned: isScan ? ({ data, type }) => {
1764
+ if (settling.current) return;
1765
+ settling.current = true;
1766
+ cameraTasks.complete({ data, format: type });
1767
+ } : void 0
1768
+ }
1769
+ ),
1770
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native2.View, { style: styles.hud, pointerEvents: "box-none", children: [
1771
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native2.Text, { style: styles.hint, children: isScan ? "Point the camera at the code" : "Recording\u2026" }),
1772
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native2.Pressable, { style: styles.cancel, onPress: () => cameraTasks.cancel(), accessibilityRole: "button", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native2.Text, { style: styles.cancelText, children: "Cancel" }) })
1773
+ ] })
1774
+ ] });
1775
+ }
1776
+ var styles = import_react_native2.StyleSheet.create({
1777
+ overlay: { ...import_react_native2.StyleSheet.absoluteFillObject, backgroundColor: "#000", zIndex: 9999 },
1778
+ hud: { flex: 1, justifyContent: "space-between", paddingVertical: 64, alignItems: "center" },
1779
+ hint: { color: "#fff", fontSize: 16, textAlign: "center", paddingHorizontal: 24 },
1780
+ cancel: { paddingHorizontal: 28, paddingVertical: 14, borderRadius: 24, backgroundColor: "rgba(255,255,255,0.18)" },
1781
+ cancelText: { color: "#fff", fontSize: 16, fontWeight: "600" }
1782
+ });
1783
+
1784
+ // src/device-state/replay.ts
1785
+ var DOMAINS = [
1786
+ "spatial",
1787
+ "visual",
1788
+ "activity",
1789
+ "deviceContext",
1790
+ "connectivity",
1791
+ "capability",
1792
+ "environment",
1793
+ "interaction"
1794
+ ];
1795
+ function unknownSnapshot(domain) {
1796
+ const quality = { freshness: { state: "unknown", observedAt: null, ageMs: null }, confidence: { level: "unknown" } };
1797
+ switch (domain) {
1798
+ case "spatial":
1799
+ return { ...{ quality }, position: null, movement: { speedMps: null, bearingDeg: null, distanceRecentM: null, state: "unknown" }, orientation: { headingDeg: null }, recentPath: [] };
1800
+ case "visual":
1801
+ return { quality, camera: { available: false, active: false, facing: "unknown" }, latest: null, recentTimeline: { windowMs: 0, frames: [] } };
1802
+ case "activity":
1803
+ return { quality, human: { state: "unknown", since: null, confidence: { level: "unknown" } }, devicePose: { placement: "unknown", orientation: "unknown", confidence: { level: "unknown" } }, recentTransitions: [] };
1804
+ default:
1805
+ return { quality };
1806
+ }
1807
+ }
1808
+ function refusal(domain, code, message) {
1809
+ const err = new Error(message || `deviceState.${domain}: refused during recording (${code}).`);
1810
+ err.code = code;
1811
+ err.domain = domain;
1812
+ return err;
1813
+ }
1814
+ function createReplayDeviceState(fixture) {
1815
+ const samples = [...fixture.samples || []].sort((a, b) => a.t - b.t);
1816
+ const duration = samples.length ? samples[samples.length - 1].t : 0;
1817
+ const refusals = new Map((fixture.refusals || []).map((r) => [r.domain, r]));
1818
+ const openSessions = /* @__PURE__ */ new Set();
1819
+ let cursor = 0;
1820
+ const spatialDetector = new SpatialEventDetector();
1821
+ const spatialListeners = listenerSet();
1822
+ const moveTo = (target) => {
1823
+ const next = Math.min(duration, Math.max(0, target));
1824
+ if (!openSessions.has("spatial")) return cursor = next;
1825
+ if (next < cursor) {
1826
+ cursor = next;
1827
+ spatialDetector.reset(void 0, turnOnRecordAt());
1828
+ return cursor;
1829
+ }
1830
+ const from = cursor;
1831
+ for (const s of samples) {
1832
+ if (s.t <= from || !s.spatial) continue;
1833
+ if (s.t > next) break;
1834
+ cursor = s.t;
1835
+ for (const event of spatialDetector.push(s.spatial, s.t)) spatialListeners.emit(event);
1836
+ }
1837
+ return cursor = next;
1838
+ };
1839
+ const clock = {
1840
+ now: () => cursor,
1841
+ advance: (ms) => moveTo(cursor + ms),
1842
+ seek: (ms) => moveTo(ms),
1843
+ end: () => moveTo(duration),
1844
+ durationMs: () => duration
1845
+ };
1846
+ const sampleAt = () => {
1847
+ let found = null;
1848
+ for (const s of samples) {
1849
+ if (s.t > cursor) break;
1850
+ found = s;
1851
+ }
1852
+ return found;
1853
+ };
1854
+ const turnOnRecordAt = () => sampleAt()?.spatial?.changes?.timestamp ?? null;
1855
+ const domainFor = (name) => ({
1856
+ async getSnapshot() {
1857
+ const s = sampleAt();
1858
+ const recorded = s ? s[name] : void 0;
1859
+ return recorded ?? unknownSnapshot(name);
1860
+ },
1861
+ async start(options) {
1862
+ const r = refusals.get(name);
1863
+ if (r) throw refusal(name, r.code, r.message);
1864
+ if (name === "spatial" && !openSessions.has(name)) {
1865
+ spatialDetector.reset(spatialEventProfile(options?.intent), turnOnRecordAt());
1866
+ }
1867
+ openSessions.add(name);
1868
+ return { id: `replay_${name}`, intent: "replay", startedAt: 0 };
1869
+ },
1870
+ async stop() {
1871
+ openSessions.delete(name);
1872
+ if (name === "spatial") spatialDetector.reset();
1873
+ },
1874
+ subscribe(listener) {
1875
+ if (name === "spatial") return spatialListeners.add(listener);
1876
+ throw refusal(name, "UNSUPPORTED", `deviceState.${name}.subscribe is not replayable \u2014 advance the clock and read.`);
1877
+ }
1878
+ });
1879
+ const deviceState = {};
1880
+ for (const d of DOMAINS) deviceState[d] = domainFor(d);
1881
+ return { deviceState, clock, started: () => [...openSessions] };
1882
+ }
1883
+ function parseWalkJsonl(text) {
1884
+ const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
1885
+ if (!lines.length) throw new Error("Empty recording \u2014 no header line.");
1886
+ const first = JSON.parse(lines[0]);
1887
+ const header = first.header ?? first;
1888
+ const refusals = first.refusals ?? [];
1889
+ const samples = [];
1890
+ for (const line of lines.slice(1)) {
1891
+ const rec = JSON.parse(line);
1892
+ if (rec.refusal) {
1893
+ refusals.push(rec.refusal);
1894
+ continue;
1895
+ }
1896
+ if (typeof rec.t === "number") samples.push(rec);
1897
+ }
1898
+ return { header, refusals, samples };
1899
+ }
1900
+
209
1901
  // src/index.ts
210
1902
  function setupExpoProviders(opts) {
211
- (0, import_plugin_runtime.setHapticsProvider)(expoHaptics);
212
- (0, import_plugin_runtime.setBundleStorage)(new ExpoBundleStorage({ indexKey: opts?.bundleIndexKey }));
1903
+ (0, import_plugin_runtime2.setHapticsProvider)(expoHaptics);
1904
+ if (opts?.deviceProvider) (0, import_plugin_runtime2.setPluginNativeProvider)(opts.deviceProvider);
1905
+ (0, import_plugin_runtime2.setBundleStorage)(new ExpoBundleStorage({ indexKey: opts?.bundleIndexKey }));
213
1906
  (0, import_ui.setClipboardProvider)({
214
1907
  setString: (text) => ExpoClipboard.setStringAsync(text).then(() => {
215
1908
  })
216
1909
  });
217
- (0, import_plugin_runtime.registerBundleModules)({
1910
+ (0, import_plugin_runtime2.registerBundleModules)({
218
1911
  "expo-web-browser": ExpoWebBrowser,
219
1912
  "expo-linking": ExpoLinking,
220
1913
  ...opts?.bundleModules || {}
@@ -227,9 +1920,16 @@ function setupExpoProviders(opts) {
227
1920
  }
228
1921
  // Annotate the CommonJS export names for ESM import in node:
229
1922
  0 && (module.exports = {
1923
+ CameraTaskHost,
230
1924
  ExpoAttachmentCache,
231
1925
  ExpoBundleStorage,
1926
+ IMPLEMENTED_DOMAINS,
1927
+ cameraTasks,
1928
+ createDeviceState,
1929
+ createReplayDeviceState,
232
1930
  expoHaptics,
233
- setupExpoProviders
1931
+ parseWalkJsonl,
1932
+ setupExpoProviders,
1933
+ visualEngine
234
1934
  });
235
1935
  //# sourceMappingURL=index.js.map