@mentra/engine 0.1.0-beta.0 → 0.1.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -1
- package/build/engine.d.ts +11 -3
- package/build/engine.d.ts.map +1 -1
- package/build/engine.js +7 -2
- package/build/engine.js.map +1 -1
- package/build/facades/dev.d.ts.map +1 -1
- package/build/facades/dev.js +9 -5
- package/build/facades/dev.js.map +1 -1
- package/build/facades/gallery.js +1 -1
- package/build/facades/gallery.js.map +1 -1
- package/build/facades/glasses.d.ts +1 -0
- package/build/facades/glasses.d.ts.map +1 -1
- package/build/facades/glasses.js +19 -4
- package/build/facades/glasses.js.map +1 -1
- package/build/facades/glassesSettings.d.ts.map +1 -1
- package/build/facades/glassesSettings.js +1 -0
- package/build/facades/glassesSettings.js.map +1 -1
- package/build/facades/miniapps.d.ts +4 -0
- package/build/facades/miniapps.d.ts.map +1 -1
- package/build/facades/miniapps.js +5 -0
- package/build/facades/miniapps.js.map +1 -1
- package/build/facades/ota.d.ts +11 -2
- package/build/facades/ota.d.ts.map +1 -1
- package/build/facades/ota.js +19 -4
- package/build/facades/ota.js.map +1 -1
- package/build/facades/pairing.d.ts +4 -0
- package/build/facades/pairing.d.ts.map +1 -1
- package/build/facades/pairing.js +10 -8
- package/build/facades/pairing.js.map +1 -1
- package/build/facades/phoneNotifications.d.ts +0 -4
- package/build/facades/phoneNotifications.d.ts.map +1 -1
- package/build/facades/phoneNotifications.js +4 -14
- package/build/facades/phoneNotifications.js.map +1 -1
- package/build/index.d.ts +6 -3
- package/build/index.d.ts.map +1 -1
- package/build/index.js +4 -2
- package/build/index.js.map +1 -1
- package/build/internal.d.ts +2 -2
- package/build/internal.d.ts.map +1 -1
- package/build/internal.js +1 -1
- package/build/internal.js.map +1 -1
- package/build/react/MentraLiveOtaFlow.d.ts +38 -0
- package/build/react/MentraLiveOtaFlow.d.ts.map +1 -0
- package/build/react/MentraLiveOtaFlow.js +528 -0
- package/build/react/MentraLiveOtaFlow.js.map +1 -0
- package/build/react/index.d.ts +2 -0
- package/build/react/index.d.ts.map +1 -0
- package/build/react/index.js +2 -0
- package/build/react/index.js.map +1 -0
- package/build/react/useEngineSnapshot.d.ts +2 -0
- package/build/react/useEngineSnapshot.d.ts.map +1 -0
- package/build/react/useEngineSnapshot.js +14 -0
- package/build/react/useEngineSnapshot.js.map +1 -0
- package/build/runtime/bootstrap.d.ts +24 -1
- package/build/runtime/bootstrap.d.ts.map +1 -1
- package/build/runtime/bootstrap.js +17 -0
- package/build/runtime/bootstrap.js.map +1 -1
- package/build/runtime/scanQrSeam.d.ts +7 -0
- package/build/runtime/scanQrSeam.d.ts.map +1 -0
- package/build/runtime/scanQrSeam.js +16 -0
- package/build/runtime/scanQrSeam.js.map +1 -0
- package/build/services/AppRegistry.d.ts +18 -8
- package/build/services/AppRegistry.d.ts.map +1 -1
- package/build/services/AppRegistry.js +44 -45
- package/build/services/AppRegistry.js.map +1 -1
- package/build/services/AudioCloudUplink.d.ts +9 -3
- package/build/services/AudioCloudUplink.d.ts.map +1 -1
- package/build/services/AudioCloudUplink.js +9 -3
- package/build/services/AudioCloudUplink.js.map +1 -1
- package/build/services/AudioPlaybackService.d.ts +9 -1
- package/build/services/AudioPlaybackService.d.ts.map +1 -1
- package/build/services/AudioPlaybackService.js +77 -32
- package/build/services/AudioPlaybackService.js.map +1 -1
- package/build/services/BlobStore.d.ts +2 -1
- package/build/services/BlobStore.d.ts.map +1 -1
- package/build/services/BlobStore.js +17 -9
- package/build/services/BlobStore.js.map +1 -1
- package/build/services/CloudAudioSubscriptionSync.d.ts.map +1 -1
- package/build/services/CloudAudioSubscriptionSync.js +13 -1
- package/build/services/CloudAudioSubscriptionSync.js.map +1 -1
- package/build/services/CloudClientService.d.ts +15 -0
- package/build/services/CloudClientService.d.ts.map +1 -1
- package/build/services/CloudClientService.js +75 -0
- package/build/services/CloudClientService.js.map +1 -1
- package/build/services/ForegroundLocationPermission.d.ts +13 -0
- package/build/services/ForegroundLocationPermission.d.ts.map +1 -0
- package/build/services/ForegroundLocationPermission.js +12 -0
- package/build/services/ForegroundLocationPermission.js.map +1 -0
- package/build/services/GlassesSettingsSync.d.ts.map +1 -1
- package/build/services/GlassesSettingsSync.js +9 -3
- package/build/services/GlassesSettingsSync.js.map +1 -1
- package/build/services/GlassesStatusProjection.d.ts +2 -1
- package/build/services/GlassesStatusProjection.d.ts.map +1 -1
- package/build/services/GlassesStatusProjection.js +15 -8
- package/build/services/GlassesStatusProjection.js.map +1 -1
- package/build/services/HotspotOtaTransport.d.ts +29 -0
- package/build/services/HotspotOtaTransport.d.ts.map +1 -0
- package/build/services/HotspotOtaTransport.js +146 -0
- package/build/services/HotspotOtaTransport.js.map +1 -0
- package/build/services/HotspotShutdown.d.ts +17 -0
- package/build/services/HotspotShutdown.d.ts.map +1 -0
- package/build/services/HotspotShutdown.js +29 -0
- package/build/services/HotspotShutdown.js.map +1 -0
- package/build/services/LocalDisplayManager.d.ts +15 -0
- package/build/services/LocalDisplayManager.d.ts.map +1 -1
- package/build/services/LocalDisplayManager.js +106 -20
- package/build/services/LocalDisplayManager.js.map +1 -1
- package/build/services/LocalMiniappRuntime.d.ts +67 -1
- package/build/services/LocalMiniappRuntime.d.ts.map +1 -1
- package/build/services/LocalMiniappRuntime.js +486 -126
- package/build/services/LocalMiniappRuntime.js.map +1 -1
- package/build/services/LocalMiniappStorage.d.ts +32 -0
- package/build/services/LocalMiniappStorage.d.ts.map +1 -0
- package/build/services/LocalMiniappStorage.js +66 -0
- package/build/services/LocalMiniappStorage.js.map +1 -0
- package/build/services/LocalMiniappUserIdentity.d.ts +20 -0
- package/build/services/LocalMiniappUserIdentity.d.ts.map +1 -0
- package/build/services/LocalMiniappUserIdentity.js +43 -0
- package/build/services/LocalMiniappUserIdentity.js.map +1 -0
- package/build/services/MicStateCoordinator.d.ts +42 -1
- package/build/services/MicStateCoordinator.d.ts.map +1 -1
- package/build/services/MicStateCoordinator.js +141 -3
- package/build/services/MicStateCoordinator.js.map +1 -1
- package/build/services/MiniappLauncher.d.ts.map +1 -1
- package/build/services/MiniappLauncher.js +23 -3
- package/build/services/MiniappLauncher.js.map +1 -1
- package/build/services/MiniappLiveness.d.ts +12 -0
- package/build/services/MiniappLiveness.d.ts.map +1 -0
- package/build/services/MiniappLiveness.js +16 -0
- package/build/services/MiniappLiveness.js.map +1 -0
- package/build/services/OtaArtifactDownloader.d.ts +65 -0
- package/build/services/OtaArtifactDownloader.d.ts.map +1 -0
- package/build/services/OtaArtifactDownloader.js +226 -0
- package/build/services/OtaArtifactDownloader.js.map +1 -0
- package/build/services/OtaAutoChain.d.ts +34 -0
- package/build/services/OtaAutoChain.d.ts.map +1 -0
- package/build/services/OtaAutoChain.js +83 -0
- package/build/services/OtaAutoChain.js.map +1 -0
- package/build/services/OtaErrorMapping.d.ts +18 -0
- package/build/services/OtaErrorMapping.d.ts.map +1 -0
- package/build/services/OtaErrorMapping.js +63 -0
- package/build/services/OtaErrorMapping.js.map +1 -0
- package/build/services/OtaInstallCoordinator.d.ts +94 -14
- package/build/services/OtaInstallCoordinator.d.ts.map +1 -1
- package/build/services/OtaInstallCoordinator.js +574 -130
- package/build/services/OtaInstallCoordinator.js.map +1 -1
- package/build/services/OtaService.d.ts.map +1 -1
- package/build/services/OtaService.js +8 -1
- package/build/services/OtaService.js.map +1 -1
- package/build/services/OtaUpdateCheckService.d.ts +38 -3
- package/build/services/OtaUpdateCheckService.d.ts.map +1 -1
- package/build/services/OtaUpdateCheckService.js +142 -22
- package/build/services/OtaUpdateCheckService.js.map +1 -1
- package/build/services/PhoneCalendarService.d.ts.map +1 -1
- package/build/services/PhoneCalendarService.js +22 -1
- package/build/services/PhoneCalendarService.js.map +1 -1
- package/build/services/PhoneCameraFovCoordinator.d.ts +2 -0
- package/build/services/PhoneCameraFovCoordinator.d.ts.map +1 -1
- package/build/services/PhoneCameraFovCoordinator.js +14 -0
- package/build/services/PhoneCameraFovCoordinator.js.map +1 -1
- package/build/services/PhoneNotificationsSync.d.ts.map +1 -1
- package/build/services/PhoneNotificationsSync.js +12 -10
- package/build/services/PhoneNotificationsSync.js.map +1 -1
- package/build/services/PhonePhotoCoordinator.d.ts +10 -3
- package/build/services/PhonePhotoCoordinator.d.ts.map +1 -1
- package/build/services/PhonePhotoCoordinator.js +21 -3
- package/build/services/PhonePhotoCoordinator.js.map +1 -1
- package/build/services/PhoneStreamCoordinator.d.ts +8 -1
- package/build/services/PhoneStreamCoordinator.d.ts.map +1 -1
- package/build/services/PhoneStreamCoordinator.js +125 -13
- package/build/services/PhoneStreamCoordinator.js.map +1 -1
- package/build/services/PhoneVideoCoordinator.d.ts +2 -0
- package/build/services/PhoneVideoCoordinator.d.ts.map +1 -1
- package/build/services/PhoneVideoCoordinator.js +10 -0
- package/build/services/PhoneVideoCoordinator.js.map +1 -1
- package/build/services/SceneRenderer.d.ts.map +1 -1
- package/build/services/SceneRenderer.js +15 -0
- package/build/services/SceneRenderer.js.map +1 -1
- package/build/services/SupportProfileSync.d.ts +22 -0
- package/build/services/SupportProfileSync.d.ts.map +1 -0
- package/build/services/SupportProfileSync.js +213 -0
- package/build/services/SupportProfileSync.js.map +1 -0
- package/build/services/TtsTextSanitizer.d.ts +5 -0
- package/build/services/TtsTextSanitizer.d.ts.map +1 -0
- package/build/services/TtsTextSanitizer.js +61 -0
- package/build/services/TtsTextSanitizer.js.map +1 -0
- package/build/services/WifiAdbRequest.d.ts +17 -0
- package/build/services/WifiAdbRequest.d.ts.map +1 -0
- package/build/services/WifiAdbRequest.js +35 -0
- package/build/services/WifiAdbRequest.js.map +1 -0
- package/build/services/asg/asgCameraApi.d.ts +3 -0
- package/build/services/asg/asgCameraApi.d.ts.map +1 -1
- package/build/services/asg/asgCameraApi.js +72 -2
- package/build/services/asg/asgCameraApi.js.map +1 -1
- package/build/services/asg/gallerySyncService.d.ts.map +1 -1
- package/build/services/asg/gallerySyncService.js +26 -14
- package/build/services/asg/gallerySyncService.js.map +1 -1
- package/build/services/asg/localNetworkTransport.d.ts +2 -2
- package/build/services/asg/localNetworkTransport.d.ts.map +1 -1
- package/build/services/asg/localNetworkTransport.js +6 -6
- package/build/services/asg/localNetworkTransport.js.map +1 -1
- package/build/services/audioPlaybackAssets.d.ts +8 -0
- package/build/services/audioPlaybackAssets.d.ts.map +1 -0
- package/build/services/audioPlaybackAssets.js +7 -0
- package/build/services/audioPlaybackAssets.js.map +1 -0
- package/build/services/glassesClockSync.js +2 -2
- package/build/services/glassesClockSync.js.map +1 -1
- package/build/services/manifestActions.d.ts +7 -0
- package/build/services/manifestActions.d.ts.map +1 -0
- package/build/services/manifestActions.js +25 -0
- package/build/services/manifestActions.js.map +1 -0
- package/build/services/otaDisplayState.d.ts +22 -11
- package/build/services/otaDisplayState.d.ts.map +1 -1
- package/build/services/otaDisplayState.js +36 -14
- package/build/services/otaDisplayState.js.map +1 -1
- package/build/services/otaInstallPolicy.d.ts +15 -3
- package/build/services/otaInstallPolicy.d.ts.map +1 -1
- package/build/services/otaInstallPolicy.js +24 -3
- package/build/services/otaInstallPolicy.js.map +1 -1
- package/build/services/otaManifestUrl.d.ts +2 -0
- package/build/services/otaManifestUrl.d.ts.map +1 -0
- package/build/services/{asgOtaVersionUrl.js → otaManifestUrl.js} +15 -5
- package/build/services/otaManifestUrl.js.map +1 -0
- package/build/services/slimStreamStatus.d.ts +11 -0
- package/build/services/slimStreamStatus.d.ts.map +1 -1
- package/build/services/slimStreamStatus.js +14 -4
- package/build/services/slimStreamStatus.js.map +1 -1
- package/build/stores/apps.d.ts.map +1 -1
- package/build/stores/apps.js +11 -0
- package/build/stores/apps.js.map +1 -1
- package/build/stores/bluetoothSettingKeys.d.ts.map +1 -1
- package/build/stores/bluetoothSettingKeys.js +2 -0
- package/build/stores/bluetoothSettingKeys.js.map +1 -1
- package/build/stores/gallerySync.d.ts +2 -0
- package/build/stores/gallerySync.d.ts.map +1 -1
- package/build/stores/gallerySync.js +2 -0
- package/build/stores/gallerySync.js.map +1 -1
- package/build/stores/glasses.d.ts.map +1 -1
- package/build/stores/glasses.js +3 -0
- package/build/stores/glasses.js.map +1 -1
- package/build/stores/settings.d.ts +17 -0
- package/build/stores/settings.d.ts.map +1 -1
- package/build/stores/settings.js +152 -19
- package/build/stores/settings.js.map +1 -1
- package/build/types/applet.d.ts +2 -0
- package/build/types/applet.d.ts.map +1 -1
- package/build/types/applet.js.map +1 -1
- package/build/types/enums.d.ts +1 -0
- package/build/types/enums.d.ts.map +1 -1
- package/build/types/enums.js +1 -0
- package/build/types/enums.js.map +1 -1
- package/build/types/hardware.d.ts +1 -0
- package/build/types/hardware.d.ts.map +1 -1
- package/build/types/hardware.js +14 -0
- package/build/types/hardware.js.map +1 -1
- package/build/utils/configuredDevHost.d.ts +6 -0
- package/build/utils/configuredDevHost.d.ts.map +1 -0
- package/build/utils/configuredDevHost.js +19 -0
- package/build/utils/configuredDevHost.js.map +1 -0
- package/build/utils/devMiniappLaunch.d.ts +19 -8
- package/build/utils/devMiniappLaunch.d.ts.map +1 -1
- package/build/utils/devMiniappLaunch.js +144 -21
- package/build/utils/devMiniappLaunch.js.map +1 -1
- package/build/utils/diagnosticContext.d.ts.map +1 -1
- package/build/utils/diagnosticContext.js +15 -17
- package/build/utils/diagnosticContext.js.map +1 -1
- package/build/utils/hardware/hardware.d.ts.map +1 -1
- package/build/utils/hardware/hardware.js +7 -3
- package/build/utils/hardware/hardware.js.map +1 -1
- package/build/utils/miniappDiagnostics.d.ts +64 -0
- package/build/utils/miniappDiagnostics.d.ts.map +1 -0
- package/build/utils/miniappDiagnostics.js +173 -0
- package/build/utils/miniappDiagnostics.js.map +1 -0
- package/build/utils/timers/timers.d.ts.map +1 -1
- package/build/utils/timers/timers.js +55 -18
- package/build/utils/timers/timers.js.map +1 -1
- package/package.json +27 -18
- package/src/assets/silence.wav +0 -0
- package/src/engine.ts +7 -2
- package/src/facades/dev.ts +9 -5
- package/src/facades/gallery.ts +1 -1
- package/src/facades/glasses.ts +17 -4
- package/src/facades/glassesSettings.ts +5 -0
- package/src/facades/miniapps.ts +7 -0
- package/src/facades/ota.ts +19 -4
- package/src/facades/pairing.ts +11 -7
- package/src/facades/phoneNotifications.ts +4 -13
- package/src/index.ts +26 -2
- package/src/internal.ts +2 -1
- package/src/react/MentraLiveOtaFlow.tsx +856 -0
- package/src/react/index.ts +7 -0
- package/src/react/useEngineSnapshot.ts +16 -0
- package/src/runtime/bootstrap.ts +33 -1
- package/src/runtime/scanQrSeam.ts +20 -0
- package/src/services/AppRegistry.ts +72 -48
- package/src/services/AudioCloudUplink.ts +9 -3
- package/src/services/AudioPlaybackService.ts +94 -34
- package/src/services/BlobStore.ts +22 -9
- package/src/services/CloudAudioSubscriptionSync.ts +13 -1
- package/src/services/CloudClientService.ts +74 -0
- package/src/services/ForegroundLocationPermission.ts +24 -0
- package/src/services/GlassesSettingsSync.ts +9 -3
- package/src/services/GlassesStatusProjection.ts +16 -8
- package/src/services/HotspotOtaTransport.ts +184 -0
- package/src/services/HotspotShutdown.ts +41 -0
- package/src/services/LocalDisplayManager.ts +112 -21
- package/src/services/LocalMiniappRuntime.ts +576 -130
- package/src/services/LocalMiniappStorage.ts +82 -0
- package/src/services/LocalMiniappUserIdentity.ts +46 -0
- package/src/services/MicStateCoordinator.ts +169 -4
- package/src/services/MiniappLauncher.ts +30 -3
- package/src/services/MiniappLiveness.ts +24 -0
- package/src/services/OtaArtifactDownloader.ts +312 -0
- package/src/services/OtaAutoChain.ts +106 -0
- package/src/services/OtaErrorMapping.ts +80 -0
- package/src/services/OtaInstallCoordinator.ts +645 -143
- package/src/services/OtaService.ts +11 -5
- package/src/services/OtaUpdateCheckService.ts +180 -20
- package/src/services/PhoneCalendarService.ts +27 -4
- package/src/services/PhoneCameraFovCoordinator.ts +15 -0
- package/src/services/PhoneNotificationsSync.ts +12 -10
- package/src/services/PhonePhotoCoordinator.ts +33 -7
- package/src/services/PhoneStreamCoordinator.ts +139 -25
- package/src/services/PhoneVideoCoordinator.ts +11 -0
- package/src/services/SceneRenderer.ts +16 -0
- package/src/services/SupportProfileSync.ts +218 -0
- package/src/services/TtsTextSanitizer.ts +66 -0
- package/src/services/WifiAdbRequest.ts +53 -0
- package/src/services/asg/asgCameraApi.ts +99 -8
- package/src/services/asg/gallerySyncService.ts +28 -19
- package/src/services/asg/localNetworkTransport.ts +7 -11
- package/src/services/audioPlaybackAssets.ts +8 -0
- package/src/services/glassesClockSync.ts +2 -2
- package/src/services/manifestActions.ts +30 -0
- package/src/services/otaDisplayState.ts +57 -16
- package/src/services/otaInstallPolicy.ts +29 -3
- package/src/services/{asgOtaVersionUrl.ts → otaManifestUrl.ts} +16 -4
- package/src/services/slimStreamStatus.ts +16 -5
- package/src/stores/apps.ts +12 -0
- package/src/stores/bluetoothSettingKeys.ts +2 -0
- package/src/stores/gallerySync.ts +4 -0
- package/src/stores/glasses.ts +3 -0
- package/src/stores/settings.ts +174 -21
- package/src/types/applet.ts +2 -0
- package/src/types/enums.ts +2 -1
- package/src/types/hardware.ts +17 -0
- package/src/utils/configuredDevHost.ts +17 -0
- package/src/utils/devMiniappLaunch.ts +151 -23
- package/src/utils/diagnosticContext.ts +17 -17
- package/src/utils/hardware/hardware.ts +7 -9
- package/src/utils/miniappDiagnostics.ts +226 -0
- package/src/utils/timers/timers.ts +57 -21
- package/build/services/asgOtaVersionUrl.d.ts +0 -2
- package/build/services/asgOtaVersionUrl.d.ts.map +0 -1
- package/build/services/asgOtaVersionUrl.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MiniappLauncher.js","sourceRoot":"","sources":["../../src/services/MiniappLauncher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAC,IAAI,EAAC,MAAM,kBAAkB,CAAA;AAErC,OAAO,EAAC,oBAAoB,EAAC,MAAM,2BAA2B,CAAA;AAC9D,OAAO,EAAC,OAAO,EAAC,MAAM,0BAA0B,CAAA;AAChD,OAAO,WAAW,E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CAAC,GAAG,CAAC,WAAW,CAAC,CAAA;QAC9C,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,MAAM,OAAO,CAAA;YACf,CAAC;YAAC,MAAM,CAAC;gBACP,mEAAmE;YACrE,CAAC;QACH,CAAC;QACD,MAAM,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAA;IACjD,CAAC;IAED,4EAA4E;IAEpE,YAAY,CAAC,WAAmB;QACtC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAS,GAAG,WAAW,UAAU,CAAC,CAAA;QACxD,OAAO,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;IACxC,CAAC;IAED,4EAA4E;IACpE,cAAc,CAAC,WAA+B,EAAE,WAAmB;QACzE,IAAI,WAAW,EAAE,CAAC;YAChB,MAAM,CAAC,GAAG,QAAQ,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;YACnC,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;gBAAE,OAAO,CAAC,CAAA;QAClC,CAAC;QACD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAS,GAAG,WAAW,WAAW,CAAC,CAAA;QAC9D,IAAI,MAAM,CAAC,KAAK,EAAE;YAAE,OAAO,MAAM,CAAC,KAAK,CAAA;QACvC,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAA","sourcesContent":["/**\n * MiniappLauncher — headless launch/teardown of a local miniapp's background\n * JS context.\n *\n * This is the one piece of \"run a miniapp\" that used to live inside the\n * `LocalMiniappView` React component (resolve the bundle → read the manifest →\n * `spawnAndRegister`), triggered only when the Compositor mounted that\n * component on foreground. Pulling it into the runtime means:\n *\n * - `start()` can actually spawn an app even when nothing foregrounds it\n * (e.g. a system app launching another miniapp via `session.miniapps`).\n * - the action broker can wake a stopped target headlessly — no UI at all.\n * - the dev hot-reload respawn path and the WebView mount path share one\n * resolve+spawn recipe instead of three copies.\n *\n * The launcher is **headless**: no React, no RN components. The engine-owned\n * MiniappEngine hands it the {@link MentraJSRouter} instance once during\n * engine construction. OEMs embedding the runtime drive miniapp lifecycle\n * through the engine facade and stores, not a separate launcher configure API.\n *\n * Boundary: the launcher owns the **background** context. WebView *rendering*\n * (the UI layer) stays with the host — the launcher just hands back the\n * resolved UI entry so the host can mount its `<WebView>`.\n */\n\nimport {File} from \"expo-file-system\"\n\nimport {decideDevLaunchRoute} from \"../utils/devMiniappLaunch\"\nimport {storage} from \"../utils/storage/storage\"\nimport appRegistry, {getLocalAppRunningState, saveLocalAppRunningState} from \"./AppRegistry\"\nimport devServerBridge from \"./DevServerBridge\"\nimport localMiniappRuntime, {type InstalledMiniappManifest} from \"./LocalMiniappRuntime\"\nimport type {MentraJSRouter} from \"./MentraJSRouter\"\n\ninterface LauncherDeps {\n /** The host-constructed router (needs the native Crust binding). */\n router: MentraJSRouter\n}\n\n/** Hints the host may pass from a view's props to avoid re-deriving them. */\nexport interface LaunchHints {\n devUrl?: string\n version?: string\n devPort?: string\n}\n\n/** Everything the launcher resolved for a package — bg source + UI entry. */\nexport interface ResolvedBundle {\n bgSource: string\n uiUri: string | null\n uiBaseDir: string | null\n declaredPermissions: string[]\n installedManifest?: InstalledMiniappManifest\n /** Set for dev miniapps (HTTP off the dev server); null for released. */\n devUrl: string | null\n devPort: number | null\n}\n\n/** What the host needs back to render the UI layer. */\nexport interface LaunchResult {\n uiUri: string | null\n uiBaseDir: string | null\n}\n\nclass MiniappLauncher {\n private deps: LauncherDeps | null = null\n\n /**\n * In-flight launches keyed by packageName. Both apps.ts start() and the\n * WebView mount call ensureRunning() before the first spawnAndRegister\n * resolves — without this, neither sees the package in registeredPackages()\n * yet and both spawn the same context (a clobber/double-spawn). Concurrent\n * callers share the same promise.\n */\n private readonly inFlight = new Map<string, Promise<LaunchResult>>()\n\n /** Wire the router in. Called once from MiniappEngine construction. */\n configure(deps: LauncherDeps): void {\n this.deps = deps\n }\n\n private requireRouter(): MentraJSRouter {\n if (!this.deps) {\n throw new Error(\"MiniappLauncher not configured — ensureMiniappEngine() has not run\")\n }\n return this.deps.router\n }\n\n /** True iff the package's background JS context is currently spawned. */\n isRunning(packageName: string): boolean {\n return this.deps?.router.registeredPackages().includes(packageName) ?? false\n }\n\n /**\n * Resolve the background JS source + UI entry + declared permissions for a\n * package. Handles both dev (HTTP off the running dev server) and released\n * (file:// from the installed snapshot). Reads disk/network/storage; does\n * NOT spawn. Returns null when the bundle can't be resolved (dev server\n * unreachable, missing entry, no installed version).\n */\n async resolveBundle(packageName: string, hints?: LaunchHints): Promise<ResolvedBundle | null> {\n const devUrl = hints?.devUrl ?? this.storedDevUrl(packageName)\n\n // --- Dev: load directly off the local dev server over HTTP. ---\n if (devUrl) {\n const route = await decideDevLaunchRoute(packageName, devUrl)\n if (route.decision === \"offline\" || !route.manifest) return null\n const manifest = route.manifest\n const entry = manifest.entry as {background?: string; ui?: string} | undefined\n if (!entry?.background) return null\n\n const base = devUrl.replace(/\\/$/, \"\")\n // entry.* are bundle-root paths (dist/ stripped); the dev server serves\n // files relative to cwd, so prepend dist/.\n const bgUrl = `${base}/dist/${entry.background.replace(/^\\.?\\/+/, \"\")}`\n const uiUri = entry.ui ? `${base}/dist/${entry.ui.replace(/^\\.?\\/+/, \"\")}` : null\n\n const perms = manifest.permissions as Array<{type?: string} | string> | undefined\n const declaredPermissions = (perms ?? [])\n .map((p) => (typeof p === \"string\" ? p : p?.type))\n .filter((t): t is string => typeof t === \"string\")\n const installedManifest: InstalledMiniappManifest = {\n name: manifest.name,\n permissions: manifest.permissions as InstalledMiniappManifest[\"permissions\"],\n hardwareRequirements: manifest.hardwareRequirements as InstalledMiniappManifest[\"hardwareRequirements\"],\n }\n\n let bgSource: string\n try {\n const res = await fetch(bgUrl)\n if (!res.ok) return null\n bgSource = await res.text()\n } catch {\n return null\n }\n\n return {\n bgSource,\n uiUri,\n uiBaseDir: uiUri ? uiUri.replace(/\\/[^/]+$/, \"/\") : null,\n declaredPermissions,\n installedManifest,\n devUrl,\n devPort: this.resolveDevPort(hints?.devPort, packageName),\n }\n }\n\n // --- Released: resolve from the installed file:// snapshot. ---\n const version = hints?.version ?? (await appRegistry.getActiveVersion(packageName))\n if (!version) return null\n const entryPaths = appRegistry.getMiniappEntryPaths(packageName, version)\n if (!entryPaths?.background) return null\n\n const manifest = appRegistry.getMiniappManifest(packageName, version) as {\n name?: string\n permissions?: Array<{type: string; required?: boolean; description?: string}>\n hardwareRequirements?: Array<{type: string; level: string; description?: string}>\n } | null\n const declaredPermissions = (manifest?.permissions ?? [])\n .map((p) => p.type)\n .filter((t): t is string => typeof t === \"string\")\n const installedManifest: InstalledMiniappManifest | undefined = manifest\n ? {name: manifest.name, permissions: manifest.permissions, hardwareRequirements: manifest.hardwareRequirements}\n : undefined\n\n let bgSource: string\n try {\n bgSource = new File(entryPaths.background).textSync()\n } catch {\n return null\n }\n\n return {\n bgSource,\n uiUri: entryPaths.ui ?? null,\n uiBaseDir: entryPaths.ui ? entryPaths.ui.replace(/\\/[^/]+$/, \"/\") : null,\n declaredPermissions,\n installedManifest,\n devUrl: null,\n devPort: null,\n }\n }\n\n /**\n * Ensure a miniapp's background JS context is spawned. Idempotent — if the\n * context is already alive this is a no-op spawn-wise (it still resolves the\n * UI entry so a re-mounting host gets its `<WebView>` source back).\n *\n * Resolves once the context is SPAWNED. It does NOT block on the context's\n * CONNECT handshake — the host's WebView mount shouldn't wait on background\n * JS. Callers that need the context to be connected and ready to receive\n * messages (the action broker) follow up with\n * {@link LocalMiniappRuntime.waitForConnect}.\n */\n async ensureRunning(packageName: string, hints?: LaunchHints): Promise<LaunchResult> {\n const router = this.requireRouter()\n\n // Already spawned: best-effort resolve for the UI entry, never throw —\n // a headless caller that doesn't need UI gets {null, null} fast even if\n // the dev server has since dropped.\n if (router.registeredPackages().includes(packageName)) {\n const existing = await this.resolveBundle(packageName, hints).catch(() => null)\n return {uiUri: existing?.uiUri ?? null, uiBaseDir: existing?.uiBaseDir ?? null}\n }\n\n // Coalesce concurrent launches of the same package onto one promise.\n const pending = this.inFlight.get(packageName)\n if (pending) return pending\n\n const launch = this.spawn(packageName, hints)\n this.inFlight.set(packageName, launch)\n try {\n return await launch\n } finally {\n this.inFlight.delete(packageName)\n }\n }\n\n /** Resolve the bundle and spawn the context. Serialized via {@link inFlight}. */\n private async spawn(packageName: string, hints?: LaunchHints): Promise<LaunchResult> {\n const router = this.requireRouter()\n const resolved = await this.resolveBundle(packageName, hints)\n if (!resolved) {\n throw new Error(`MiniappLauncher: cannot resolve bundle for ${packageName}`)\n }\n\n // Re-check after the async resolve: a different path may have spawned it\n // while we were fetching/reading the bundle.\n if (!router.registeredPackages().includes(packageName)) {\n const ok = await router.spawnAndRegister(packageName, resolved.bgSource, {\n permissions: resolved.declaredPermissions,\n installedManifest: resolved.installedManifest,\n })\n if (!ok) {\n throw new Error(`MiniappLauncher: spawn failed for ${packageName}`)\n }\n\n // Dev: wire the hot-reload + log-forwarding sidecar. No-op in prod\n // (devServerBridge silently drops when no sidecar is up).\n if (resolved.devUrl && resolved.devPort != null) {\n devServerBridge.connect(packageName, resolved.devUrl, resolved.devPort)\n } else if (resolved.devUrl) {\n // Dev miniapp with no resolvable port — it still launches, but hot\n // reload + log forwarding won't connect. Surface it instead of failing\n // silently (the old inline path hard-failed with \"no dev port\").\n console.warn(`MiniappLauncher: ${packageName} has no dev port — hot reload + log forwarding disabled`)\n }\n }\n\n return {uiUri: resolved.uiUri, uiBaseDir: resolved.uiBaseDir}\n }\n\n /**\n * Re-spawn local miniapps that were running when the app was last killed.\n *\n * Cloud apps run on a remote server: the cloud persists which ones are\n * running and resurrects them when the phone reconnects, so a host-app\n * restart brings them back on its own. Local (phone-hosted) miniapps run in\n * the phone's own JS engine — a host-process kill tears down their JSContext\n * and there is no server to resurrect them, so without this they silently\n * stay stopped on the next launch even though the user left them running.\n *\n * Each local miniapp persists its running flag to disk on start/stop\n * (`saveLocalAppRunningState`, via the applet's `onStart`/`onStop`). We read\n * those flags back and re-spawn the background context headlessly (no\n * foreground, no navigation) — the spawn registers the package so the home\n * tray/switcher project it as running, exactly as a normal start would. The\n * WebView, if any, re-attaches lazily when the user opens the app.\n *\n * Idempotent and best-effort: skips already-spawned contexts, and clears the\n * persisted flag for any app whose bundle can no longer be resolved\n * (uninstalled, or dev server gone) so a dead entry doesn't retry every boot.\n * Not compatibility-gated: a previously-running background app shouldn't be\n * dropped just because glasses are momentarily disconnected at boot — it\n * resumes when they reconnect, same as mid-session.\n */\n async autostartLocalMiniapps(): Promise<void> {\n const apps = await appRegistry.getInstalledMiniapps()\n for (const app of apps) {\n // Only phone-hosted miniapps have a JSContext to re-spawn. Offline\n // built-ins (`local:false, offline:true`) restore their native running\n // state elsewhere and have no bundle to launch.\n if (!app.local) continue\n if (!getLocalAppRunningState(app.packageName)) continue\n if (this.isRunning(app.packageName)) continue\n try {\n await this.ensureRunning(app.packageName)\n } catch (e) {\n console.warn(`MiniappLauncher: autostart failed for ${app.packageName} — clearing stale running flag`, e)\n saveLocalAppRunningState(app.packageName, false)\n }\n }\n }\n\n /**\n * Ensure the context is running AND has completed its CONNECT handshake.\n * Used by the action broker, which must not deliver to a context that hasn't\n * come up yet. Throws on spawn failure or connect timeout.\n */\n async ensureConnected(packageName: string, connectTimeoutMs = 10_000, hints?: LaunchHints): Promise<void> {\n await this.ensureRunning(packageName, hints)\n await localMiniappRuntime.waitForConnect(packageName, connectTimeoutMs)\n }\n\n /** Tear down a miniapp's background JS context. */\n async stop(packageName: string): Promise<void> {\n // If a launch is in flight, let it finish first. Otherwise unregister()\n // no-ops on the not-yet-registered package and the pending spawn then\n // re-registers the context — leaving it running despite the stop.\n const pending = this.inFlight.get(packageName)\n if (pending) {\n try {\n await pending\n } catch {\n // Launch failed — nothing got registered, so nothing to tear down.\n }\n }\n await this.deps?.router.unregister(packageName)\n }\n\n // --- internals -----------------------------------------------------------\n\n private storedDevUrl(packageName: string): string | undefined {\n const r = storage.load<string>(`${packageName}_dev_url`)\n return r.is_ok() ? r.value : undefined\n }\n\n /** resolveDevPort — moved verbatim from the old LocalMiniappView helper. */\n private resolveDevPort(searchParam: string | undefined, packageName: string): number | null {\n if (searchParam) {\n const n = parseInt(searchParam, 10)\n if (Number.isFinite(n)) return n\n }\n const stored = storage.load<number>(`${packageName}_dev_port`)\n if (stored.is_ok()) return stored.value\n return null\n }\n}\n\nexport const miniappLauncher = new MiniappLauncher()\n"]}
|
|
1
|
+
{"version":3,"file":"MiniappLauncher.js","sourceRoot":"","sources":["../../src/services/MiniappLauncher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAC,IAAI,EAAC,MAAM,kBAAkB,CAAA;AAErC,OAAO,EAAC,oBAAoB,EAAC,MAAM,2BAA2B,CAAA;AAC9D,OAAO,EAAC,OAAO,EAAC,MAAM,0BAA0B,CAAA;AAChD,OAAO,WAAW,EAAE,EAAC,uBAAuB,EAAE,wBAAwB,EAAC,MAAM,eAAe,CAAA;AAC5F,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAC/C,OAAO,mBAAoD,MAAM,uBAAuB,CAAA;AAiCxF,MAAM,eAAe;IACX,IAAI,GAAwB,IAAI,CAAA;IAExC;;;;;;OAMG;IACc,QAAQ,GAAG,IAAI,GAAG,EAAiC,CAAA;IAEpE,uEAAuE;IACvE,SAAS,CAAC,IAAkB;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;IAClB,CAAC;IAEO,aAAa;QACnB,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,oEAAoE,CAAC,CAAA;QACvF,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAA;IACzB,CAAC;IAED,yEAAyE;IACzE,SAAS,CAAC,WAAmB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AAO,CAAC,IAAI,CAAS,GAAG,WAAW,WAAW,CAAC,CAAA;QAC9D,IAAI,MAAM,CAAC,KAAK,EAAE;YAAE,OAAO,MAAM,CAAC,KAAK,CAAA;QACvC,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAA","sourcesContent":["/**\n * MiniappLauncher — headless launch/teardown of a local miniapp's background\n * JS context.\n *\n * This is the one piece of \"run a miniapp\" that used to live inside the\n * `LocalMiniappView` React component (resolve the bundle → read the manifest →\n * `spawnAndRegister`), triggered only when the Compositor mounted that\n * component on foreground. Pulling it into the runtime means:\n *\n * - `start()` can actually spawn an app even when nothing foregrounds it\n * (e.g. a system app launching another miniapp via `session.miniapps`).\n * - the action broker can wake a stopped target headlessly — no UI at all.\n * - the dev hot-reload respawn path and the WebView mount path share one\n * resolve+spawn recipe instead of three copies.\n *\n * The launcher is **headless**: no React, no RN components. The engine-owned\n * MiniappEngine hands it the {@link MentraJSRouter} instance once during\n * engine construction. OEMs embedding the runtime drive miniapp lifecycle\n * through the engine facade and stores, not a separate launcher configure API.\n *\n * Boundary: the launcher owns the **background** context. WebView *rendering*\n * (the UI layer) stays with the host — the launcher just hands back the\n * resolved UI entry so the host can mount its `<WebView>`.\n */\n\nimport {File} from \"expo-file-system\"\n\nimport {decideDevLaunchRoute} from \"../utils/devMiniappLaunch\"\nimport {storage} from \"../utils/storage/storage\"\nimport appRegistry, {getLocalAppRunningState, saveLocalAppRunningState} from \"./AppRegistry\"\nimport devServerBridge from \"./DevServerBridge\"\nimport localMiniappRuntime, {type InstalledMiniappManifest} from \"./LocalMiniappRuntime\"\nimport type {MentraJSRouter} from \"./MentraJSRouter\"\n\ninterface LauncherDeps {\n /** The host-constructed router (needs the native Crust binding). */\n router: MentraJSRouter\n}\n\n/** Hints the host may pass from a view's props to avoid re-deriving them. */\nexport interface LaunchHints {\n devUrl?: string\n version?: string\n devPort?: string\n}\n\n/** Everything the launcher resolved for a package — bg source + UI entry. */\nexport interface ResolvedBundle {\n bgSource: string\n uiUri: string | null\n uiBaseDir: string | null\n declaredPermissions: string[]\n installedManifest?: InstalledMiniappManifest\n /** Set for dev miniapps (HTTP off the dev server); null for released. */\n devUrl: string | null\n devPort: number | null\n}\n\n/** What the host needs back to render the UI layer. */\nexport interface LaunchResult {\n uiUri: string | null\n uiBaseDir: string | null\n}\n\nclass MiniappLauncher {\n private deps: LauncherDeps | null = null\n\n /**\n * In-flight launches keyed by packageName. Both apps.ts start() and the\n * WebView mount call ensureRunning() before the first spawnAndRegister\n * resolves — without this, neither sees the package in registeredPackages()\n * yet and both spawn the same context (a clobber/double-spawn). Concurrent\n * callers share the same promise.\n */\n private readonly inFlight = new Map<string, Promise<LaunchResult>>()\n\n /** Wire the router in. Called once from MiniappEngine construction. */\n configure(deps: LauncherDeps): void {\n this.deps = deps\n }\n\n private requireRouter(): MentraJSRouter {\n if (!this.deps) {\n throw new Error(\"MiniappLauncher not configured — ensureMiniappEngine() has not run\")\n }\n return this.deps.router\n }\n\n /** True iff the package's background JS context is currently spawned. */\n isRunning(packageName: string): boolean {\n return this.deps?.router.registeredPackages().includes(packageName) ?? false\n }\n\n /**\n * Resolve the background JS source + UI entry + declared permissions for a\n * package. Handles both dev (HTTP off the running dev server) and released\n * (file:// from the installed snapshot). Reads disk/network/storage; does\n * NOT spawn. Returns null when the bundle can't be resolved (dev server\n * unreachable, missing entry, no installed version).\n */\n async resolveBundle(packageName: string, hints?: LaunchHints): Promise<ResolvedBundle | null> {\n const devUrl = hints?.devUrl ?? this.storedDevUrl(packageName)\n\n // --- Dev: load directly off the local dev server over HTTP. ---\n if (devUrl) {\n const route = await decideDevLaunchRoute(packageName, devUrl)\n if (route.decision === \"offline\" || !route.manifest) return null\n const manifest = route.manifest\n const entry = manifest.entry as {background?: string; ui?: string} | undefined\n if (!entry?.background) return null\n\n // Use the host that actually answered — may differ from the stored IP\n // after a laptop Wi-Fi change (mDNS / Metro failover inside decideDevLaunchRoute).\n const base = route.resolvedUrl.replace(/\\/$/, \"\")\n // entry.* are bundle-root paths (dist/ stripped); the dev server serves\n // files relative to cwd, so prepend dist/.\n const bgUrl = `${base}/dist/${entry.background.replace(/^\\.?\\/+/, \"\")}`\n const uiUri = entry.ui ? `${base}/dist/${entry.ui.replace(/^\\.?\\/+/, \"\")}` : null\n\n const perms = manifest.permissions as Array<{type?: string} | string> | undefined\n const declaredPermissions = (perms ?? [])\n .map((p) => (typeof p === \"string\" ? p : p?.type))\n .filter((t): t is string => typeof t === \"string\")\n const installedManifest: InstalledMiniappManifest = {\n packageName: typeof manifest.packageName === \"string\" ? manifest.packageName : packageName,\n name: manifest.name,\n version: typeof manifest.version === \"string\" ? manifest.version : undefined,\n sdkVersion: typeof manifest.sdkVersion === \"string\" ? manifest.sdkVersion : undefined,\n minHostVersion: typeof manifest.minHostVersion === \"string\" ? manifest.minHostVersion : undefined,\n type: typeof manifest.type === \"string\" ? manifest.type : undefined,\n entry: manifest.entry as InstalledMiniappManifest[\"entry\"],\n permissions: manifest.permissions as InstalledMiniappManifest[\"permissions\"],\n hardwareRequirements: manifest.hardwareRequirements as InstalledMiniappManifest[\"hardwareRequirements\"],\n actions: manifest.actions as InstalledMiniappManifest[\"actions\"],\n }\n\n let bgSource: string\n try {\n const res = await fetch(bgUrl)\n if (!res.ok) return null\n bgSource = await res.text()\n } catch {\n return null\n }\n\n return {\n bgSource,\n uiUri,\n uiBaseDir: uiUri ? uiUri.replace(/\\/[^/]+$/, \"/\") : null,\n declaredPermissions,\n installedManifest,\n devUrl: route.resolvedUrl,\n devPort: this.resolveDevPort(hints?.devPort, packageName),\n }\n }\n\n // --- Released: resolve from the installed file:// snapshot. ---\n const version = hints?.version ?? (await appRegistry.getActiveVersion(packageName))\n if (!version) return null\n const entryPaths = appRegistry.getMiniappEntryPaths(packageName, version)\n if (!entryPaths?.background) return null\n\n const manifest = appRegistry.getMiniappManifest(packageName, version) as {\n packageName?: string\n name?: string\n version?: string\n sdkVersion?: string\n minHostVersion?: string\n type?: string\n entry?: {background?: string; ui?: string}\n permissions?: Array<{type: string; required?: boolean; description?: string}>\n hardwareRequirements?: Array<{type: string; level: string; description?: string}>\n actions?: Array<{id?: unknown; description?: unknown; parameters?: unknown; outputSchema?: unknown}>\n } | null\n const declaredPermissions = (manifest?.permissions ?? [])\n .map((p) => p.type)\n .filter((t): t is string => typeof t === \"string\")\n const installedManifest: InstalledMiniappManifest | undefined = manifest\n ? {\n packageName: manifest.packageName ?? packageName,\n name: manifest.name,\n version: manifest.version ?? version,\n sdkVersion: manifest.sdkVersion,\n minHostVersion: manifest.minHostVersion,\n type: manifest.type,\n entry: manifest.entry,\n permissions: manifest.permissions,\n hardwareRequirements: manifest.hardwareRequirements,\n actions: manifest.actions,\n }\n : undefined\n\n let bgSource: string\n try {\n bgSource = new File(entryPaths.background).textSync()\n } catch {\n return null\n }\n\n return {\n bgSource,\n uiUri: entryPaths.ui ?? null,\n uiBaseDir: entryPaths.ui ? entryPaths.ui.replace(/\\/[^/]+$/, \"/\") : null,\n declaredPermissions,\n installedManifest,\n devUrl: null,\n devPort: null,\n }\n }\n\n /**\n * Ensure a miniapp's background JS context is spawned. Idempotent — if the\n * context is already alive this is a no-op spawn-wise (it still resolves the\n * UI entry so a re-mounting host gets its `<WebView>` source back).\n *\n * Resolves once the context is SPAWNED. It does NOT block on the context's\n * CONNECT handshake — the host's WebView mount shouldn't wait on background\n * JS. Callers that need the context to be connected and ready to receive\n * messages (the action broker) follow up with\n * {@link LocalMiniappRuntime.waitForConnect}.\n */\n async ensureRunning(packageName: string, hints?: LaunchHints): Promise<LaunchResult> {\n const router = this.requireRouter()\n\n // Already spawned: best-effort resolve for the UI entry, never throw —\n // a headless caller that doesn't need UI gets {null, null} fast even if\n // the dev server has since dropped.\n if (router.registeredPackages().includes(packageName)) {\n const existing = await this.resolveBundle(packageName, hints).catch(() => null)\n return {uiUri: existing?.uiUri ?? null, uiBaseDir: existing?.uiBaseDir ?? null}\n }\n\n // Coalesce concurrent launches of the same package onto one promise.\n const pending = this.inFlight.get(packageName)\n if (pending) return pending\n\n const launch = this.spawn(packageName, hints)\n this.inFlight.set(packageName, launch)\n try {\n return await launch\n } finally {\n this.inFlight.delete(packageName)\n }\n }\n\n /** Resolve the bundle and spawn the context. Serialized via {@link inFlight}. */\n private async spawn(packageName: string, hints?: LaunchHints): Promise<LaunchResult> {\n const router = this.requireRouter()\n const resolved = await this.resolveBundle(packageName, hints)\n if (!resolved) {\n throw new Error(`MiniappLauncher: cannot resolve bundle for ${packageName}`)\n }\n\n // Re-check after the async resolve: a different path may have spawned it\n // while we were fetching/reading the bundle.\n if (!router.registeredPackages().includes(packageName)) {\n const ok = await router.spawnAndRegister(packageName, resolved.bgSource, {\n permissions: resolved.declaredPermissions,\n installedManifest: resolved.installedManifest,\n })\n if (!ok) {\n throw new Error(`MiniappLauncher: spawn failed for ${packageName}`)\n }\n\n // Dev: wire the hot-reload + log-forwarding sidecar. No-op in prod\n // (devServerBridge silently drops when no sidecar is up).\n if (resolved.devUrl && resolved.devPort != null) {\n devServerBridge.connect(packageName, resolved.devUrl, resolved.devPort)\n } else if (resolved.devUrl) {\n // Dev miniapp with no resolvable port — it still launches, but hot\n // reload + log forwarding won't connect. Surface it instead of failing\n // silently (the old inline path hard-failed with \"no dev port\").\n console.warn(`MiniappLauncher: ${packageName} has no dev port — hot reload + log forwarding disabled`)\n }\n }\n\n return {uiUri: resolved.uiUri, uiBaseDir: resolved.uiBaseDir}\n }\n\n /**\n * Re-spawn local miniapps that were running when the app was last killed.\n *\n * Cloud apps run on a remote server: the cloud persists which ones are\n * running and resurrects them when the phone reconnects, so a host-app\n * restart brings them back on its own. Local (phone-hosted) miniapps run in\n * the phone's own JS engine — a host-process kill tears down their JSContext\n * and there is no server to resurrect them, so without this they silently\n * stay stopped on the next launch even though the user left them running.\n *\n * Each local miniapp persists its running flag to disk on start/stop\n * (`saveLocalAppRunningState`, via the applet's `onStart`/`onStop`). We read\n * those flags back and re-spawn the background context headlessly (no\n * foreground, no navigation) — the spawn registers the package so the home\n * tray/switcher project it as running, exactly as a normal start would. The\n * WebView, if any, re-attaches lazily when the user opens the app.\n *\n * Idempotent and best-effort: skips already-spawned contexts, and clears the\n * persisted flag for any app whose bundle can no longer be resolved\n * (uninstalled, or dev server gone) so a dead entry doesn't retry every boot.\n * Not compatibility-gated: a previously-running background app shouldn't be\n * dropped just because glasses are momentarily disconnected at boot — it\n * resumes when they reconnect, same as mid-session.\n */\n async autostartLocalMiniapps(): Promise<void> {\n const apps = await appRegistry.getInstalledMiniapps()\n for (const app of apps) {\n // Only phone-hosted miniapps have a JSContext to re-spawn. Offline\n // built-ins (`local:false, offline:true`) restore their native running\n // state elsewhere and have no bundle to launch.\n if (!app.local) continue\n if (!getLocalAppRunningState(app.packageName)) continue\n if (this.isRunning(app.packageName)) continue\n try {\n await this.ensureRunning(app.packageName)\n } catch (e) {\n console.warn(`MiniappLauncher: autostart failed for ${app.packageName} — clearing stale running flag`, e)\n saveLocalAppRunningState(app.packageName, false)\n }\n }\n }\n\n /**\n * Ensure the context is running AND has completed its CONNECT handshake.\n * Used by the action broker, which must not deliver to a context that hasn't\n * come up yet. Throws on spawn failure or connect timeout.\n */\n async ensureConnected(packageName: string, connectTimeoutMs = 10_000, hints?: LaunchHints): Promise<void> {\n await this.ensureRunning(packageName, hints)\n await localMiniappRuntime.waitForConnect(packageName, connectTimeoutMs)\n }\n\n /** Tear down a miniapp's background JS context. */\n async stop(packageName: string): Promise<void> {\n // If a launch is in flight, let it finish first. Otherwise unregister()\n // no-ops on the not-yet-registered package and the pending spawn then\n // re-registers the context — leaving it running despite the stop.\n const pending = this.inFlight.get(packageName)\n if (pending) {\n try {\n await pending\n } catch {\n // Launch failed — nothing got registered, so nothing to tear down.\n }\n }\n await this.deps?.router.unregister(packageName)\n }\n\n // --- internals -----------------------------------------------------------\n\n private storedDevUrl(packageName: string): string | undefined {\n const r = storage.load<string>(`${packageName}_dev_url`)\n return r.is_ok() ? r.value : undefined\n }\n\n /** resolveDevPort — moved verbatim from the old LocalMiniappView helper. */\n private resolveDevPort(searchParam: string | undefined, packageName: string): number | null {\n if (searchParam) {\n const n = parseInt(searchParam, 10)\n if (Number.isFinite(n)) return n\n }\n const stored = storage.load<number>(`${packageName}_dev_port`)\n if (stored.is_ok()) return stored.value\n return null\n }\n}\n\nexport const miniappLauncher = new MiniappLauncher()\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface MiniappPingLivenessDecision {
|
|
2
|
+
shouldUnregister: boolean;
|
|
3
|
+
unansweredPingRounds: number;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Advance liveness by one scheduled ping round.
|
|
7
|
+
*
|
|
8
|
+
* Counting actual rounds avoids treating time while React Native's scheduler
|
|
9
|
+
* was paused in the background as pings the miniapp failed to answer.
|
|
10
|
+
*/
|
|
11
|
+
export declare function advanceMiniappPingLiveness(unansweredPingRounds: number, timeoutThreshold: number): MiniappPingLivenessDecision;
|
|
12
|
+
//# sourceMappingURL=MiniappLiveness.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MiniappLiveness.d.ts","sourceRoot":"","sources":["../../src/services/MiniappLiveness.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,2BAA2B;IAC1C,gBAAgB,EAAE,OAAO,CAAA;IACzB,oBAAoB,EAAE,MAAM,CAAA;CAC7B;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,oBAAoB,EAAE,MAAM,EAC5B,gBAAgB,EAAE,MAAM,GACvB,2BAA2B,CAS7B"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Advance liveness by one scheduled ping round.
|
|
3
|
+
*
|
|
4
|
+
* Counting actual rounds avoids treating time while React Native's scheduler
|
|
5
|
+
* was paused in the background as pings the miniapp failed to answer.
|
|
6
|
+
*/
|
|
7
|
+
export function advanceMiniappPingLiveness(unansweredPingRounds, timeoutThreshold) {
|
|
8
|
+
if (unansweredPingRounds >= timeoutThreshold) {
|
|
9
|
+
return { shouldUnregister: true, unansweredPingRounds };
|
|
10
|
+
}
|
|
11
|
+
return {
|
|
12
|
+
shouldUnregister: false,
|
|
13
|
+
unansweredPingRounds: unansweredPingRounds + 1,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=MiniappLiveness.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"MiniappLiveness.js","sourceRoot":"","sources":["../../src/services/MiniappLiveness.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,oBAA4B,EAC5B,gBAAwB;IAExB,IAAI,oBAAoB,IAAI,gBAAgB,EAAE,CAAC;QAC7C,OAAO,EAAC,gBAAgB,EAAE,IAAI,EAAE,oBAAoB,EAAC,CAAA;IACvD,CAAC;IAED,OAAO;QACL,gBAAgB,EAAE,KAAK;QACvB,oBAAoB,EAAE,oBAAoB,GAAG,CAAC;KAC/C,CAAA;AACH,CAAC","sourcesContent":["export interface MiniappPingLivenessDecision {\n shouldUnregister: boolean\n unansweredPingRounds: number\n}\n\n/**\n * Advance liveness by one scheduled ping round.\n *\n * Counting actual rounds avoids treating time while React Native's scheduler\n * was paused in the background as pings the miniapp failed to answer.\n */\nexport function advanceMiniappPingLiveness(\n unansweredPingRounds: number,\n timeoutThreshold: number,\n): MiniappPingLivenessDecision {\n if (unansweredPingRounds >= timeoutThreshold) {\n return {shouldUnregister: true, unansweredPingRounds}\n }\n\n return {\n shouldUnregister: false,\n unansweredPingRounds: unansweredPingRounds + 1,\n }\n}\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { OtaCheckCurrentGlassesResult } from "./OtaUpdateCheckService";
|
|
2
|
+
/**
|
|
3
|
+
* Phone-side artifact staging for hotspot-served OTA (OS-1676).
|
|
4
|
+
*
|
|
5
|
+
* When the glasses have no WiFi, the phone downloads the OTA artifacts itself (over
|
|
6
|
+
* whatever network it is on — the user's tap on "update" is the consent) and serves them
|
|
7
|
+
* to the glasses via the LocalOtaServer over the glasses' hotspot. This module owns:
|
|
8
|
+
*
|
|
9
|
+
* - planning which artifacts the pending update actually needs (from the raw manifest the
|
|
10
|
+
* update check fetched, so the glasses re-parse byte-identical version data),
|
|
11
|
+
* - downloading them with .part staging and sha256 verification, keyed on disk by hash so
|
|
12
|
+
* retries and the post-APK continuation reuse verified files,
|
|
13
|
+
* - rewriting the manifest's URL fields to point at the phone server, and
|
|
14
|
+
* - cleanup once the update completes or the manifest moves on.
|
|
15
|
+
*/
|
|
16
|
+
export type OtaArtifactKind = "apk" | "mtk" | "bes";
|
|
17
|
+
export interface OtaArtifactPlanEntry {
|
|
18
|
+
kind: OtaArtifactKind;
|
|
19
|
+
/** URL this artifact is fetched from, exactly as it appears in the raw manifest. */
|
|
20
|
+
url: string;
|
|
21
|
+
/** Required content hash from the manifest. */
|
|
22
|
+
sha256: string;
|
|
23
|
+
}
|
|
24
|
+
export interface PreparedOtaArtifact extends OtaArtifactPlanEntry {
|
|
25
|
+
filePath: string;
|
|
26
|
+
}
|
|
27
|
+
export interface OtaArtifactDownloadProgress {
|
|
28
|
+
kind: OtaArtifactKind;
|
|
29
|
+
/** 0-based index of the artifact being downloaded. */
|
|
30
|
+
index: number;
|
|
31
|
+
totalCount: number;
|
|
32
|
+
/** Percent of the current artifact, 0-100 (0 when the server sent no length). */
|
|
33
|
+
artifactPercent: number;
|
|
34
|
+
bytesWritten: number;
|
|
35
|
+
contentLength: number;
|
|
36
|
+
}
|
|
37
|
+
export declare class OtaArtifactError extends Error {
|
|
38
|
+
readonly code: "artifact_download_failed" | "artifact_verify_failed" | "manifest_invalid";
|
|
39
|
+
constructor(code: "artifact_download_failed" | "artifact_verify_failed" | "manifest_invalid", message: string);
|
|
40
|
+
}
|
|
41
|
+
export declare function otaArtifactsDirectory(): string;
|
|
42
|
+
/**
|
|
43
|
+
* Derive the artifact list the pending update needs from a completed check.
|
|
44
|
+
* Works off the raw manifest body (not the normalized check fields) so the URLs and
|
|
45
|
+
* hashes match exactly what the glasses will re-parse.
|
|
46
|
+
*/
|
|
47
|
+
export declare function planArtifacts(result: OtaCheckCurrentGlassesResult): OtaArtifactPlanEntry[];
|
|
48
|
+
/**
|
|
49
|
+
* Download every planned artifact into the on-disk hash-keyed store, reusing files that
|
|
50
|
+
* already verify. Sequential on purpose: progress is legible and the hotspot window that
|
|
51
|
+
* follows is the slow part, not phone-side parallelism.
|
|
52
|
+
*/
|
|
53
|
+
export declare function prepareArtifacts(plan: OtaArtifactPlanEntry[], onProgress?: (progress: OtaArtifactDownloadProgress) => void, nativeDownload?: (entry: OtaArtifactPlanEntry, destination: string, onProgress?: (bytesWritten: number, contentLength: number) => void) => Promise<{
|
|
54
|
+
statusCode: number;
|
|
55
|
+
}>): Promise<PreparedOtaArtifact[]>;
|
|
56
|
+
/**
|
|
57
|
+
* Point the manifest's artifact URLs at the phone server, leaving every other field
|
|
58
|
+
* semantically identical to what the update check saw. Entries we host get
|
|
59
|
+
* `<baseUrl>/artifacts/<sha256>`; entries the update does not need keep their CDN URLs.
|
|
60
|
+
* Only URL fields change: target versions, sizes, and manifest hashes remain untouched.
|
|
61
|
+
*/
|
|
62
|
+
export declare function rewriteManifestForLocalServer(manifestBody: string, artifacts: PreparedOtaArtifact[], baseUrl: string): string;
|
|
63
|
+
/** Delete every stored artifact whose hash is not in `keepSha256s` (plus stray .part files). */
|
|
64
|
+
export declare function cleanupArtifacts(keepSha256s?: string[]): Promise<void>;
|
|
65
|
+
//# sourceMappingURL=OtaArtifactDownloader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OtaArtifactDownloader.d.ts","sourceRoot":"","sources":["../../src/services/OtaArtifactDownloader.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,4BAA4B,EAAc,MAAM,yBAAyB,CAAA;AAEtF;;;;;;;;;;;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AmB,EAAE,CAAC,CA0EhC;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC3C,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,mBAAmB,EAAE,EAChC,OAAO,EAAE,MAAM,GACd,MAAM,CA0BR;AAED,gGAAgG;AAChG,wBAAsB,gBAAgB,CAAC,WAAW,GAAE,MAAM,EAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAYhF"}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import * as RNFS from "@dr.pogodin/react-native-fs";
|
|
2
|
+
export class OtaArtifactError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.name = "OtaArtifactError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const ASG_PACKAGE = "com.mentra.asg_client";
|
|
11
|
+
export function otaArtifactsDirectory() {
|
|
12
|
+
return `${RNFS.DocumentDirectoryPath}/ota_artifacts`;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Derive the artifact list the pending update needs from a completed check.
|
|
16
|
+
* Works off the raw manifest body (not the normalized check fields) so the URLs and
|
|
17
|
+
* hashes match exactly what the glasses will re-parse.
|
|
18
|
+
*/
|
|
19
|
+
export function planArtifacts(result) {
|
|
20
|
+
if (!result.manifestBody) {
|
|
21
|
+
throw new OtaArtifactError("manifest_invalid", "Check result carries no manifest body");
|
|
22
|
+
}
|
|
23
|
+
let manifest;
|
|
24
|
+
try {
|
|
25
|
+
manifest = JSON.parse(result.manifestBody);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new OtaArtifactError("manifest_invalid", "Manifest body is not valid JSON");
|
|
29
|
+
}
|
|
30
|
+
const entries = [];
|
|
31
|
+
if (result.updates.includes("apk")) {
|
|
32
|
+
const app = manifest.apps?.[ASG_PACKAGE];
|
|
33
|
+
const url = typeof app?.apkUrl === "string" ? app.apkUrl : null;
|
|
34
|
+
if (!url) {
|
|
35
|
+
throw new OtaArtifactError("manifest_invalid", "Manifest has no apkUrl for the pending APK update");
|
|
36
|
+
}
|
|
37
|
+
entries.push({
|
|
38
|
+
kind: "apk",
|
|
39
|
+
url,
|
|
40
|
+
sha256: requireSha256(app, "APK"),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (result.updates.includes("mtk") && result.mtkPatch) {
|
|
44
|
+
const raw = (manifest.mtk_patches ?? []).find((patch) => firmwareUrl(patch) === firmwareUrl(result.mtkPatch));
|
|
45
|
+
const url = firmwareUrl(raw) ?? firmwareUrl(result.mtkPatch);
|
|
46
|
+
if (!url) {
|
|
47
|
+
throw new OtaArtifactError("manifest_invalid", "Manifest has no URL for the pending MTK patch");
|
|
48
|
+
}
|
|
49
|
+
entries.push({
|
|
50
|
+
kind: "mtk",
|
|
51
|
+
url,
|
|
52
|
+
sha256: requireSha256(raw, "MTK"),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
if (result.updates.includes("bes") && manifest.bes_firmware) {
|
|
56
|
+
const raw = manifest.bes_firmware;
|
|
57
|
+
const url = firmwareUrl(raw);
|
|
58
|
+
if (!url) {
|
|
59
|
+
throw new OtaArtifactError("manifest_invalid", "Manifest has no URL for the pending BES firmware");
|
|
60
|
+
}
|
|
61
|
+
entries.push({
|
|
62
|
+
kind: "bes",
|
|
63
|
+
url,
|
|
64
|
+
sha256: requireSha256(raw, "BES"),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return entries;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Download every planned artifact into the on-disk hash-keyed store, reusing files that
|
|
71
|
+
* already verify. Sequential on purpose: progress is legible and the hotspot window that
|
|
72
|
+
* follows is the slow part, not phone-side parallelism.
|
|
73
|
+
*/
|
|
74
|
+
export async function prepareArtifacts(plan, onProgress, nativeDownload) {
|
|
75
|
+
const directory = otaArtifactsDirectory();
|
|
76
|
+
await RNFS.mkdir(directory, { NSURLIsExcludedFromBackupKey: true });
|
|
77
|
+
const prepared = [];
|
|
78
|
+
for (let index = 0; index < plan.length; index++) {
|
|
79
|
+
const entry = plan[index];
|
|
80
|
+
const cachedPath = `${directory}/${entry.sha256}`;
|
|
81
|
+
if (await RNFS.exists(cachedPath)) {
|
|
82
|
+
const cachedHash = (await RNFS.hash(cachedPath, "sha256")).toLowerCase();
|
|
83
|
+
if (cachedHash === entry.sha256) {
|
|
84
|
+
prepared.push({ ...entry, filePath: cachedPath });
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
await safeUnlink(cachedPath);
|
|
88
|
+
}
|
|
89
|
+
const partPath = `${directory}/download-${index}.part`;
|
|
90
|
+
await safeUnlink(partPath);
|
|
91
|
+
try {
|
|
92
|
+
const reportProgress = (bytesWritten, contentLength) => {
|
|
93
|
+
onProgress?.({
|
|
94
|
+
kind: entry.kind,
|
|
95
|
+
index,
|
|
96
|
+
totalCount: plan.length,
|
|
97
|
+
artifactPercent: contentLength > 0 ? Math.round((bytesWritten / contentLength) * 100) : 0,
|
|
98
|
+
bytesWritten,
|
|
99
|
+
contentLength,
|
|
100
|
+
});
|
|
101
|
+
};
|
|
102
|
+
const downloadResult = nativeDownload
|
|
103
|
+
? await nativeDownload(entry, partPath, reportProgress)
|
|
104
|
+
: await RNFS.downloadFile({
|
|
105
|
+
fromUrl: entry.url,
|
|
106
|
+
toFile: partPath,
|
|
107
|
+
connectionTimeout: 30_000,
|
|
108
|
+
readTimeout: 30_000,
|
|
109
|
+
progressDivider: 5,
|
|
110
|
+
progress: (res) => {
|
|
111
|
+
reportProgress(res.bytesWritten, res.contentLength);
|
|
112
|
+
},
|
|
113
|
+
}).promise;
|
|
114
|
+
if (downloadResult.statusCode !== 200) {
|
|
115
|
+
throw new OtaArtifactError("artifact_download_failed", `Download of ${entry.kind} artifact failed with HTTP ${downloadResult.statusCode}`);
|
|
116
|
+
}
|
|
117
|
+
const actualSha256 = (await RNFS.hash(partPath, "sha256")).toLowerCase();
|
|
118
|
+
if (actualSha256 !== entry.sha256) {
|
|
119
|
+
throw new OtaArtifactError("artifact_verify_failed", `${entry.kind} artifact hash mismatch: expected ${entry.sha256}, got ${actualSha256}`);
|
|
120
|
+
}
|
|
121
|
+
const finalPath = `${directory}/${entry.sha256}`;
|
|
122
|
+
await safeUnlink(finalPath);
|
|
123
|
+
await RNFS.moveFile(partPath, finalPath);
|
|
124
|
+
prepared.push({ ...entry, filePath: finalPath });
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
await safeUnlink(partPath);
|
|
128
|
+
if (error instanceof OtaArtifactError) {
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
throw new OtaArtifactError("artifact_download_failed", `Download of ${entry.kind} artifact failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return prepared;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Point the manifest's artifact URLs at the phone server, leaving every other field
|
|
138
|
+
* semantically identical to what the update check saw. Entries we host get
|
|
139
|
+
* `<baseUrl>/artifacts/<sha256>`; entries the update does not need keep their CDN URLs.
|
|
140
|
+
* Only URL fields change: target versions, sizes, and manifest hashes remain untouched.
|
|
141
|
+
*/
|
|
142
|
+
export function rewriteManifestForLocalServer(manifestBody, artifacts, baseUrl) {
|
|
143
|
+
let manifest;
|
|
144
|
+
try {
|
|
145
|
+
manifest = JSON.parse(manifestBody);
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
throw new OtaArtifactError("manifest_invalid", "Manifest body is not valid JSON");
|
|
149
|
+
}
|
|
150
|
+
const byUrl = new Map(artifacts.map((artifact) => [artifact.url, artifact]));
|
|
151
|
+
const localUrl = (artifact) => `${baseUrl}/artifacts/${artifact.sha256}`;
|
|
152
|
+
for (const app of Object.values(manifest.apps ?? {})) {
|
|
153
|
+
const record = app;
|
|
154
|
+
const artifact = typeof record.apkUrl === "string" ? byUrl.get(record.apkUrl) : undefined;
|
|
155
|
+
if (artifact) {
|
|
156
|
+
record.apkUrl = localUrl(artifact);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
for (const patch of manifest.mtk_patches ?? []) {
|
|
160
|
+
rewriteFirmwareEntry(patch, byUrl, localUrl);
|
|
161
|
+
}
|
|
162
|
+
if (manifest.bes_firmware) {
|
|
163
|
+
rewriteFirmwareEntry(manifest.bes_firmware, byUrl, localUrl);
|
|
164
|
+
}
|
|
165
|
+
return JSON.stringify(manifest);
|
|
166
|
+
}
|
|
167
|
+
/** Delete every stored artifact whose hash is not in `keepSha256s` (plus stray .part files). */
|
|
168
|
+
export async function cleanupArtifacts(keepSha256s = []) {
|
|
169
|
+
const directory = otaArtifactsDirectory();
|
|
170
|
+
if (!(await RNFS.exists(directory))) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const keep = new Set(keepSha256s.map((sha) => sha.toLowerCase()));
|
|
174
|
+
const items = await RNFS.readDir(directory);
|
|
175
|
+
for (const item of items) {
|
|
176
|
+
if (!item.isFile())
|
|
177
|
+
continue;
|
|
178
|
+
if (keep.has(item.name.toLowerCase()))
|
|
179
|
+
continue;
|
|
180
|
+
await safeUnlink(item.path);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function rewriteFirmwareEntry(entry, byUrl, localUrl) {
|
|
184
|
+
const url = firmwareUrl(entry);
|
|
185
|
+
const artifact = url ? byUrl.get(url) : undefined;
|
|
186
|
+
if (!artifact) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
entry.url = localUrl(artifact);
|
|
190
|
+
// Overwrite the legacy key too when present, so no glasses build can prefer a stale
|
|
191
|
+
// CDN URL over the local one.
|
|
192
|
+
if (typeof entry.firmwareUrl === "string") {
|
|
193
|
+
entry.firmwareUrl = localUrl(artifact);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function firmwareUrl(entry) {
|
|
197
|
+
if (!entry || typeof entry !== "object") {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
const record = entry;
|
|
201
|
+
if (typeof record.url === "string" && record.url.length > 0) {
|
|
202
|
+
return record.url;
|
|
203
|
+
}
|
|
204
|
+
if (typeof record.firmwareUrl === "string" && record.firmwareUrl.length > 0) {
|
|
205
|
+
return record.firmwareUrl;
|
|
206
|
+
}
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
function requireSha256(entry, label) {
|
|
210
|
+
const sha256 = typeof entry?.sha256 === "string" ? entry.sha256.trim().toLowerCase() : "";
|
|
211
|
+
if (!/^[a-f0-9]{64}$/.test(sha256)) {
|
|
212
|
+
throw new OtaArtifactError("manifest_invalid", `${label} artifact has no valid manifest sha256`);
|
|
213
|
+
}
|
|
214
|
+
return sha256;
|
|
215
|
+
}
|
|
216
|
+
async function safeUnlink(path) {
|
|
217
|
+
try {
|
|
218
|
+
if (await RNFS.exists(path)) {
|
|
219
|
+
await RNFS.unlink(path);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
// Best-effort: a leftover file only wastes space and is cleaned up next run.
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
//# sourceMappingURL=OtaArtifactDownloader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OtaArtifactDownloader.js","sourceRoot":"","sources":["../../src/services/OtaArtifactDownloader.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,6BAA6B,CAAA;AA2CnD,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAEvB;IADlB,YACkB,IAAgF,EAChG,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAA;QAHE,SAAI,GAAJ,IAAI,CAA4E;QAIhG,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAA;IAChC,CAAC;CACF;AAED,MAAM,WAAW,GAAG,uBAAuB,CAAA;AAE3C,MAAM,UAAU,qBAAqB;IACnC,OAAO,GAAG,IAAI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,kBAAkB,EAAE,GAAG,KAAK,wCAAwC,CAAC,CAAA;IAClG,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,IAAY;IACpC,IAAI,CAAC;QACH,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QACzB,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,6EAA6E;IAC/E,CAAC;AACH,CAAC","sourcesContent":["import * as RNFS from \"@dr.pogodin/react-native-fs\"\nimport type {OtaCheckCurrentGlassesResult, VersionJson} from \"./OtaUpdateCheckService\"\n\n/**\n * Phone-side artifact staging for hotspot-served OTA (OS-1676).\n *\n * When the glasses have no WiFi, the phone downloads the OTA artifacts itself (over\n * whatever network it is on — the user's tap on \"update\" is the consent) and serves them\n * to the glasses via the LocalOtaServer over the glasses' hotspot. This module owns:\n *\n * - planning which artifacts the pending update actually needs (from the raw manifest the\n * update check fetched, so the glasses re-parse byte-identical version data),\n * - downloading them with .part staging and sha256 verification, keyed on disk by hash so\n * retries and the post-APK continuation reuse verified files,\n * - rewriting the manifest's URL fields to point at the phone server, and\n * - cleanup once the update completes or the manifest moves on.\n */\n\nexport type OtaArtifactKind = \"apk\" | \"mtk\" | \"bes\"\n\nexport interface OtaArtifactPlanEntry {\n kind: OtaArtifactKind\n /** URL this artifact is fetched from, exactly as it appears in the raw manifest. */\n url: string\n /** Required content hash from the manifest. */\n sha256: string\n}\n\nexport interface PreparedOtaArtifact extends OtaArtifactPlanEntry {\n filePath: string\n}\n\nexport interface OtaArtifactDownloadProgress {\n kind: OtaArtifactKind\n /** 0-based index of the artifact being downloaded. */\n index: number\n totalCount: number\n /** Percent of the current artifact, 0-100 (0 when the server sent no length). */\n artifactPercent: number\n bytesWritten: number\n contentLength: number\n}\n\nexport class OtaArtifactError extends Error {\n constructor(\n public readonly code: \"artifact_download_failed\" | \"artifact_verify_failed\" | \"manifest_invalid\",\n message: string,\n ) {\n super(message)\n this.name = \"OtaArtifactError\"\n }\n}\n\nconst ASG_PACKAGE = \"com.mentra.asg_client\"\n\nexport function otaArtifactsDirectory(): string {\n return `${RNFS.DocumentDirectoryPath}/ota_artifacts`\n}\n\n/**\n * Derive the artifact list the pending update needs from a completed check.\n * Works off the raw manifest body (not the normalized check fields) so the URLs and\n * hashes match exactly what the glasses will re-parse.\n */\nexport function planArtifacts(result: OtaCheckCurrentGlassesResult): OtaArtifactPlanEntry[] {\n if (!result.manifestBody) {\n throw new OtaArtifactError(\"manifest_invalid\", \"Check result carries no manifest body\")\n }\n let manifest: VersionJson\n try {\n manifest = JSON.parse(result.manifestBody)\n } catch {\n throw new OtaArtifactError(\"manifest_invalid\", \"Manifest body is not valid JSON\")\n }\n\n const entries: OtaArtifactPlanEntry[] = []\n\n if (result.updates.includes(\"apk\")) {\n const app = manifest.apps?.[ASG_PACKAGE] as unknown as Record<string, unknown> | undefined\n const url = typeof app?.apkUrl === \"string\" ? app.apkUrl : null\n if (!url) {\n throw new OtaArtifactError(\"manifest_invalid\", \"Manifest has no apkUrl for the pending APK update\")\n }\n entries.push({\n kind: \"apk\",\n url,\n sha256: requireSha256(app, \"APK\"),\n })\n }\n\n if (result.updates.includes(\"mtk\") && result.mtkPatch) {\n const raw = (manifest.mtk_patches ?? []).find(\n (patch) => firmwareUrl(patch) === firmwareUrl(result.mtkPatch!),\n ) as unknown as Record<string, unknown> | undefined\n const url = firmwareUrl(raw) ?? firmwareUrl(result.mtkPatch)\n if (!url) {\n throw new OtaArtifactError(\"manifest_invalid\", \"Manifest has no URL for the pending MTK patch\")\n }\n entries.push({\n kind: \"mtk\",\n url,\n sha256: requireSha256(raw, \"MTK\"),\n })\n }\n\n if (result.updates.includes(\"bes\") && manifest.bes_firmware) {\n const raw = manifest.bes_firmware as unknown as Record<string, unknown>\n const url = firmwareUrl(raw)\n if (!url) {\n throw new OtaArtifactError(\"manifest_invalid\", \"Manifest has no URL for the pending BES firmware\")\n }\n entries.push({\n kind: \"bes\",\n url,\n sha256: requireSha256(raw, \"BES\"),\n })\n }\n\n return entries\n}\n\n/**\n * Download every planned artifact into the on-disk hash-keyed store, reusing files that\n * already verify. Sequential on purpose: progress is legible and the hotspot window that\n * follows is the slow part, not phone-side parallelism.\n */\nexport async function prepareArtifacts(\n plan: OtaArtifactPlanEntry[],\n onProgress?: (progress: OtaArtifactDownloadProgress) => void,\n nativeDownload?: (\n entry: OtaArtifactPlanEntry,\n destination: string,\n onProgress?: (bytesWritten: number, contentLength: number) => void,\n ) => Promise<{statusCode: number}>,\n): Promise<PreparedOtaArtifact[]> {\n const directory = otaArtifactsDirectory()\n await RNFS.mkdir(directory, {NSURLIsExcludedFromBackupKey: true})\n\n const prepared: PreparedOtaArtifact[] = []\n for (let index = 0; index < plan.length; index++) {\n const entry = plan[index]\n\n const cachedPath = `${directory}/${entry.sha256}`\n if (await RNFS.exists(cachedPath)) {\n const cachedHash = (await RNFS.hash(cachedPath, \"sha256\")).toLowerCase()\n if (cachedHash === entry.sha256) {\n prepared.push({...entry, filePath: cachedPath})\n continue\n }\n await safeUnlink(cachedPath)\n }\n\n const partPath = `${directory}/download-${index}.part`\n await safeUnlink(partPath)\n try {\n const reportProgress = (bytesWritten: number, contentLength: number) => {\n onProgress?.({\n kind: entry.kind,\n index,\n totalCount: plan.length,\n artifactPercent: contentLength > 0 ? Math.round((bytesWritten / contentLength) * 100) : 0,\n bytesWritten,\n contentLength,\n })\n }\n const downloadResult = nativeDownload\n ? await nativeDownload(entry, partPath, reportProgress)\n : await RNFS.downloadFile({\n fromUrl: entry.url,\n toFile: partPath,\n connectionTimeout: 30_000,\n readTimeout: 30_000,\n progressDivider: 5,\n progress: (res: RNFS.DownloadProgressCallbackResultT) => {\n reportProgress(res.bytesWritten, res.contentLength)\n },\n }).promise\n if (downloadResult.statusCode !== 200) {\n throw new OtaArtifactError(\n \"artifact_download_failed\",\n `Download of ${entry.kind} artifact failed with HTTP ${downloadResult.statusCode}`,\n )\n }\n\n const actualSha256 = (await RNFS.hash(partPath, \"sha256\")).toLowerCase()\n if (actualSha256 !== entry.sha256) {\n throw new OtaArtifactError(\n \"artifact_verify_failed\",\n `${entry.kind} artifact hash mismatch: expected ${entry.sha256}, got ${actualSha256}`,\n )\n }\n\n const finalPath = `${directory}/${entry.sha256}`\n await safeUnlink(finalPath)\n await RNFS.moveFile(partPath, finalPath)\n prepared.push({...entry, filePath: finalPath})\n } catch (error) {\n await safeUnlink(partPath)\n if (error instanceof OtaArtifactError) {\n throw error\n }\n throw new OtaArtifactError(\n \"artifact_download_failed\",\n `Download of ${entry.kind} artifact failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n return prepared\n}\n\n/**\n * Point the manifest's artifact URLs at the phone server, leaving every other field\n * semantically identical to what the update check saw. Entries we host get\n * `<baseUrl>/artifacts/<sha256>`; entries the update does not need keep their CDN URLs.\n * Only URL fields change: target versions, sizes, and manifest hashes remain untouched.\n */\nexport function rewriteManifestForLocalServer(\n manifestBody: string,\n artifacts: PreparedOtaArtifact[],\n baseUrl: string,\n): string {\n let manifest: VersionJson\n try {\n manifest = JSON.parse(manifestBody)\n } catch {\n throw new OtaArtifactError(\"manifest_invalid\", \"Manifest body is not valid JSON\")\n }\n const byUrl = new Map(artifacts.map((artifact) => [artifact.url, artifact]))\n const localUrl = (artifact: PreparedOtaArtifact) => `${baseUrl}/artifacts/${artifact.sha256}`\n\n for (const app of Object.values(manifest.apps ?? {})) {\n const record = app as unknown as Record<string, unknown>\n const artifact = typeof record.apkUrl === \"string\" ? byUrl.get(record.apkUrl) : undefined\n if (artifact) {\n record.apkUrl = localUrl(artifact)\n }\n }\n\n for (const patch of manifest.mtk_patches ?? []) {\n rewriteFirmwareEntry(patch as unknown as Record<string, unknown>, byUrl, localUrl)\n }\n if (manifest.bes_firmware) {\n rewriteFirmwareEntry(manifest.bes_firmware as unknown as Record<string, unknown>, byUrl, localUrl)\n }\n\n return JSON.stringify(manifest)\n}\n\n/** Delete every stored artifact whose hash is not in `keepSha256s` (plus stray .part files). */\nexport async function cleanupArtifacts(keepSha256s: string[] = []): Promise<void> {\n const directory = otaArtifactsDirectory()\n if (!(await RNFS.exists(directory))) {\n return\n }\n const keep = new Set(keepSha256s.map((sha) => sha.toLowerCase()))\n const items = await RNFS.readDir(directory)\n for (const item of items) {\n if (!item.isFile()) continue\n if (keep.has(item.name.toLowerCase())) continue\n await safeUnlink(item.path)\n }\n}\n\nfunction rewriteFirmwareEntry(\n entry: Record<string, unknown>,\n byUrl: Map<string, PreparedOtaArtifact>,\n localUrl: (artifact: PreparedOtaArtifact) => string,\n): void {\n const url = firmwareUrl(entry)\n const artifact = url ? byUrl.get(url) : undefined\n if (!artifact) {\n return\n }\n entry.url = localUrl(artifact)\n // Overwrite the legacy key too when present, so no glasses build can prefer a stale\n // CDN URL over the local one.\n if (typeof entry.firmwareUrl === \"string\") {\n entry.firmwareUrl = localUrl(artifact)\n }\n}\n\nfunction firmwareUrl(entry: unknown): string | null {\n if (!entry || typeof entry !== \"object\") {\n return null\n }\n const record = entry as Record<string, unknown>\n if (typeof record.url === \"string\" && record.url.length > 0) {\n return record.url\n }\n if (typeof record.firmwareUrl === \"string\" && record.firmwareUrl.length > 0) {\n return record.firmwareUrl\n }\n return null\n}\n\nfunction requireSha256(entry: Record<string, unknown> | undefined, label: string): string {\n const sha256 = typeof entry?.sha256 === \"string\" ? entry.sha256.trim().toLowerCase() : \"\"\n if (!/^[a-f0-9]{64}$/.test(sha256)) {\n throw new OtaArtifactError(\"manifest_invalid\", `${label} artifact has no valid manifest sha256`)\n }\n return sha256\n}\n\nasync function safeUnlink(path: string): Promise<void> {\n try {\n if (await RNFS.exists(path)) {\n await RNFS.unlink(path)\n }\n } catch {\n // Best-effort: a leftover file only wastes space and is cleaned up next run.\n }\n}\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { OtaCheckCurrentGlassesResult } from "./OtaUpdateCheckService";
|
|
2
|
+
export declare const MAX_OTA_AUTO_CHAIN_PASSES = 8;
|
|
3
|
+
export declare const OTA_AUTO_CHAIN_RECONNECT_TIMEOUT_MS = 120000;
|
|
4
|
+
export type OtaAutoChainAdvanceResult = {
|
|
5
|
+
advance: true;
|
|
6
|
+
passCount: number;
|
|
7
|
+
} | {
|
|
8
|
+
advance: false;
|
|
9
|
+
reason: "inactive" | "duplicate" | "max_passes" | "downgrade_not_approved";
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Identify the exact update offer that produced one OTA pass. Including the
|
|
13
|
+
* observed versions and manifest body lets a changed manifest advance while a
|
|
14
|
+
* stale post-install version_info response is rejected as a duplicate.
|
|
15
|
+
*/
|
|
16
|
+
export declare function otaAutoChainFingerprint(result: OtaCheckCurrentGlassesResult): string;
|
|
17
|
+
/** Start a chain after the user explicitly approves its first update pass. */
|
|
18
|
+
export declare function beginOtaAutoChain(initialFingerprint: string, approvedDowngrade: boolean): void;
|
|
19
|
+
export declare function isOtaAutoChainActive(): boolean;
|
|
20
|
+
/** End the current chain. Safe to call when no chain is active. */
|
|
21
|
+
export declare function stopOtaAutoChain(): void;
|
|
22
|
+
/**
|
|
23
|
+
* Start (or continue) the bounded wait for glasses that are rebooting between
|
|
24
|
+
* passes. Re-renders must not extend the original deadline indefinitely.
|
|
25
|
+
*/
|
|
26
|
+
export declare function otaAutoChainReconnectWaitRemaining(now?: number): number | null;
|
|
27
|
+
/** A successful reconnect allows a future pass to establish a fresh wait. */
|
|
28
|
+
export declare function clearOtaAutoChainReconnectWait(): void;
|
|
29
|
+
/**
|
|
30
|
+
* Admit the next pass of an active chain. Repeated offers, unexpectedly
|
|
31
|
+
* destructive downgrades, and runaway chains fail closed and end automation.
|
|
32
|
+
*/
|
|
33
|
+
export declare function tryAdvanceOtaAutoChain(fingerprint: string, isDowngrade: boolean): OtaAutoChainAdvanceResult;
|
|
34
|
+
//# sourceMappingURL=OtaAutoChain.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OtaAutoChain.d.ts","sourceRoot":"","sources":["../../src/services/OtaAutoChain.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,yBAAyB,CAAA;AAEzE,eAAO,MAAM,yBAAyB,IAAI,CAAA;AAC1C,eAAO,MAAM,mCAAmC,SAAU,CAAA;AAS1D,MAAM,MAAM,yBAAyB,GACjC;IAAC,OAAO,EAAE,IAAI,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAC,GAClC;IAAC,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,UAAU,GAAG,WAAW,GAAG,YAAY,GAAG,wBAAwB,CAAA;CAAC,CAAA;AAIhG;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,4BAA4B,GAAG,MAAM,CAkBpF;AAED,8EAA8E;AAC9E,wBAAgB,iBAAiB,CAAC,kBAAkB,EAAE,MAAM,EAAE,iBAAiB,EAAE,OAAO,GAAG,IAAI,CAO9F;AAED,wBAAgB,oBAAoB,IAAI,OAAO,CAE9C;AAED,mEAAmE;AACnE,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC;AAED;;;GAGG;AACH,wBAAgB,kCAAkC,CAAC,GAAG,SAAoB,GAAG,MAAM,GAAG,IAAI,CAKzF;AAED,6EAA6E;AAC7E,wBAAgB,8BAA8B,IAAI,IAAI,CAErD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,GAAG,yBAAyB,CAuB3G"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export const MAX_OTA_AUTO_CHAIN_PASSES = 8;
|
|
2
|
+
export const OTA_AUTO_CHAIN_RECONNECT_TIMEOUT_MS = 120_000;
|
|
3
|
+
let session = null;
|
|
4
|
+
/**
|
|
5
|
+
* Identify the exact update offer that produced one OTA pass. Including the
|
|
6
|
+
* observed versions and manifest body lets a changed manifest advance while a
|
|
7
|
+
* stale post-install version_info response is rejected as a duplicate.
|
|
8
|
+
*/
|
|
9
|
+
export function otaAutoChainFingerprint(result) {
|
|
10
|
+
return JSON.stringify({
|
|
11
|
+
manifestUrl: result.manifestUrl ?? "",
|
|
12
|
+
manifestBody: result.manifestBody ?? "",
|
|
13
|
+
buildNumber: result.buildNumber ?? "",
|
|
14
|
+
mtkFirmwareVersion: result.mtkFirmwareVersion ?? "",
|
|
15
|
+
besFirmwareVersion: result.besFirmwareVersion ?? "",
|
|
16
|
+
updates: result.updates,
|
|
17
|
+
targetBuildNumber: result.updateInfo?.versionCode ?? result.latestVersionInfo?.versionCode ?? 0,
|
|
18
|
+
targetBesVersion: result.besVersion ?? "",
|
|
19
|
+
mtkPatch: result.mtkPatch
|
|
20
|
+
? {
|
|
21
|
+
startFirmware: result.mtkPatch.start_firmware,
|
|
22
|
+
endFirmware: result.mtkPatch.end_firmware,
|
|
23
|
+
url: result.mtkPatch.url,
|
|
24
|
+
}
|
|
25
|
+
: null,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Start a chain after the user explicitly approves its first update pass. */
|
|
29
|
+
export function beginOtaAutoChain(initialFingerprint, approvedDowngrade) {
|
|
30
|
+
session = {
|
|
31
|
+
approvedDowngrade,
|
|
32
|
+
passCount: 1,
|
|
33
|
+
reconnectDeadline: null,
|
|
34
|
+
seenFingerprints: new Set([initialFingerprint]),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export function isOtaAutoChainActive() {
|
|
38
|
+
return session !== null;
|
|
39
|
+
}
|
|
40
|
+
/** End the current chain. Safe to call when no chain is active. */
|
|
41
|
+
export function stopOtaAutoChain() {
|
|
42
|
+
session = null;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Start (or continue) the bounded wait for glasses that are rebooting between
|
|
46
|
+
* passes. Re-renders must not extend the original deadline indefinitely.
|
|
47
|
+
*/
|
|
48
|
+
export function otaAutoChainReconnectWaitRemaining(now = performance.now()) {
|
|
49
|
+
if (!session)
|
|
50
|
+
return null;
|
|
51
|
+
session.reconnectDeadline ??= now + OTA_AUTO_CHAIN_RECONNECT_TIMEOUT_MS;
|
|
52
|
+
return Math.max(0, session.reconnectDeadline - now);
|
|
53
|
+
}
|
|
54
|
+
/** A successful reconnect allows a future pass to establish a fresh wait. */
|
|
55
|
+
export function clearOtaAutoChainReconnectWait() {
|
|
56
|
+
if (session)
|
|
57
|
+
session.reconnectDeadline = null;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Admit the next pass of an active chain. Repeated offers, unexpectedly
|
|
61
|
+
* destructive downgrades, and runaway chains fail closed and end automation.
|
|
62
|
+
*/
|
|
63
|
+
export function tryAdvanceOtaAutoChain(fingerprint, isDowngrade) {
|
|
64
|
+
if (!session) {
|
|
65
|
+
return { advance: false, reason: "inactive" };
|
|
66
|
+
}
|
|
67
|
+
if (isDowngrade && !session.approvedDowngrade) {
|
|
68
|
+
stopOtaAutoChain();
|
|
69
|
+
return { advance: false, reason: "downgrade_not_approved" };
|
|
70
|
+
}
|
|
71
|
+
if (session.seenFingerprints.has(fingerprint)) {
|
|
72
|
+
stopOtaAutoChain();
|
|
73
|
+
return { advance: false, reason: "duplicate" };
|
|
74
|
+
}
|
|
75
|
+
if (session.passCount >= MAX_OTA_AUTO_CHAIN_PASSES) {
|
|
76
|
+
stopOtaAutoChain();
|
|
77
|
+
return { advance: false, reason: "max_passes" };
|
|
78
|
+
}
|
|
79
|
+
session.seenFingerprints.add(fingerprint);
|
|
80
|
+
session.passCount += 1;
|
|
81
|
+
return { advance: true, passCount: session.passCount };
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=OtaAutoChain.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OtaAutoChain.js","sourceRoot":"","sources":["../../src/services/OtaAutoChain.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,yBAAyB,G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G,CAAC,WAAW,CAAC,CAAA;IACzC,OAAO,CAAC,SAAS,IAAI,CAAC,CAAA;IACtB,OAAO,EAAC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAC,CAAA;AACtD,CAAC","sourcesContent":["import type {OtaCheckCurrentGlassesResult} from \"./OtaUpdateCheckService\"\n\nexport const MAX_OTA_AUTO_CHAIN_PASSES = 8\nexport const OTA_AUTO_CHAIN_RECONNECT_TIMEOUT_MS = 120_000\n\ntype OtaAutoChainSession = {\n approvedDowngrade: boolean\n passCount: number\n reconnectDeadline: number | null\n seenFingerprints: Set<string>\n}\n\nexport type OtaAutoChainAdvanceResult =\n | {advance: true; passCount: number}\n | {advance: false; reason: \"inactive\" | \"duplicate\" | \"max_passes\" | \"downgrade_not_approved\"}\n\nlet session: OtaAutoChainSession | null = null\n\n/**\n * Identify the exact update offer that produced one OTA pass. Including the\n * observed versions and manifest body lets a changed manifest advance while a\n * stale post-install version_info response is rejected as a duplicate.\n */\nexport function otaAutoChainFingerprint(result: OtaCheckCurrentGlassesResult): string {\n return JSON.stringify({\n manifestUrl: result.manifestUrl ?? \"\",\n manifestBody: result.manifestBody ?? \"\",\n buildNumber: result.buildNumber ?? \"\",\n mtkFirmwareVersion: result.mtkFirmwareVersion ?? \"\",\n besFirmwareVersion: result.besFirmwareVersion ?? \"\",\n updates: result.updates,\n targetBuildNumber: result.updateInfo?.versionCode ?? result.latestVersionInfo?.versionCode ?? 0,\n targetBesVersion: result.besVersion ?? \"\",\n mtkPatch: result.mtkPatch\n ? {\n startFirmware: result.mtkPatch.start_firmware,\n endFirmware: result.mtkPatch.end_firmware,\n url: result.mtkPatch.url,\n }\n : null,\n })\n}\n\n/** Start a chain after the user explicitly approves its first update pass. */\nexport function beginOtaAutoChain(initialFingerprint: string, approvedDowngrade: boolean): void {\n session = {\n approvedDowngrade,\n passCount: 1,\n reconnectDeadline: null,\n seenFingerprints: new Set([initialFingerprint]),\n }\n}\n\nexport function isOtaAutoChainActive(): boolean {\n return session !== null\n}\n\n/** End the current chain. Safe to call when no chain is active. */\nexport function stopOtaAutoChain(): void {\n session = null\n}\n\n/**\n * Start (or continue) the bounded wait for glasses that are rebooting between\n * passes. Re-renders must not extend the original deadline indefinitely.\n */\nexport function otaAutoChainReconnectWaitRemaining(now = performance.now()): number | null {\n if (!session) return null\n\n session.reconnectDeadline ??= now + OTA_AUTO_CHAIN_RECONNECT_TIMEOUT_MS\n return Math.max(0, session.reconnectDeadline - now)\n}\n\n/** A successful reconnect allows a future pass to establish a fresh wait. */\nexport function clearOtaAutoChainReconnectWait(): void {\n if (session) session.reconnectDeadline = null\n}\n\n/**\n * Admit the next pass of an active chain. Repeated offers, unexpectedly\n * destructive downgrades, and runaway chains fail closed and end automation.\n */\nexport function tryAdvanceOtaAutoChain(fingerprint: string, isDowngrade: boolean): OtaAutoChainAdvanceResult {\n if (!session) {\n return {advance: false, reason: \"inactive\"}\n }\n\n if (isDowngrade && !session.approvedDowngrade) {\n stopOtaAutoChain()\n return {advance: false, reason: \"downgrade_not_approved\"}\n }\n\n if (session.seenFingerprints.has(fingerprint)) {\n stopOtaAutoChain()\n return {advance: false, reason: \"duplicate\"}\n }\n\n if (session.passCount >= MAX_OTA_AUTO_CHAIN_PASSES) {\n stopOtaAutoChain()\n return {advance: false, reason: \"max_passes\"}\n }\n\n session.seenFingerprints.add(fingerprint)\n session.passCount += 1\n return {advance: true, passCount: session.passCount}\n}\n"]}
|