@technotoil/universal-react-native-ota 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +95 -2
- package/cli/index.js +67 -0
- package/package.json +54 -4
- package/plugin/index.js +25 -0
- package/src/adapters/ExpoUpdatesAdapter.ts +60 -0
- package/src/components/OTAErrorView.tsx +19 -0
- package/src/components/OTAProgress.tsx +26 -0
- package/src/components/OTAUpdateAvailableView.tsx +23 -0
- package/src/components/OTAUpdateBanner.tsx +50 -0
- package/src/components/OTAUpdateModal.tsx +101 -0
- package/src/core/OTA.ts +22 -0
- package/src/errors/OTAError.ts +28 -0
- package/src/hooks/useOTA.tsx +55 -0
- package/src/index.ts +30 -0
- package/src/managers/OTAManager.ts +331 -0
- package/src/services/OTAAnalyticsService.ts +40 -0
- package/src/services/RuntimeCompatibilityService.ts +36 -0
- package/src/types/index.ts +84 -0
- package/src/utils/logger.ts +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,96 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @technotoil/universal-react-native-ota
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Production-ready Universal **Expo OTA Update (`expo-updates`)** library for **Expo Managed / CNG**, **React Native CLI**, and **EAS Update** (Android & iOS).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @technotoil/universal-react-native-ota
|
|
9
|
+
npx expo install expo-updates react-native-safe-area-context
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## One-Command Interactive Setup
|
|
13
|
+
|
|
14
|
+
Run `init` to automatically detect your project, log into EAS (if needed), and configure `expo-updates` (`projectId` & `EXUpdatesURL`):
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npx universal-ota init
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Other CLI commands:
|
|
21
|
+
- `npx universal-ota doctor` — Inspect project setup (`android/`, `ios/`, `eas.json`)
|
|
22
|
+
- `npx universal-ota publish <channel> "<message>"` — Publish an OTA update via `eas-cli`
|
|
23
|
+
- `npx universal-ota rollback` — Rollback guidance
|
|
24
|
+
|
|
25
|
+
## Quick Start (`App.tsx`)
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
import { SafeAreaProvider } from 'react-native-safe-area-context';
|
|
29
|
+
import { OTAProvider, OTAUpdateModal } from '@technotoil/universal-react-native-ota';
|
|
30
|
+
|
|
31
|
+
export default function App() {
|
|
32
|
+
return (
|
|
33
|
+
<SafeAreaProvider>
|
|
34
|
+
<OTAProvider config={{ strategy: 'automatic', logLevel: 'info' }}>
|
|
35
|
+
{/* Your Navigation / App */}
|
|
36
|
+
<OTAUpdateModal />
|
|
37
|
+
</OTAProvider>
|
|
38
|
+
</SafeAreaProvider>
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Expo Config Plugin (`app.json`)
|
|
44
|
+
|
|
45
|
+
```json
|
|
46
|
+
{
|
|
47
|
+
"expo": {
|
|
48
|
+
"plugins": ["@technotoil/universal-react-native-ota/plugin"]
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Bare React Native CLI (iOS `AppDelegate.swift`)
|
|
54
|
+
|
|
55
|
+
For bare React Native CLI iOS apps, ensure `bundleURL()` uses `super.bundleURL()` in Release builds so downloaded OTA bundles load instead of the embedded `main.jsbundle`:
|
|
56
|
+
|
|
57
|
+
```swift
|
|
58
|
+
#if DEBUG
|
|
59
|
+
return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: ".expo/.virtual-metro-entry")
|
|
60
|
+
#else
|
|
61
|
+
return super.bundleURL() ?? Bundle.main.url(forResource: "main", withExtension: "jsbundle")
|
|
62
|
+
#endif
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Public API
|
|
66
|
+
|
|
67
|
+
- `OTAProvider` & `useOTA()`
|
|
68
|
+
- `OTA` (`checkForUpdate`, `fetchUpdate`, `reloadApp`, `syncUpdate`, `getUpdateInfo`, `getCurrentVersion`, `getRuntimeVersion`, `getUpdateChannel`, `getUpdateStatus`, `isUpdateAvailable`, `isUpdatePending`, `getLastUpdateError`, `rollbackUpdate`, `setUpdateStrategy`)
|
|
69
|
+
- UI Components: `OTAUpdateBanner`, `OTAProgress`, `OTAUpdateModal`, `OTAErrorView`, `OTAUpdateAvailableView`
|
|
70
|
+
- `OTAUpdateModal` props: `position` (`'bottom' | 'center' | 'top'`), `accentColor`, `title`, `description`, `laterButtonText`, `updateButtonText`, `overlayStyle`, `sheetStyle`, `titleStyle`, `descriptionStyle`, `laterButtonStyle`, `laterButtonTextStyle`, `updateButtonStyle`, `updateButtonTextStyle`
|
|
71
|
+
- Analytics: `otaAnalytics` (`OTAAnalyticsService`)
|
|
72
|
+
```ts
|
|
73
|
+
import { otaAnalytics } from '@technotoil/universal-react-native-ota';
|
|
74
|
+
|
|
75
|
+
otaAnalytics.setHandler((event) => {
|
|
76
|
+
console.log('[OTA Analytics]', event.name, event.updateId);
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Examples
|
|
81
|
+
|
|
82
|
+
- `examples/expo-managed/` — Expo Managed / CNG (`com.technotoil.universalotaexpomanaged`)
|
|
83
|
+
- `examples/react-native-cli/` — React Native CLI (`com.technotoil.universalotarncli`)
|
|
84
|
+
- `examples/eas-update/` — EAS Update (`com.technotoil.universalotaeasupdate`)
|
|
85
|
+
|
|
86
|
+
## Step-by-Step OTA Workflow
|
|
87
|
+
|
|
88
|
+
1. **Install:** `npm install @technotoil/universal-react-native-ota`
|
|
89
|
+
2. **Initialize EAS Update:** `npx universal-ota init`
|
|
90
|
+
3. **Create Initial Native Build (once):** `npx eas-cli build --platform android --profile preview` (or `production`)
|
|
91
|
+
4. **Push Future OTA Updates (no new APK/IPA needed):**
|
|
92
|
+
```bash
|
|
93
|
+
npx universal-ota publish preview "UI and bug fixes"
|
|
94
|
+
# or for production:
|
|
95
|
+
npx universal-ota publish production "Release update"
|
|
96
|
+
```
|
package/cli/index.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { execSync } = require('child_process');
|
|
5
|
+
|
|
6
|
+
const cwd = process.cwd();
|
|
7
|
+
const command = process.argv[2] || 'help';
|
|
8
|
+
|
|
9
|
+
function detectProjectType() {
|
|
10
|
+
const pkgPath = path.join(cwd, 'package.json');
|
|
11
|
+
if (!fs.existsSync(pkgPath)) return 'unknown';
|
|
12
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
|
|
13
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
14
|
+
if (deps.expo) return 'expo';
|
|
15
|
+
if (deps['react-native']) return 'react-native-cli';
|
|
16
|
+
return 'unknown';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function runDoctor() {
|
|
20
|
+
const type = detectProjectType();
|
|
21
|
+
const hasAndroid = fs.existsSync(path.join(cwd, 'android'));
|
|
22
|
+
const hasIos = fs.existsSync(path.join(cwd, 'ios'));
|
|
23
|
+
const hasEas = fs.existsSync(path.join(cwd, 'eas.json'));
|
|
24
|
+
console.log(`[universal-ota doctor] Project type: ${type}`);
|
|
25
|
+
console.log(`[universal-ota doctor] Android dir: ${hasAndroid ? 'found' : 'missing'}`);
|
|
26
|
+
console.log(`[universal-ota doctor] iOS dir: ${hasIos ? 'found' : 'missing'}`);
|
|
27
|
+
console.log(`[universal-ota doctor] eas.json: ${hasEas ? 'found' : 'missing'}`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
switch (command) {
|
|
31
|
+
case 'init':
|
|
32
|
+
case 'configure': {
|
|
33
|
+
const type = detectProjectType();
|
|
34
|
+
console.log(`[universal-ota ${command}] Detected project: ${type}`);
|
|
35
|
+
console.log('[universal-ota] Step 1/2: Checking Expo EAS login...');
|
|
36
|
+
try {
|
|
37
|
+
execSync('npx eas-cli whoami', { stdio: 'inherit' });
|
|
38
|
+
} catch (_e) {
|
|
39
|
+
execSync('npx eas-cli login', { stdio: 'inherit' });
|
|
40
|
+
}
|
|
41
|
+
console.log('[universal-ota] Step 2/2: Configuring EAS Update (projectId & EXUpdatesURL)...');
|
|
42
|
+
execSync('npx eas-cli update:configure', { stdio: 'inherit' });
|
|
43
|
+
console.log('[universal-ota] Setup complete! Wrap your root app in <OTAProvider>.');
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
case 'doctor':
|
|
47
|
+
case 'status':
|
|
48
|
+
runDoctor();
|
|
49
|
+
break;
|
|
50
|
+
case 'check':
|
|
51
|
+
console.log('[universal-ota check] Checking EAS / Expo Updates configuration...');
|
|
52
|
+
runDoctor();
|
|
53
|
+
break;
|
|
54
|
+
case 'publish': {
|
|
55
|
+
const channel = process.argv[3] || 'production';
|
|
56
|
+
const message = process.argv[4] || 'OTA update';
|
|
57
|
+
console.log(`[universal-ota publish] Publishing to channel "${channel}"...`);
|
|
58
|
+
execSync(`npx eas-cli update --channel ${channel} --message "${message}"`, { stdio: 'inherit' });
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
case 'rollback':
|
|
62
|
+
console.log('[universal-ota rollback] Use `npx eas-cli update:republish` or `npx eas-cli update` to roll back on EAS.');
|
|
63
|
+
break;
|
|
64
|
+
default:
|
|
65
|
+
console.log('Usage: npx universal-ota <init|doctor|configure|status|check|publish|rollback>');
|
|
66
|
+
}
|
|
67
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@technotoil/universal-react-native-ota",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Production-ready Universal React Native OTA Update Library for Expo Managed, React Native CLI, and EAS Update",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"react-native": "src/index.ts",
|
|
9
|
+
"bin": {
|
|
10
|
+
"universal-ota": "./cli/index.js"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.mjs",
|
|
16
|
+
"require": "./dist/index.js",
|
|
17
|
+
"default": "./src/index.ts"
|
|
18
|
+
},
|
|
19
|
+
"./plugin": {
|
|
20
|
+
"types": "./plugin/index.d.ts",
|
|
21
|
+
"default": "./plugin/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"src",
|
|
27
|
+
"plugin",
|
|
28
|
+
"cli",
|
|
29
|
+
"scripts",
|
|
30
|
+
"android",
|
|
31
|
+
"ios",
|
|
32
|
+
"README.md",
|
|
33
|
+
"CHANGELOG.md"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsc -p tsconfig.build.json",
|
|
37
|
+
"typecheck": "tsc --noEmit",
|
|
38
|
+
"test": "node --test tests/*.test.js"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"expo-updates": "*",
|
|
42
|
+
"react": "*",
|
|
43
|
+
"react-native": "*",
|
|
44
|
+
"react-native-safe-area-context": "*"
|
|
45
|
+
},
|
|
46
|
+
"keywords": [
|
|
47
|
+
"react-native",
|
|
48
|
+
"expo",
|
|
49
|
+
"expo-updates",
|
|
50
|
+
"ota",
|
|
51
|
+
"eas-update",
|
|
52
|
+
"over-the-air"
|
|
53
|
+
],
|
|
54
|
+
"license": "MIT"
|
|
55
|
+
}
|
|
56
|
+
|
package/plugin/index.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Expo Config Plugin for universal-react-native-ota
|
|
3
|
+
* Automatically configures expo-updates runtimeVersion, update URL, and channel.
|
|
4
|
+
*/
|
|
5
|
+
module.exports = function withUniversalOTA(config, options = {}) {
|
|
6
|
+
const {
|
|
7
|
+
runtimeVersion = '1.0.0',
|
|
8
|
+
updateUrl,
|
|
9
|
+
fallbackToCacheTimeout = 5000,
|
|
10
|
+
checkAutomatically = 'ON_LOAD',
|
|
11
|
+
} = options;
|
|
12
|
+
|
|
13
|
+
return {
|
|
14
|
+
...config,
|
|
15
|
+
runtimeVersion: config.runtimeVersion ?? runtimeVersion,
|
|
16
|
+
updates: {
|
|
17
|
+
enabled: true,
|
|
18
|
+
checkAutomatically,
|
|
19
|
+
fallbackToCacheTimeout,
|
|
20
|
+
...(updateUrl ? { url: updateUrl } : {}),
|
|
21
|
+
...(config.updates || {}),
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import * as Updates from 'expo-updates';
|
|
2
|
+
|
|
3
|
+
export interface UpdateEngineAdapter {
|
|
4
|
+
isEnabled(): boolean;
|
|
5
|
+
getCurrentUpdateId(): string | null;
|
|
6
|
+
getRuntimeVersion(): string | null;
|
|
7
|
+
getChannel(): string | null;
|
|
8
|
+
isEmbeddedLaunch(): boolean;
|
|
9
|
+
getCreatedAt(): Date | null;
|
|
10
|
+
checkForUpdate(): Promise<{ isAvailable: boolean; manifest: Record<string, unknown> | null }>;
|
|
11
|
+
fetchUpdate(): Promise<{ isNew: boolean; manifest: Record<string, unknown> | null }>;
|
|
12
|
+
reloadAsync(): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class ExpoUpdatesAdapter implements UpdateEngineAdapter {
|
|
16
|
+
public isEnabled(): boolean {
|
|
17
|
+
return Boolean(Updates.isEnabled);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
public getCurrentUpdateId(): string | null {
|
|
21
|
+
return Updates.updateId ?? null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
public getRuntimeVersion(): string | null {
|
|
25
|
+
return Updates.runtimeVersion ?? null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
public getChannel(): string | null {
|
|
29
|
+
return Updates.channel ?? null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
public isEmbeddedLaunch(): boolean {
|
|
33
|
+
return Boolean(Updates.isEmbeddedLaunch);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
public getCreatedAt(): Date | null {
|
|
37
|
+
return Updates.createdAt ?? null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public async checkForUpdate(): Promise<{ isAvailable: boolean; manifest: Record<string, unknown> | null }> {
|
|
41
|
+
const result = await Updates.checkForUpdateAsync();
|
|
42
|
+
return {
|
|
43
|
+
isAvailable: Boolean(result.isAvailable),
|
|
44
|
+
manifest: (result.manifest as Record<string, unknown> | undefined) ?? null,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
public async fetchUpdate(): Promise<{ isNew: boolean; manifest: Record<string, unknown> | null }> {
|
|
49
|
+
const result = await Updates.fetchUpdateAsync();
|
|
50
|
+
return {
|
|
51
|
+
isNew: Boolean(result.isNew),
|
|
52
|
+
manifest: (result.manifest as Record<string, unknown> | undefined) ?? null,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
public async reloadAsync(): Promise<void> {
|
|
57
|
+
await Updates.reloadAsync();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { Text, TouchableOpacity, View } from 'react-native';
|
|
3
|
+
import { useOTA } from '../hooks/useOTA';
|
|
4
|
+
|
|
5
|
+
export const OTAErrorView: React.FC<{ onRetry?: () => void }> = ({ onRetry }) => {
|
|
6
|
+
const { lastError, checkForUpdate } = useOTA();
|
|
7
|
+
if (!lastError) return null;
|
|
8
|
+
|
|
9
|
+
return (
|
|
10
|
+
<View style={{ backgroundColor: '#FEF2F2', borderRadius: 12, padding: 14, borderWidth: 1, borderColor: '#FECACA' }}>
|
|
11
|
+
<Text style={{ color: '#991B1B', fontWeight: '700', fontSize: 14 }}>OTA Error ({lastError.code})</Text>
|
|
12
|
+
<Text style={{ color: '#B91C1C', fontSize: 13, marginTop: 4 }}>{lastError.message}</Text>
|
|
13
|
+
<TouchableOpacity onPress={onRetry ?? checkForUpdate} style={{ marginTop: 10 }}>
|
|
14
|
+
<Text style={{ color: '#991B1B', fontWeight: '700', fontSize: 13 }}>Retry</Text>
|
|
15
|
+
</TouchableOpacity>
|
|
16
|
+
</View>
|
|
17
|
+
);
|
|
18
|
+
};
|
|
19
|
+
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { ActivityIndicator, Text, View } from 'react-native';
|
|
3
|
+
import { useOTA } from '../hooks/useOTA';
|
|
4
|
+
|
|
5
|
+
export interface OTAProgressProps {
|
|
6
|
+
accentColor?: string;
|
|
7
|
+
label?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const OTAProgress: React.FC<OTAProgressProps> = ({
|
|
11
|
+
accentColor = '#4F46E5',
|
|
12
|
+
label = 'Downloading update...',
|
|
13
|
+
}) => {
|
|
14
|
+
const { isDownloading, progress } = useOTA();
|
|
15
|
+
if (!isDownloading) return null;
|
|
16
|
+
|
|
17
|
+
return (
|
|
18
|
+
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: 8 }}>
|
|
19
|
+
<ActivityIndicator size="small" color={accentColor} />
|
|
20
|
+
<Text style={{ fontSize: 14, color: '#374151', fontWeight: '500' }}>
|
|
21
|
+
{label} ({progress}%)
|
|
22
|
+
</Text>
|
|
23
|
+
</View>
|
|
24
|
+
);
|
|
25
|
+
};
|
|
26
|
+
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { Text, TouchableOpacity, View } from 'react-native';
|
|
3
|
+
import { useOTA } from '../hooks/useOTA';
|
|
4
|
+
|
|
5
|
+
export const OTAUpdateAvailableView: React.FC<{ accentColor?: string }> = ({ accentColor = '#4F46E5' }) => {
|
|
6
|
+
const { isAvailable, updateInfo, fetchUpdate } = useOTA();
|
|
7
|
+
if (!isAvailable) return null;
|
|
8
|
+
|
|
9
|
+
return (
|
|
10
|
+
<View style={{ backgroundColor: '#EEF2FF', borderRadius: 12, padding: 14 }}>
|
|
11
|
+
<Text style={{ color: '#312E81', fontWeight: '700', fontSize: 14 }}>
|
|
12
|
+
Update Available {updateInfo.availableUpdateId ? `(${updateInfo.availableUpdateId.slice(0, 8)})` : ''}
|
|
13
|
+
</Text>
|
|
14
|
+
<TouchableOpacity
|
|
15
|
+
onPress={fetchUpdate}
|
|
16
|
+
style={{ marginTop: 10, backgroundColor: accentColor, paddingVertical: 10, borderRadius: 8, alignItems: 'center' }}
|
|
17
|
+
>
|
|
18
|
+
<Text style={{ color: '#FFFFFF', fontWeight: '700', fontSize: 13 }}>Download Update</Text>
|
|
19
|
+
</TouchableOpacity>
|
|
20
|
+
</View>
|
|
21
|
+
);
|
|
22
|
+
};
|
|
23
|
+
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { StyleProp, Text, TouchableOpacity, View, ViewStyle } from 'react-native';
|
|
3
|
+
import { useOTA } from '../hooks/useOTA';
|
|
4
|
+
|
|
5
|
+
export interface OTAUpdateBannerProps {
|
|
6
|
+
title?: string;
|
|
7
|
+
buttonText?: string;
|
|
8
|
+
accentColor?: string;
|
|
9
|
+
style?: StyleProp<ViewStyle>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const OTAUpdateBanner: React.FC<OTAUpdateBannerProps> = ({
|
|
13
|
+
title = 'A new update is available',
|
|
14
|
+
buttonText = 'Update',
|
|
15
|
+
accentColor = '#4F46E5',
|
|
16
|
+
style,
|
|
17
|
+
}) => {
|
|
18
|
+
const { isAvailable, isPending, fetchUpdate, reloadApp } = useOTA();
|
|
19
|
+
if (!isAvailable && !isPending) return null;
|
|
20
|
+
|
|
21
|
+
return (
|
|
22
|
+
<View
|
|
23
|
+
style={[
|
|
24
|
+
{
|
|
25
|
+
flexDirection: 'row',
|
|
26
|
+
alignItems: 'center',
|
|
27
|
+
justifyContent: 'space-between',
|
|
28
|
+
backgroundColor: '#111827',
|
|
29
|
+
paddingHorizontal: 16,
|
|
30
|
+
paddingVertical: 12,
|
|
31
|
+
borderRadius: 12,
|
|
32
|
+
},
|
|
33
|
+
style,
|
|
34
|
+
]}
|
|
35
|
+
>
|
|
36
|
+
<Text style={{ color: '#FFFFFF', fontSize: 14, fontWeight: '600', flex: 1 }}>
|
|
37
|
+
{isPending ? 'Update ready to install' : title}
|
|
38
|
+
</Text>
|
|
39
|
+
<TouchableOpacity
|
|
40
|
+
onPress={isPending ? reloadApp : fetchUpdate}
|
|
41
|
+
style={{ backgroundColor: accentColor, paddingHorizontal: 14, paddingVertical: 8, borderRadius: 8 }}
|
|
42
|
+
>
|
|
43
|
+
<Text style={{ color: '#FFFFFF', fontWeight: '700', fontSize: 13 }}>
|
|
44
|
+
{isPending ? 'Restart' : buttonText}
|
|
45
|
+
</Text>
|
|
46
|
+
</TouchableOpacity>
|
|
47
|
+
</View>
|
|
48
|
+
);
|
|
49
|
+
};
|
|
50
|
+
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import React, { useState } from 'react';
|
|
2
|
+
import { ActivityIndicator, Modal, StyleProp, Text, TextStyle, TouchableOpacity, View, ViewStyle } from 'react-native';
|
|
3
|
+
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
|
4
|
+
import { useOTA } from '../hooks/useOTA';
|
|
5
|
+
|
|
6
|
+
export interface OTAUpdateModalProps {
|
|
7
|
+
position?: 'bottom' | 'center' | 'top';
|
|
8
|
+
accentColor?: string;
|
|
9
|
+
title?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
laterButtonText?: string;
|
|
12
|
+
updateButtonText?: string;
|
|
13
|
+
overlayStyle?: StyleProp<ViewStyle>;
|
|
14
|
+
sheetStyle?: StyleProp<ViewStyle>;
|
|
15
|
+
titleStyle?: StyleProp<TextStyle>;
|
|
16
|
+
descriptionStyle?: StyleProp<TextStyle>;
|
|
17
|
+
laterButtonStyle?: StyleProp<ViewStyle>;
|
|
18
|
+
laterButtonTextStyle?: StyleProp<TextStyle>;
|
|
19
|
+
updateButtonStyle?: StyleProp<ViewStyle>;
|
|
20
|
+
updateButtonTextStyle?: StyleProp<TextStyle>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const OTAUpdateModal: React.FC<OTAUpdateModalProps> = ({
|
|
24
|
+
position = 'bottom',
|
|
25
|
+
accentColor = '#4F46E5',
|
|
26
|
+
title = 'Update Available',
|
|
27
|
+
description = 'A new update is available with the latest improvements. Would you like to update now?',
|
|
28
|
+
laterButtonText = 'Later',
|
|
29
|
+
updateButtonText = 'Update Now',
|
|
30
|
+
overlayStyle,
|
|
31
|
+
sheetStyle,
|
|
32
|
+
titleStyle,
|
|
33
|
+
descriptionStyle,
|
|
34
|
+
laterButtonStyle,
|
|
35
|
+
laterButtonTextStyle,
|
|
36
|
+
updateButtonStyle,
|
|
37
|
+
updateButtonTextStyle,
|
|
38
|
+
}) => {
|
|
39
|
+
const insets = useSafeAreaInsets();
|
|
40
|
+
const { isAvailable, isPending, isDownloading, fetchUpdate, reloadApp } = useOTA();
|
|
41
|
+
const [dismissed, setDismissed] = useState(false);
|
|
42
|
+
|
|
43
|
+
const visible = (isAvailable || isPending || isDownloading) && !dismissed;
|
|
44
|
+
const justifyContent = position === 'center' ? 'center' : position === 'top' ? 'flex-start' : 'flex-end';
|
|
45
|
+
|
|
46
|
+
return (
|
|
47
|
+
<Modal visible={visible} transparent animationType={position === 'center' ? 'fade' : 'slide'}>
|
|
48
|
+
<View style={[{ flex: 1, backgroundColor: 'rgba(0,0,0,0.45)', justifyContent, paddingHorizontal: position === 'center' ? 20 : 0 }, overlayStyle]}>
|
|
49
|
+
<View
|
|
50
|
+
style={[
|
|
51
|
+
{
|
|
52
|
+
backgroundColor: '#FFFFFF',
|
|
53
|
+
borderRadius: position === 'center' ? 20 : 0,
|
|
54
|
+
borderTopLeftRadius: position === 'bottom' ? 24 : position === 'center' ? 20 : 0,
|
|
55
|
+
borderTopRightRadius: position === 'bottom' ? 24 : position === 'center' ? 20 : 0,
|
|
56
|
+
borderBottomLeftRadius: position === 'top' ? 24 : position === 'center' ? 20 : 0,
|
|
57
|
+
borderBottomRightRadius: position === 'top' ? 24 : position === 'center' ? 20 : 0,
|
|
58
|
+
padding: 24,
|
|
59
|
+
paddingBottom: position === 'bottom' ? Math.max(insets.bottom, 20) + 12 : 24,
|
|
60
|
+
},
|
|
61
|
+
sheetStyle,
|
|
62
|
+
]}
|
|
63
|
+
>
|
|
64
|
+
<Text style={[{ fontSize: 18, fontWeight: '700', color: '#111827' }, titleStyle]}>
|
|
65
|
+
{isDownloading ? 'Updating App...' : isPending ? 'Update Ready' : title}
|
|
66
|
+
</Text>
|
|
67
|
+
<Text style={[{ marginTop: 6, fontSize: 14, color: '#6B7280', lineHeight: 20 }, descriptionStyle]}>
|
|
68
|
+
{isDownloading
|
|
69
|
+
? 'Downloading the latest update. The app will reload automatically.'
|
|
70
|
+
: isPending
|
|
71
|
+
? 'Restart the app to apply the downloaded update.'
|
|
72
|
+
: description}
|
|
73
|
+
</Text>
|
|
74
|
+
{isDownloading ? (
|
|
75
|
+
<View style={{ marginTop: 20, alignItems: 'center' }}>
|
|
76
|
+
<ActivityIndicator size="large" color={accentColor} />
|
|
77
|
+
</View>
|
|
78
|
+
) : (
|
|
79
|
+
<View style={{ flexDirection: 'row', gap: 12, marginTop: 20 }}>
|
|
80
|
+
<TouchableOpacity
|
|
81
|
+
onPress={() => setDismissed(true)}
|
|
82
|
+
style={[{ flex: 1, paddingVertical: 12, borderRadius: 12, borderWidth: 1, borderColor: '#D1D5DB', alignItems: 'center' }, laterButtonStyle]}
|
|
83
|
+
>
|
|
84
|
+
<Text style={[{ fontWeight: '600', color: '#374151' }, laterButtonTextStyle]}>{laterButtonText}</Text>
|
|
85
|
+
</TouchableOpacity>
|
|
86
|
+
<TouchableOpacity
|
|
87
|
+
onPress={isPending ? reloadApp : async () => { const ok = await fetchUpdate(); if (ok) await reloadApp(); }}
|
|
88
|
+
style={[{ flex: 1, paddingVertical: 12, borderRadius: 12, backgroundColor: accentColor, alignItems: 'center' }, updateButtonStyle]}
|
|
89
|
+
>
|
|
90
|
+
<Text style={[{ fontWeight: '700', color: '#FFFFFF' }, updateButtonTextStyle]}>
|
|
91
|
+
{isPending ? 'Restart' : updateButtonText}
|
|
92
|
+
</Text>
|
|
93
|
+
</TouchableOpacity>
|
|
94
|
+
</View>
|
|
95
|
+
)}
|
|
96
|
+
</View>
|
|
97
|
+
</View>
|
|
98
|
+
</Modal>
|
|
99
|
+
);
|
|
100
|
+
};
|
|
101
|
+
|
package/src/core/OTA.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { OTAManager } from '../managers/OTAManager';
|
|
2
|
+
|
|
3
|
+
export const otaManager = new OTAManager();
|
|
4
|
+
|
|
5
|
+
export const OTA = {
|
|
6
|
+
configure: otaManager.configure.bind(otaManager),
|
|
7
|
+
checkForUpdate: otaManager.checkForUpdate.bind(otaManager),
|
|
8
|
+
fetchUpdate: otaManager.fetchUpdate.bind(otaManager),
|
|
9
|
+
reloadApp: otaManager.reloadApp.bind(otaManager),
|
|
10
|
+
syncUpdate: otaManager.syncUpdate.bind(otaManager),
|
|
11
|
+
getUpdateInfo: otaManager.getUpdateInfo.bind(otaManager),
|
|
12
|
+
getCurrentVersion: otaManager.getCurrentVersion.bind(otaManager),
|
|
13
|
+
getRuntimeVersion: otaManager.getRuntimeVersion.bind(otaManager),
|
|
14
|
+
getUpdateChannel: otaManager.getUpdateChannel.bind(otaManager),
|
|
15
|
+
getUpdateStatus: otaManager.getUpdateStatus.bind(otaManager),
|
|
16
|
+
isUpdateAvailable: otaManager.isUpdateAvailable.bind(otaManager),
|
|
17
|
+
isUpdatePending: otaManager.isUpdatePending.bind(otaManager),
|
|
18
|
+
getLastUpdateError: otaManager.getLastUpdateError.bind(otaManager),
|
|
19
|
+
rollbackUpdate: otaManager.rollbackUpdate.bind(otaManager),
|
|
20
|
+
setUpdateStrategy: otaManager.setUpdateStrategy.bind(otaManager),
|
|
21
|
+
};
|
|
22
|
+
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { OTAErrorCode, OTAErrorInfo } from '../types';
|
|
2
|
+
|
|
3
|
+
export class OTAError extends Error {
|
|
4
|
+
public readonly code: OTAErrorCode;
|
|
5
|
+
public readonly timestamp: number;
|
|
6
|
+
public readonly recoverable: boolean;
|
|
7
|
+
public readonly cause?: unknown;
|
|
8
|
+
|
|
9
|
+
constructor(code: OTAErrorCode, message: string, recoverable = true, cause?: unknown) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'OTAError';
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.timestamp = Date.now();
|
|
14
|
+
this.recoverable = recoverable;
|
|
15
|
+
this.cause = cause;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
public toInfo(): OTAErrorInfo {
|
|
19
|
+
return {
|
|
20
|
+
code: this.code,
|
|
21
|
+
message: this.message,
|
|
22
|
+
timestamp: this.timestamp,
|
|
23
|
+
recoverable: this.recoverable,
|
|
24
|
+
cause: this.cause,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import React, { createContext, useContext, useEffect, useState } from 'react';
|
|
2
|
+
import { otaManager } from '../core/OTA';
|
|
3
|
+
import type { OTAConfig, OTAContextValue } from '../types';
|
|
4
|
+
|
|
5
|
+
const OTAContext = createContext<OTAContextValue | null>(null);
|
|
6
|
+
|
|
7
|
+
export interface OTAProviderProps {
|
|
8
|
+
children: React.ReactNode;
|
|
9
|
+
config?: OTAConfig;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const OTAProvider: React.FC<OTAProviderProps> = ({ children, config }) => {
|
|
13
|
+
const [, setTick] = useState(0);
|
|
14
|
+
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
if (config) {
|
|
17
|
+
otaManager.configure(config);
|
|
18
|
+
}
|
|
19
|
+
const unsub = otaManager.subscribe(() => setTick((t) => t + 1));
|
|
20
|
+
const stop = otaManager.start();
|
|
21
|
+
return () => {
|
|
22
|
+
unsub();
|
|
23
|
+
stop();
|
|
24
|
+
};
|
|
25
|
+
}, [config]);
|
|
26
|
+
|
|
27
|
+
const status = otaManager.getUpdateStatus();
|
|
28
|
+
const value: OTAContextValue = {
|
|
29
|
+
status,
|
|
30
|
+
progress: otaManager.getProgress(),
|
|
31
|
+
updateInfo: otaManager.getUpdateInfo(),
|
|
32
|
+
lastError: otaManager.getLastUpdateError(),
|
|
33
|
+
isAvailable: otaManager.isUpdateAvailable(),
|
|
34
|
+
isPending: otaManager.isUpdatePending(),
|
|
35
|
+
isChecking: status === 'checking',
|
|
36
|
+
isDownloading: status === 'downloading',
|
|
37
|
+
checkForUpdate: () => otaManager.checkForUpdate(),
|
|
38
|
+
fetchUpdate: () => otaManager.fetchUpdate(),
|
|
39
|
+
reloadApp: () => otaManager.reloadApp(),
|
|
40
|
+
syncUpdate: () => otaManager.syncUpdate(),
|
|
41
|
+
rollbackUpdate: () => otaManager.rollbackUpdate(),
|
|
42
|
+
setUpdateStrategy: (strategy) => otaManager.setUpdateStrategy(strategy),
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
return <OTAContext.Provider value={value}>{children}</OTAContext.Provider>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export function useOTA(): OTAContextValue {
|
|
49
|
+
const ctx = useContext(OTAContext);
|
|
50
|
+
if (!ctx) {
|
|
51
|
+
throw new Error('useOTA() must be used inside <OTAProvider>');
|
|
52
|
+
}
|
|
53
|
+
return ctx;
|
|
54
|
+
}
|
|
55
|
+
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export { OTA, otaManager } from './core/OTA';
|
|
2
|
+
export { OTAManager } from './managers/OTAManager';
|
|
3
|
+
export { OTAProvider, useOTA } from './hooks/useOTA';
|
|
4
|
+
export type { OTAProviderProps } from './hooks/useOTA';
|
|
5
|
+
export { OTAUpdateBanner } from './components/OTAUpdateBanner';
|
|
6
|
+
export type { OTAUpdateBannerProps } from './components/OTAUpdateBanner';
|
|
7
|
+
export { OTAProgress } from './components/OTAProgress';
|
|
8
|
+
export type { OTAProgressProps } from './components/OTAProgress';
|
|
9
|
+
export { OTAUpdateModal } from './components/OTAUpdateModal';
|
|
10
|
+
export type { OTAUpdateModalProps } from './components/OTAUpdateModal';
|
|
11
|
+
export { OTAErrorView } from './components/OTAErrorView';
|
|
12
|
+
export { OTAUpdateAvailableView } from './components/OTAUpdateAvailableView';
|
|
13
|
+
export { OTAError } from './errors/OTAError';
|
|
14
|
+
export { RuntimeCompatibilityService } from './services/RuntimeCompatibilityService';
|
|
15
|
+
export { ExpoUpdatesAdapter } from './adapters/ExpoUpdatesAdapter';
|
|
16
|
+
export type { UpdateEngineAdapter } from './adapters/ExpoUpdatesAdapter';
|
|
17
|
+
export { otaAnalytics, OTAAnalyticsService } from './services/OTAAnalyticsService';
|
|
18
|
+
export type { OTAAnalyticsEvent, OTAAnalyticsEventName, OTAAnalyticsHandler } from './services/OTAAnalyticsService';
|
|
19
|
+
export { otaLogger, OTALogger } from './utils/logger';
|
|
20
|
+
export type {
|
|
21
|
+
OTAConfig,
|
|
22
|
+
OTAContextValue,
|
|
23
|
+
OTAErrorCode,
|
|
24
|
+
OTAErrorInfo,
|
|
25
|
+
OTALogLevel,
|
|
26
|
+
OTAStrategy,
|
|
27
|
+
OTAUpdateInfo,
|
|
28
|
+
OTAUpdateStatus,
|
|
29
|
+
} from './types';
|
|
30
|
+
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { AppState, AppStateStatus } from 'react-native';
|
|
2
|
+
import { ExpoUpdatesAdapter, UpdateEngineAdapter } from '../adapters/ExpoUpdatesAdapter';
|
|
3
|
+
import { OTAError } from '../errors/OTAError';
|
|
4
|
+
import { RuntimeCompatibilityService } from '../services/RuntimeCompatibilityService';
|
|
5
|
+
import type {
|
|
6
|
+
OTAConfig,
|
|
7
|
+
OTAErrorInfo,
|
|
8
|
+
OTAStrategy,
|
|
9
|
+
OTAUpdateInfo,
|
|
10
|
+
OTAUpdateStatus,
|
|
11
|
+
} from '../types';
|
|
12
|
+
import { otaLogger } from '../utils/logger';
|
|
13
|
+
|
|
14
|
+
declare const __DEV__: boolean;
|
|
15
|
+
|
|
16
|
+
export type OTAListener = () => void;
|
|
17
|
+
|
|
18
|
+
export class OTAManager {
|
|
19
|
+
private adapter: UpdateEngineAdapter;
|
|
20
|
+
private config: Required<
|
|
21
|
+
Pick<
|
|
22
|
+
OTAConfig,
|
|
23
|
+
| 'strategy'
|
|
24
|
+
| 'checkOnLaunch'
|
|
25
|
+
| 'checkOnForeground'
|
|
26
|
+
| 'checkIntervalMs'
|
|
27
|
+
| 'confirmBeforeReload'
|
|
28
|
+
| 'logLevel'
|
|
29
|
+
>
|
|
30
|
+
> &
|
|
31
|
+
OTAConfig;
|
|
32
|
+
|
|
33
|
+
private status: OTAUpdateStatus = 'idle';
|
|
34
|
+
private progress = 0;
|
|
35
|
+
private isAvailableState = false;
|
|
36
|
+
private isPendingState = false;
|
|
37
|
+
private availableUpdateId: string | null = null;
|
|
38
|
+
private availableManifest: Record<string, unknown> | null = null;
|
|
39
|
+
private lastError: OTAErrorInfo | null = null;
|
|
40
|
+
private activeOperation: Promise<unknown> | null = null;
|
|
41
|
+
private intervalId: ReturnType<typeof setInterval> | null = null;
|
|
42
|
+
private appStateSub: { remove: () => void } | null = null;
|
|
43
|
+
private listeners = new Set<OTAListener>();
|
|
44
|
+
|
|
45
|
+
constructor(adapter: UpdateEngineAdapter = new ExpoUpdatesAdapter(), config: OTAConfig = {}) {
|
|
46
|
+
this.adapter = adapter;
|
|
47
|
+
this.config = {
|
|
48
|
+
strategy: 'automatic',
|
|
49
|
+
checkOnLaunch: true,
|
|
50
|
+
checkOnForeground: true,
|
|
51
|
+
checkIntervalMs: 120000,
|
|
52
|
+
confirmBeforeReload: false,
|
|
53
|
+
logLevel: 'info',
|
|
54
|
+
...config,
|
|
55
|
+
};
|
|
56
|
+
otaLogger.setLevel(this.config.logLevel);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
public configure(config: OTAConfig): void {
|
|
60
|
+
this.config = { ...this.config, ...config };
|
|
61
|
+
if (config.logLevel) {
|
|
62
|
+
otaLogger.setLevel(config.logLevel);
|
|
63
|
+
}
|
|
64
|
+
this.notify();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
public setUpdateStrategy(strategy: OTAStrategy): void {
|
|
68
|
+
this.config.strategy = strategy;
|
|
69
|
+
otaLogger.info(`Update strategy set to: ${strategy}`);
|
|
70
|
+
this.notify();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
public subscribe(listener: OTAListener): () => void {
|
|
74
|
+
this.listeners.add(listener);
|
|
75
|
+
return () => this.listeners.delete(listener);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private notify(): void {
|
|
79
|
+
this.listeners.forEach((l) => l());
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private setStatus(status: OTAUpdateStatus): void {
|
|
83
|
+
this.status = status;
|
|
84
|
+
this.config.onStatusChange?.(status);
|
|
85
|
+
this.notify();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private setProgress(value: number): void {
|
|
89
|
+
this.progress = value;
|
|
90
|
+
this.config.onProgress?.(value);
|
|
91
|
+
this.notify();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private handleError(err: unknown, fallbackCode: OTAError['code'], fallbackMsg: string): OTAErrorInfo {
|
|
95
|
+
const otaErr =
|
|
96
|
+
err instanceof OTAError
|
|
97
|
+
? err
|
|
98
|
+
: new OTAError(fallbackCode, err instanceof Error ? err.message : fallbackMsg, true, err);
|
|
99
|
+
const info = otaErr.toInfo();
|
|
100
|
+
this.lastError = info;
|
|
101
|
+
this.setStatus('error');
|
|
102
|
+
otaLogger.error(`${info.code}: ${info.message}`);
|
|
103
|
+
this.config.onError?.(info);
|
|
104
|
+
return info;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
public start(): () => void {
|
|
108
|
+
otaLogger.info('Initializing OTA manager');
|
|
109
|
+
otaLogger.info(`Current runtime version: ${this.getRuntimeVersion() ?? 'unknown'}`);
|
|
110
|
+
otaLogger.info(`Current update ID: ${this.getCurrentVersion() ?? 'embedded'}`);
|
|
111
|
+
|
|
112
|
+
if (this.config.checkOnLaunch) {
|
|
113
|
+
void this.syncOnTrigger();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const startPolling = () => {
|
|
117
|
+
if (!this.intervalId && this.config.checkIntervalMs > 0) {
|
|
118
|
+
this.intervalId = setInterval(() => {
|
|
119
|
+
void this.syncOnTrigger();
|
|
120
|
+
}, this.config.checkIntervalMs);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const stopPolling = () => {
|
|
125
|
+
if (this.intervalId) {
|
|
126
|
+
clearInterval(this.intervalId);
|
|
127
|
+
this.intervalId = null;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
startPolling();
|
|
132
|
+
|
|
133
|
+
this.appStateSub = AppState.addEventListener('change', (nextState: AppStateStatus) => {
|
|
134
|
+
if (nextState === 'active') {
|
|
135
|
+
if (this.config.checkOnForeground) {
|
|
136
|
+
void this.syncOnTrigger();
|
|
137
|
+
}
|
|
138
|
+
startPolling();
|
|
139
|
+
} else {
|
|
140
|
+
stopPolling();
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
return () => {
|
|
145
|
+
stopPolling();
|
|
146
|
+
this.appStateSub?.remove();
|
|
147
|
+
this.appStateSub = null;
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private async syncOnTrigger(): Promise<void> {
|
|
152
|
+
if (this.config.strategy === 'manual') return;
|
|
153
|
+
await this.syncUpdate();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
public getUpdateInfo(): OTAUpdateInfo {
|
|
157
|
+
return {
|
|
158
|
+
isAvailable: this.isAvailableState,
|
|
159
|
+
isPending: this.isPendingState,
|
|
160
|
+
isEmbeddedLaunch: this.adapter.isEmbeddedLaunch(),
|
|
161
|
+
currentUpdateId: this.adapter.getCurrentUpdateId(),
|
|
162
|
+
availableUpdateId: this.availableUpdateId,
|
|
163
|
+
runtimeVersion: this.adapter.getRuntimeVersion(),
|
|
164
|
+
channel: this.adapter.getChannel() ?? this.config.channel ?? null,
|
|
165
|
+
createdAt: this.adapter.getCreatedAt(),
|
|
166
|
+
manifest: this.availableManifest,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
public getCurrentVersion(): string | null {
|
|
171
|
+
return this.adapter.getCurrentUpdateId();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
public getRuntimeVersion(): string | null {
|
|
175
|
+
return this.adapter.getRuntimeVersion();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
public getUpdateChannel(): string | null {
|
|
179
|
+
return this.adapter.getChannel() ?? this.config.channel ?? null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
public getUpdateStatus(): OTAUpdateStatus {
|
|
183
|
+
return this.status;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
public getProgress(): number {
|
|
187
|
+
return this.progress;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
public isUpdateAvailable(): boolean {
|
|
191
|
+
return this.isAvailableState;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
public isUpdatePending(): boolean {
|
|
195
|
+
return this.isPendingState;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
public getLastUpdateError(): OTAErrorInfo | null {
|
|
199
|
+
return this.lastError;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
public async checkForUpdate(): Promise<OTAUpdateInfo> {
|
|
203
|
+
if (typeof __DEV__ !== 'undefined' && __DEV__) {
|
|
204
|
+
otaLogger.debug('Skipping OTA check in __DEV__ mode');
|
|
205
|
+
this.setStatus('disabled');
|
|
206
|
+
return this.getUpdateInfo();
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (!this.adapter.isEnabled()) {
|
|
210
|
+
otaLogger.warn('expo-updates is disabled in this build');
|
|
211
|
+
this.setStatus('disabled');
|
|
212
|
+
return this.getUpdateInfo();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (this.activeOperation) {
|
|
216
|
+
otaLogger.debug('Update operation already in progress');
|
|
217
|
+
return this.getUpdateInfo();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
this.activeOperation = (async () => {
|
|
221
|
+
try {
|
|
222
|
+
this.setStatus('checking');
|
|
223
|
+
otaLogger.info('Checking for updates');
|
|
224
|
+
const res = await this.adapter.checkForUpdate();
|
|
225
|
+
if (res.isAvailable) {
|
|
226
|
+
RuntimeCompatibilityService.validate({
|
|
227
|
+
deviceRuntimeVersion: this.adapter.getRuntimeVersion(),
|
|
228
|
+
expectedRuntimeVersion: this.config.expectedRuntimeVersion,
|
|
229
|
+
manifest: res.manifest,
|
|
230
|
+
});
|
|
231
|
+
this.isAvailableState = true;
|
|
232
|
+
this.availableManifest = res.manifest;
|
|
233
|
+
this.availableUpdateId = (res.manifest?.id as string | undefined) ?? null;
|
|
234
|
+
this.setStatus('available');
|
|
235
|
+
otaLogger.info('Update available');
|
|
236
|
+
} else {
|
|
237
|
+
this.isAvailableState = false;
|
|
238
|
+
this.setStatus('up_to_date');
|
|
239
|
+
otaLogger.info('App is up to date');
|
|
240
|
+
}
|
|
241
|
+
} catch (err) {
|
|
242
|
+
this.handleError(err, 'NETWORK_ERROR', 'Failed to check for updates');
|
|
243
|
+
} finally {
|
|
244
|
+
this.activeOperation = null;
|
|
245
|
+
}
|
|
246
|
+
})();
|
|
247
|
+
|
|
248
|
+
await this.activeOperation;
|
|
249
|
+
return this.getUpdateInfo();
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
public async fetchUpdate(): Promise<boolean> {
|
|
253
|
+
if (this.activeOperation) {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
let downloaded = false;
|
|
258
|
+
this.activeOperation = (async () => {
|
|
259
|
+
try {
|
|
260
|
+
this.setStatus('downloading');
|
|
261
|
+
this.setProgress(0);
|
|
262
|
+
otaLogger.info('Download started');
|
|
263
|
+
const res = await this.adapter.fetchUpdate();
|
|
264
|
+
this.setProgress(100);
|
|
265
|
+
if (res.isNew) {
|
|
266
|
+
this.isPendingState = true;
|
|
267
|
+
this.isAvailableState = false;
|
|
268
|
+
this.setStatus('downloaded');
|
|
269
|
+
otaLogger.info('Download completed');
|
|
270
|
+
otaLogger.info('Update ready');
|
|
271
|
+
downloaded = true;
|
|
272
|
+
} else {
|
|
273
|
+
this.setStatus('up_to_date');
|
|
274
|
+
}
|
|
275
|
+
} catch (err) {
|
|
276
|
+
this.handleError(err, 'DOWNLOAD_FAILED', 'Failed to download update');
|
|
277
|
+
} finally {
|
|
278
|
+
this.activeOperation = null;
|
|
279
|
+
}
|
|
280
|
+
})();
|
|
281
|
+
|
|
282
|
+
await this.activeOperation;
|
|
283
|
+
return downloaded;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
public async reloadApp(): Promise<void> {
|
|
287
|
+
if (this.config.isCriticalOperationActive?.()) {
|
|
288
|
+
otaLogger.warn('Deferring reload: critical operation in progress');
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
try {
|
|
293
|
+
otaLogger.info('Reloading application');
|
|
294
|
+
await this.adapter.reloadAsync();
|
|
295
|
+
otaLogger.info('Update successfully applied');
|
|
296
|
+
} catch (err) {
|
|
297
|
+
this.handleError(err, 'RELOAD_FAILED', 'Failed to reload application');
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
public async syncUpdate(): Promise<boolean> {
|
|
302
|
+
const info = await this.checkForUpdate();
|
|
303
|
+
if (!info.isAvailable) return false;
|
|
304
|
+
|
|
305
|
+
if (this.config.strategy === 'manual') {
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const fetched = await this.fetchUpdate();
|
|
310
|
+
if (!fetched) return false;
|
|
311
|
+
|
|
312
|
+
const shouldReloadImmediately =
|
|
313
|
+
(this.config.strategy === 'automatic' ||
|
|
314
|
+
this.config.strategy === 'immediate' ||
|
|
315
|
+
this.config.strategy === 'critical') &&
|
|
316
|
+
!this.config.confirmBeforeReload;
|
|
317
|
+
|
|
318
|
+
if (shouldReloadImmediately) {
|
|
319
|
+
await this.reloadApp();
|
|
320
|
+
}
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
public async rollbackUpdate(): Promise<boolean> {
|
|
325
|
+
otaLogger.warn(
|
|
326
|
+
'expo-updates automatically falls back to the embedded or previous working update on launch failure; programmatic rollback to an arbitrary older update is not supported.'
|
|
327
|
+
);
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type OTAAnalyticsEventName =
|
|
2
|
+
| 'update_available'
|
|
3
|
+
| 'update_downloaded'
|
|
4
|
+
| 'update_installed'
|
|
5
|
+
| 'update_applied'
|
|
6
|
+
| 'update_failed'
|
|
7
|
+
| 'update_rolled_back';
|
|
8
|
+
|
|
9
|
+
export interface OTAAnalyticsEvent {
|
|
10
|
+
name: OTAAnalyticsEventName;
|
|
11
|
+
timestamp: number;
|
|
12
|
+
updateId?: string | null;
|
|
13
|
+
runtimeVersion?: string | null;
|
|
14
|
+
channel?: string | null;
|
|
15
|
+
errorCode?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type OTAAnalyticsHandler = (event: OTAAnalyticsEvent) => void;
|
|
19
|
+
|
|
20
|
+
export class OTAAnalyticsService {
|
|
21
|
+
private handler: OTAAnalyticsHandler | null = null;
|
|
22
|
+
private history: OTAAnalyticsEvent[] = [];
|
|
23
|
+
|
|
24
|
+
public setHandler(handler: OTAAnalyticsHandler | null): void {
|
|
25
|
+
this.handler = handler;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
public track(event: Omit<OTAAnalyticsEvent, 'timestamp'>): void {
|
|
29
|
+
const fullEvent: OTAAnalyticsEvent = { ...event, timestamp: Date.now() };
|
|
30
|
+
this.history.push(fullEvent);
|
|
31
|
+
this.handler?.(fullEvent);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
public getHistory(): OTAAnalyticsEvent[] {
|
|
35
|
+
return [...this.history];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const otaAnalytics = new OTAAnalyticsService();
|
|
40
|
+
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Platform } from 'react-native';
|
|
2
|
+
import { OTAError } from '../errors/OTAError';
|
|
3
|
+
|
|
4
|
+
export interface RuntimeCompatibilityInput {
|
|
5
|
+
deviceRuntimeVersion: string | null;
|
|
6
|
+
expectedRuntimeVersion?: string;
|
|
7
|
+
manifest?: Record<string, unknown> | null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class RuntimeCompatibilityService {
|
|
11
|
+
public static validate(input: RuntimeCompatibilityInput): void {
|
|
12
|
+
const { deviceRuntimeVersion, expectedRuntimeVersion, manifest } = input;
|
|
13
|
+
|
|
14
|
+
if (expectedRuntimeVersion && deviceRuntimeVersion && expectedRuntimeVersion !== deviceRuntimeVersion) {
|
|
15
|
+
throw new OTAError(
|
|
16
|
+
'INCOMPATIBLE_RUNTIME',
|
|
17
|
+
`Runtime version mismatch: device has "${deviceRuntimeVersion}", expected "${expectedRuntimeVersion}". A new binary build is required.`,
|
|
18
|
+
false
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const manifestRuntime = manifest?.runtimeVersion;
|
|
23
|
+
if (
|
|
24
|
+
typeof manifestRuntime === 'string' &&
|
|
25
|
+
deviceRuntimeVersion &&
|
|
26
|
+
manifestRuntime !== deviceRuntimeVersion
|
|
27
|
+
) {
|
|
28
|
+
throw new OTAError(
|
|
29
|
+
'INCOMPATIBLE_RUNTIME',
|
|
30
|
+
`Update runtimeVersion "${manifestRuntime}" is incompatible with installed binary "${deviceRuntimeVersion}" on ${Platform.OS}.`,
|
|
31
|
+
false
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export type OTAUpdateStatus =
|
|
2
|
+
| 'idle'
|
|
3
|
+
| 'checking'
|
|
4
|
+
| 'available'
|
|
5
|
+
| 'downloading'
|
|
6
|
+
| 'downloaded'
|
|
7
|
+
| 'up_to_date'
|
|
8
|
+
| 'error'
|
|
9
|
+
| 'disabled';
|
|
10
|
+
|
|
11
|
+
export type OTAStrategy =
|
|
12
|
+
| 'automatic'
|
|
13
|
+
| 'manual'
|
|
14
|
+
| 'background_download'
|
|
15
|
+
| 'immediate'
|
|
16
|
+
| 'on_next_launch'
|
|
17
|
+
| 'critical';
|
|
18
|
+
|
|
19
|
+
export type OTALogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug';
|
|
20
|
+
|
|
21
|
+
export type OTAErrorCode =
|
|
22
|
+
| 'OTA_DISABLED'
|
|
23
|
+
| 'DEV_MODE_SKIPPED'
|
|
24
|
+
| 'NETWORK_ERROR'
|
|
25
|
+
| 'INCOMPATIBLE_RUNTIME'
|
|
26
|
+
| 'DOWNLOAD_FAILED'
|
|
27
|
+
| 'VERIFICATION_FAILED'
|
|
28
|
+
| 'RELOAD_FAILED'
|
|
29
|
+
| 'ROLLBACK_UNSUPPORTED'
|
|
30
|
+
| 'OPERATION_IN_PROGRESS'
|
|
31
|
+
| 'UNKNOWN_ERROR';
|
|
32
|
+
|
|
33
|
+
export interface OTAUpdateInfo {
|
|
34
|
+
isAvailable: boolean;
|
|
35
|
+
isPending: boolean;
|
|
36
|
+
isEmbeddedLaunch: boolean;
|
|
37
|
+
currentUpdateId: string | null;
|
|
38
|
+
availableUpdateId: string | null;
|
|
39
|
+
runtimeVersion: string | null;
|
|
40
|
+
channel: string | null;
|
|
41
|
+
createdAt: Date | null;
|
|
42
|
+
manifest: Record<string, unknown> | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface OTAConfig {
|
|
46
|
+
strategy?: OTAStrategy;
|
|
47
|
+
checkOnLaunch?: boolean;
|
|
48
|
+
checkOnForeground?: boolean;
|
|
49
|
+
checkIntervalMs?: number;
|
|
50
|
+
confirmBeforeReload?: boolean;
|
|
51
|
+
isCriticalOperationActive?: () => boolean;
|
|
52
|
+
logLevel?: OTALogLevel;
|
|
53
|
+
expectedRuntimeVersion?: string;
|
|
54
|
+
channel?: string;
|
|
55
|
+
onStatusChange?: (status: OTAUpdateStatus) => void;
|
|
56
|
+
onProgress?: (progress: number) => void;
|
|
57
|
+
onError?: (error: OTAErrorInfo) => void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface OTAErrorInfo {
|
|
61
|
+
code: OTAErrorCode;
|
|
62
|
+
message: string;
|
|
63
|
+
timestamp: number;
|
|
64
|
+
recoverable: boolean;
|
|
65
|
+
cause?: unknown;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface OTAContextValue {
|
|
69
|
+
status: OTAUpdateStatus;
|
|
70
|
+
progress: number;
|
|
71
|
+
updateInfo: OTAUpdateInfo;
|
|
72
|
+
lastError: OTAErrorInfo | null;
|
|
73
|
+
isAvailable: boolean;
|
|
74
|
+
isPending: boolean;
|
|
75
|
+
isChecking: boolean;
|
|
76
|
+
isDownloading: boolean;
|
|
77
|
+
checkForUpdate: () => Promise<OTAUpdateInfo>;
|
|
78
|
+
fetchUpdate: () => Promise<boolean>;
|
|
79
|
+
reloadApp: () => Promise<void>;
|
|
80
|
+
syncUpdate: () => Promise<boolean>;
|
|
81
|
+
rollbackUpdate: () => Promise<boolean>;
|
|
82
|
+
setUpdateStrategy: (strategy: OTAStrategy) => void;
|
|
83
|
+
}
|
|
84
|
+
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { OTALogLevel } from '../types';
|
|
2
|
+
|
|
3
|
+
const LEVEL_PRIORITY: Record<OTALogLevel, number> = {
|
|
4
|
+
none: 0,
|
|
5
|
+
error: 1,
|
|
6
|
+
warn: 2,
|
|
7
|
+
info: 3,
|
|
8
|
+
debug: 4,
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export class OTALogger {
|
|
12
|
+
private level: OTALogLevel = 'info';
|
|
13
|
+
|
|
14
|
+
public setLevel(level: OTALogLevel): void {
|
|
15
|
+
this.level = level;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
public getLevel(): OTALogLevel {
|
|
19
|
+
return this.level;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
private shouldLog(target: OTALogLevel): boolean {
|
|
23
|
+
return LEVEL_PRIORITY[this.level] >= LEVEL_PRIORITY[target];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
public debug(message: string, ...args: unknown[]): void {
|
|
27
|
+
if (this.shouldLog('debug')) {
|
|
28
|
+
console.debug(`[OTA] ${message}`, ...args);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
public info(message: string, ...args: unknown[]): void {
|
|
33
|
+
if (this.shouldLog('info')) {
|
|
34
|
+
console.info(`[OTA] ${message}`, ...args);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
public warn(message: string, ...args: unknown[]): void {
|
|
39
|
+
if (this.shouldLog('warn')) {
|
|
40
|
+
console.warn(`[OTA] ${message}`, ...args);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
public error(message: string, ...args: unknown[]): void {
|
|
45
|
+
if (this.shouldLog('error')) {
|
|
46
|
+
console.error(`[OTA] ${message}`, ...args);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const otaLogger = new OTALogger();
|
|
52
|
+
|