ota-native-bridge 1.8.0 → 1.8.2

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 CHANGED
@@ -56,6 +56,9 @@ if (Native.isNativePlatform()) {
56
56
  | 读机型 / 系统 / CPU / Canvas / WebGL | `Device.getEnvironmentInfo()` 一次返回(含系统版本、厂商、型号);也可分别调用 `getInfo()` / `getSystemInfo()` / `getCpuInfo()` / `getCanvasRenderInfo()` / `getWebGlInfo()` |
57
57
  | 用资源包里的图换桌面图标 | `Icon.setFromResource({ path: 'icons/app-icon.png' })`(Android 8+;iOS / Harmony 返回失败) |
58
58
  | 加密 Client API 请求 | `Crypto.postEncrypted(url, plain, pem)` |
59
+ | 监听安装进度(Android) | `Ota.onInstallEvent(fn)`,返回取消函数 |
60
+ | 新应用是否正在迁移 / 迁移后首启 | `Migration.getStatus()` → `{ inProgress, firstLaunch, phase }`,各平台可直接调用(1.8.1+) |
61
+ | 换包后迁移登录态 / 数据(Android) | 旧应用 `Migration.setExtras({ extras, cookieUrls })`;新应用 `Migration.getInfo()`,详见 [USAGE §5.3.1](./docs/USAGE.md) |
59
62
 
60
63
  ## OTA 服务端地址
61
64
 
@@ -236,12 +236,76 @@ exports.Ota = {
236
236
  return (0, runtime_1.withCallback)((0, runtime_1.invokeNative)('getAppInstallState'), callback);
237
237
  },
238
238
  };
239
+ /** 等待 Bridge 注入的时间。壳里 Bridge 在页面脚本之前就在了;超时说明在普通浏览器 */
240
+ const MIGRATION_STATUS_READY_TIMEOUT_MS = 1500;
241
+ /** 不支持迁移的平台上 `Migration.getStatus()` 的结果 */
242
+ const MIGRATION_UNSUPPORTED_STATUS = {
243
+ supported: false,
244
+ phase: 'none',
245
+ inProgress: false,
246
+ firstLaunch: false,
247
+ imported: false,
248
+ webApplied: false,
249
+ fromPackage: '',
250
+ importedAt: 0,
251
+ lastError: '',
252
+ };
253
+ /**
254
+ * 短时间等 Bridge 注入。不复用 `whenReady`:它的等待是全局共享的,
255
+ * 这里的短超时会连带让别处正在等待的调用提前失败。
256
+ */
257
+ function waitForBridgeBriefly(timeoutMs) {
258
+ if ((0, runtime_1.isNativeBridgeAvailable)()) {
259
+ return Promise.resolve();
260
+ }
261
+ if (typeof document === 'undefined') {
262
+ return Promise.reject(new Error('Not in browser'));
263
+ }
264
+ return new Promise((resolve, reject) => {
265
+ const onReady = () => {
266
+ clearTimeout(timer);
267
+ resolve();
268
+ };
269
+ const timer = setTimeout(() => {
270
+ document.removeEventListener('nativebridgeready', onReady);
271
+ reject(new Error('Bridge timeout'));
272
+ }, timeoutMs);
273
+ document.addEventListener('nativebridgeready', onReady, { once: true });
274
+ });
275
+ }
276
+ /**
277
+ * 判断错误是不是"这里没有迁移能力":没有 Bridge(普通浏览器),
278
+ * 或壳没实现该方法(iOS / Harmony / 桌面端 / 旧版 Android 壳)。
279
+ */
280
+ function isMigrationUnsupported(error) {
281
+ const message = error instanceof Error ? error.message : String(error);
282
+ return /Unknown method|桌面壳未实现|Native bridge not available|Bridge timeout|Not in browser/i.test(message);
283
+ }
239
284
  /**
240
285
  * 换包更新的数据迁移(Android)。新安装包的包名与当前应用不同时,
241
286
  * 装好后当前应用会自动拉起新应用,把登录状态(Cookie / localStorage)、
242
287
  * 设备序列号和 `setExtras` 的数据交给它,完成后请求卸载当前应用。
243
288
  */
244
289
  exports.Migration = {
290
+ /**
291
+ * 当前是否正在迁移,以及是不是迁移后的第一次启动。用来决定要不要等待、跳过登录或引导页。
292
+ *
293
+ * 任何平台都可以直接调用,不用先判断平台:不是 Android 壳(或壳版本不带迁移)时,
294
+ * 返回 `{ supported: false, inProgress: false, firstLaunch: false, phase: 'none', ... }`。
295
+ * 其它错误照常抛出。
296
+ */
297
+ getStatus(callback) {
298
+ // 普通浏览器里没有 Bridge:很快就判定为不支持,不要卡满默认的 8 秒
299
+ const promise = waitForBridgeBriefly(MIGRATION_STATUS_READY_TIMEOUT_MS)
300
+ .then(() => (0, runtime_1.callNative)('getMigrationStatus'))
301
+ .catch((error) => {
302
+ if (isMigrationUnsupported(error)) {
303
+ return { ...MIGRATION_UNSUPPORTED_STATUS };
304
+ }
305
+ throw error;
306
+ });
307
+ return (0, runtime_1.withCallback)(promise, callback);
308
+ },
245
309
  /**
246
310
  * 迁移前补充要带走的数据。建议在登录后和每次登录态变化时调用。
247
311
  * 新应用通过 `Migration.getInfo().extras` 读取。
@@ -4,4 +4,4 @@ exports.SDK_VERSION = exports.PACKAGE_NAME = void 0;
4
4
  /** npm 包名(与 package.json name 保持一致) */
5
5
  exports.PACKAGE_NAME = 'ota-native-bridge';
6
6
  /** OTA Native Bridge SDK 版本(与 package.json version 保持一致) */
7
- exports.SDK_VERSION = '1.8.0';
7
+ exports.SDK_VERSION = '1.8.2';
package/dist/native.d.ts CHANGED
@@ -54,6 +54,17 @@ export declare const Native: {
54
54
  getInstallState(callback?: import("./runtime").NativeCallback<import("./types").AppInstallState>): Promise<import("./types").AppInstallState>;
55
55
  };
56
56
  readonly Migration: {
57
+ getStatus(callback?: import("./runtime").NativeCallback<import("./types").MigrationStatus>): Promise<import("./types").MigrationStatus | {
58
+ supported: boolean;
59
+ phase: import("./types").MigrationPhase;
60
+ inProgress: boolean;
61
+ firstLaunch: boolean;
62
+ imported: boolean;
63
+ webApplied: boolean;
64
+ fromPackage: string;
65
+ importedAt: number;
66
+ lastError: string;
67
+ }>;
57
68
  setExtras(options: import("./types").MigrationExtrasOptions, callback?: import("./runtime").NativeCallback<import("./types").NativeOk>): Promise<import("./types").NativeOk>;
58
69
  continue(callback?: import("./runtime").NativeCallback<import("./types").AppInstallState>): Promise<import("./types").AppInstallState>;
59
70
  getInfo(callback?: import("./runtime").NativeCallback<import("./types").MigrationInfo>): Promise<import("./types").MigrationInfo>;
@@ -235,7 +246,7 @@ export declare const Native: {
235
246
  readonly Push: {
236
247
  getToken(callback?: import("./runtime").NativeCallback<import("./types").PushTokenResult>): Promise<import("./types").PushTokenResult>;
237
248
  };
238
- readonly sdkVersion: "1.8.0";
249
+ readonly sdkVersion: "1.8.2";
239
250
  readonly getPlatform: typeof getPlatform;
240
251
  readonly isNativePlatform: typeof isNativePlatform;
241
252
  readonly isNativeBridgeAvailable: typeof isNativeBridgeAvailable;
@@ -288,6 +299,17 @@ export declare const Native: {
288
299
  getInstallState(callback?: import("./runtime").NativeCallback<import("./types").AppInstallState>): Promise<import("./types").AppInstallState>;
289
300
  };
290
301
  readonly Migration: {
302
+ getStatus(callback?: import("./runtime").NativeCallback<import("./types").MigrationStatus>): Promise<import("./types").MigrationStatus | {
303
+ supported: boolean;
304
+ phase: import("./types").MigrationPhase;
305
+ inProgress: boolean;
306
+ firstLaunch: boolean;
307
+ imported: boolean;
308
+ webApplied: boolean;
309
+ fromPackage: string;
310
+ importedAt: number;
311
+ lastError: string;
312
+ }>;
291
313
  setExtras(options: import("./types").MigrationExtrasOptions, callback?: import("./runtime").NativeCallback<import("./types").NativeOk>): Promise<import("./types").NativeOk>;
292
314
  continue(callback?: import("./runtime").NativeCallback<import("./types").AppInstallState>): Promise<import("./types").AppInstallState>;
293
315
  getInfo(callback?: import("./runtime").NativeCallback<import("./types").MigrationInfo>): Promise<import("./types").MigrationInfo>;
package/dist/plugins.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type NativeCallback } from './runtime';
2
- import type { AppInstallState, MigrationEvent, MigrationExtrasOptions, MigrationInfo, MigrationUninstallResult, MigrationUninstallTarget, OtaInstallEvent, AppChannelCodes, AppIconState, AppIconsResult, AppInfo, AppInstalledResult, AppUpdateTriggerResult, ApkUpdateResult, CheckAppUpdateOptions, CheckAppsInstalledResult, DeviceIdentifiers, InstallDeviceId, DeviceInfo, CpuInfo, CanvasRenderInfo, WebGlInfo, EnvironmentInfo, EnvironmentDeviceInfo, PhoneStatePermissionResult, InstallAppPackageOptions, InstallAppPackageResult, InstallResourcePackageOptions, InstallResourcePackageResult, LaunchAppOptions, LaunchAppResult, LocationPermissionResult, LocationResult, LocationStatus, LocationWatchResult, LockStatus, NativeFeatureConfig, NotificationOptions, OpenInBrowserOptions, OpenInBrowserResult, OrientationInfo, SetFullscreenOptions, SetFullscreenResult, SetOrientationOptions, SetOrientationResult, PlayVideoOptions, PlayVideoResult, HttpRequestOptions, HttpRequestResult, ResourceUpdateResult, SafeAreaInsets, ScreenInfo, SetAppIconFromResourceOptions, SetAppIconOptions, SetAppIconResult, SetAppThemeOptions, SetNativeFeaturesOptions, SystemInfo, ThemeConfig, VideoPlayerStatus, WindowInfo, AdapterState, BiometricStatus, BrightnessState, CalendarEventOptions, CaptureResult, ClipboardResult, ContactResult, FlashlightState, MotionReading, NativeOk, PaymentOptions, PaymentResult, PedometerResult, PickerResult, PushTokenResult, RecorderResult, ReviewResult, ScanResult, ShareOptions, VolumeState } from './types';
2
+ import type { AppInstallState, MigrationEvent, MigrationExtrasOptions, MigrationInfo, MigrationStatus, MigrationUninstallResult, MigrationUninstallTarget, OtaInstallEvent, AppChannelCodes, AppIconState, AppIconsResult, AppInfo, AppInstalledResult, AppUpdateTriggerResult, ApkUpdateResult, CheckAppUpdateOptions, CheckAppsInstalledResult, DeviceIdentifiers, InstallDeviceId, DeviceInfo, CpuInfo, CanvasRenderInfo, WebGlInfo, EnvironmentInfo, EnvironmentDeviceInfo, PhoneStatePermissionResult, InstallAppPackageOptions, InstallAppPackageResult, InstallResourcePackageOptions, InstallResourcePackageResult, LaunchAppOptions, LaunchAppResult, LocationPermissionResult, LocationResult, LocationStatus, LocationWatchResult, LockStatus, NativeFeatureConfig, NotificationOptions, OpenInBrowserOptions, OpenInBrowserResult, OrientationInfo, SetFullscreenOptions, SetFullscreenResult, SetOrientationOptions, SetOrientationResult, PlayVideoOptions, PlayVideoResult, HttpRequestOptions, HttpRequestResult, ResourceUpdateResult, SafeAreaInsets, ScreenInfo, SetAppIconFromResourceOptions, SetAppIconOptions, SetAppIconResult, SetAppThemeOptions, SetNativeFeaturesOptions, SystemInfo, ThemeConfig, VideoPlayerStatus, WindowInfo, AdapterState, BiometricStatus, BrightnessState, CalendarEventOptions, CaptureResult, ClipboardResult, ContactResult, FlashlightState, MotionReading, NativeOk, PaymentOptions, PaymentResult, PedometerResult, PickerResult, PushTokenResult, RecorderResult, ReviewResult, ScanResult, ShareOptions, VolumeState } from './types';
3
3
  export declare const App: {
4
4
  ping(callback?: NativeCallback<{
5
5
  pong: boolean;
@@ -132,6 +132,24 @@ export declare const Ota: {
132
132
  * 设备序列号和 `setExtras` 的数据交给它,完成后请求卸载当前应用。
133
133
  */
134
134
  export declare const Migration: {
135
+ /**
136
+ * 当前是否正在迁移,以及是不是迁移后的第一次启动。用来决定要不要等待、跳过登录或引导页。
137
+ *
138
+ * 任何平台都可以直接调用,不用先判断平台:不是 Android 壳(或壳版本不带迁移)时,
139
+ * 返回 `{ supported: false, inProgress: false, firstLaunch: false, phase: 'none', ... }`。
140
+ * 其它错误照常抛出。
141
+ */
142
+ getStatus(callback?: NativeCallback<MigrationStatus>): Promise<MigrationStatus | {
143
+ supported: boolean;
144
+ phase: import("./types").MigrationPhase;
145
+ inProgress: boolean;
146
+ firstLaunch: boolean;
147
+ imported: boolean;
148
+ webApplied: boolean;
149
+ fromPackage: string;
150
+ importedAt: number;
151
+ lastError: string;
152
+ }>;
135
153
  /**
136
154
  * 迁移前补充要带走的数据。建议在登录后和每次登录态变化时调用。
137
155
  * 新应用通过 `Migration.getInfo().extras` 读取。
package/dist/plugins.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { onNativeEvent } from './events';
2
- import { invokeNative, withCallback } from './runtime';
2
+ import { callNative, invokeNative, isNativeBridgeAvailable, withCallback } from './runtime';
3
3
  import { readCanvasRenderInfo, readNavigatorCpu, readWebGlInfo } from './webview-signals';
4
4
  function toEnvironmentDevice(device, system) {
5
5
  return {
@@ -233,12 +233,76 @@ export const Ota = {
233
233
  return withCallback(invokeNative('getAppInstallState'), callback);
234
234
  },
235
235
  };
236
+ /** 等待 Bridge 注入的时间。壳里 Bridge 在页面脚本之前就在了;超时说明在普通浏览器 */
237
+ const MIGRATION_STATUS_READY_TIMEOUT_MS = 1500;
238
+ /** 不支持迁移的平台上 `Migration.getStatus()` 的结果 */
239
+ const MIGRATION_UNSUPPORTED_STATUS = {
240
+ supported: false,
241
+ phase: 'none',
242
+ inProgress: false,
243
+ firstLaunch: false,
244
+ imported: false,
245
+ webApplied: false,
246
+ fromPackage: '',
247
+ importedAt: 0,
248
+ lastError: '',
249
+ };
250
+ /**
251
+ * 短时间等 Bridge 注入。不复用 `whenReady`:它的等待是全局共享的,
252
+ * 这里的短超时会连带让别处正在等待的调用提前失败。
253
+ */
254
+ function waitForBridgeBriefly(timeoutMs) {
255
+ if (isNativeBridgeAvailable()) {
256
+ return Promise.resolve();
257
+ }
258
+ if (typeof document === 'undefined') {
259
+ return Promise.reject(new Error('Not in browser'));
260
+ }
261
+ return new Promise((resolve, reject) => {
262
+ const onReady = () => {
263
+ clearTimeout(timer);
264
+ resolve();
265
+ };
266
+ const timer = setTimeout(() => {
267
+ document.removeEventListener('nativebridgeready', onReady);
268
+ reject(new Error('Bridge timeout'));
269
+ }, timeoutMs);
270
+ document.addEventListener('nativebridgeready', onReady, { once: true });
271
+ });
272
+ }
273
+ /**
274
+ * 判断错误是不是"这里没有迁移能力":没有 Bridge(普通浏览器),
275
+ * 或壳没实现该方法(iOS / Harmony / 桌面端 / 旧版 Android 壳)。
276
+ */
277
+ function isMigrationUnsupported(error) {
278
+ const message = error instanceof Error ? error.message : String(error);
279
+ return /Unknown method|桌面壳未实现|Native bridge not available|Bridge timeout|Not in browser/i.test(message);
280
+ }
236
281
  /**
237
282
  * 换包更新的数据迁移(Android)。新安装包的包名与当前应用不同时,
238
283
  * 装好后当前应用会自动拉起新应用,把登录状态(Cookie / localStorage)、
239
284
  * 设备序列号和 `setExtras` 的数据交给它,完成后请求卸载当前应用。
240
285
  */
241
286
  export const Migration = {
287
+ /**
288
+ * 当前是否正在迁移,以及是不是迁移后的第一次启动。用来决定要不要等待、跳过登录或引导页。
289
+ *
290
+ * 任何平台都可以直接调用,不用先判断平台:不是 Android 壳(或壳版本不带迁移)时,
291
+ * 返回 `{ supported: false, inProgress: false, firstLaunch: false, phase: 'none', ... }`。
292
+ * 其它错误照常抛出。
293
+ */
294
+ getStatus(callback) {
295
+ // 普通浏览器里没有 Bridge:很快就判定为不支持,不要卡满默认的 8 秒
296
+ const promise = waitForBridgeBriefly(MIGRATION_STATUS_READY_TIMEOUT_MS)
297
+ .then(() => callNative('getMigrationStatus'))
298
+ .catch((error) => {
299
+ if (isMigrationUnsupported(error)) {
300
+ return { ...MIGRATION_UNSUPPORTED_STATUS };
301
+ }
302
+ throw error;
303
+ });
304
+ return withCallback(promise, callback);
305
+ },
242
306
  /**
243
307
  * 迁移前补充要带走的数据。建议在登录后和每次登录态变化时调用。
244
308
  * 新应用通过 `Migration.getInfo().extras` 读取。
package/dist/types.d.ts CHANGED
@@ -535,7 +535,7 @@ export interface InstallAppPackageResult {
535
535
  * `Ota.onInstallEvent` 的阶段。顺序一般为:
536
536
  * download-start → download-progress… → download-complete → install-start →
537
537
  * install-prompt(等用户在系统框里确认)→ install-success。
538
- * 同包升级装完后系统会替换并重启本应用,收不到 install-success。
538
+ * 同包升级走系统安装器(ACTION_VIEW),不会发出 install-success,装完后需用户手动打开应用。
539
539
  */
540
540
  export type OtaInstallStage = 'download-start' | 'download-progress' | 'download-complete' | 'download-failed' | 'install-start' | 'install-prompt' | 'install-success' | 'install-canceled' | 'install-failed';
541
541
  export interface OtaInstallEvent {
@@ -601,6 +601,35 @@ export interface MigrationInfo {
601
601
  extras: Record<string, unknown>;
602
602
  lastError: string;
603
603
  }
604
+ /**
605
+ * 新应用的迁移阶段:
606
+ * - `none`:没有发生过迁移(包括不支持迁移的平台)
607
+ * - `importing`:正在向旧应用取数据。通常在页面起来之前就结束,只有预热页面先跑起来时才读得到
608
+ * - `applying`:数据已取回,localStorage 还在等页面确认写入
609
+ * - `completed`:数据已全部写好
610
+ * - `failed`:这个应用上没有迁移成功过,且最近一次尝试失败(原因见 `lastError`)
611
+ */
612
+ export type MigrationPhase = 'none' | 'importing' | 'applying' | 'completed' | 'failed';
613
+ /** `Migration.getStatus()` 的结果:当前是否在迁移,以及是不是迁移后的第一次启动 */
614
+ export interface MigrationStatus {
615
+ /** 当前平台是否支持迁移。false 表示非 Android 壳,其余字段都是"没有迁移"的默认值 */
616
+ supported: boolean;
617
+ phase: MigrationPhase;
618
+ /** 正在迁移:`phase` 为 `importing` 或 `applying`。迁移有时限,不会永远为 true */
619
+ inProgress: boolean;
620
+ /**
621
+ * 是否是迁移之后的第一次启动:迁移成功,且就在取数据的那个进程里。
622
+ * 进程被系统回收再启动后变回 false;同一进程里页面重新加载仍是 true。
623
+ */
624
+ firstLaunch: boolean;
625
+ /** 是否已从旧应用取到过数据(同 `Migration.getInfo().imported`) */
626
+ imported: boolean;
627
+ /** localStorage 是否已写入页面 */
628
+ webApplied: boolean;
629
+ fromPackage: string;
630
+ importedAt: number;
631
+ lastError: string;
632
+ }
604
633
  export interface MigrationExtrasOptions {
605
634
  /** 随迁移带给新应用的数据,如内存里的 token,读取方式:`Migration.getInfo().extras` */
606
635
  extras?: Record<string, unknown>;
package/dist/version.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** npm 包名(与 package.json name 保持一致) */
2
2
  export declare const PACKAGE_NAME = "ota-native-bridge";
3
3
  /** OTA Native Bridge SDK 版本(与 package.json version 保持一致) */
4
- export declare const SDK_VERSION = "1.8.0";
4
+ export declare const SDK_VERSION = "1.8.2";
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  /** npm 包名(与 package.json name 保持一致) */
2
2
  export const PACKAGE_NAME = 'ota-native-bridge';
3
3
  /** OTA Native Bridge SDK 版本(与 package.json version 保持一致) */
4
- export const SDK_VERSION = '1.8.0';
4
+ export const SDK_VERSION = '1.8.2';
package/docs/USAGE.md CHANGED
@@ -84,6 +84,8 @@ if (!Native.isNativePlatform()) {
84
84
  | 生物识别 | `Biometric.authenticate()` |
85
85
  | 支付 / 评分 | `Payment.pay({ url })` / `Store.requestReview()` |
86
86
  | 推送 token | `Push.getToken()` |
87
+ | 安装进度 / 换包迁移(Android,1.8.0+) | `Ota.onInstallEvent(fn)` / `Migration.onEvent(fn)`,见 §5.3.1 |
88
+ | 新应用是否在迁移 / 迁移后首启(1.8.1+) | `Migration.getStatus()`,各平台可直接调用,见 §5.3.1 |
87
89
 
88
90
  各插件也可通过 `Native.App`、`Native.Ota` 访问,与直接 `import { App }` 相同。
89
91
 
@@ -754,6 +756,49 @@ Ota.checkApkUpdate().then(console.log);
754
756
  | 前端自定义数据 | `Migration.setExtras({ extras })`,新应用 `Migration.getInfo().extras` 读取 |
755
757
  | sessionStorage / IndexedDB | **不迁移**。需要的内容放进 `extras` |
756
758
 
759
+ **判断新应用是否在迁移(包版本 1.8.1+)**
760
+
761
+ 新应用启动时,用 `Migration.getStatus()` 判断"现在是不是正在迁移"和"是不是迁移后的第一次启动",再决定要不要等待、跳过登录页或引导页。
762
+
763
+ ```typescript
764
+ import { Migration } from 'ota-native-bridge';
765
+
766
+ // 迁移还没做完就等一会儿,再启动业务。迁移有时限,不会一直等下去
767
+ function waitMigrationDone() {
768
+ return Migration.getStatus().then((s) => {
769
+ if (!s.inProgress) return s;
770
+ return new Promise((r) => setTimeout(r, 300)).then(waitMigrationDone);
771
+ });
772
+ }
773
+
774
+ waitMigrationDone().then((s) => {
775
+ if (s.firstLaunch) {
776
+ // 迁移后的第一次启动:登录态、设备序列号都是从旧应用带来的,不要当成新用户
777
+ Migration.getInfo().then((info) => restoreSession(info.extras));
778
+ }
779
+ startApp();
780
+ });
781
+ ```
782
+
783
+ 返回值:
784
+
785
+ | 字段 | 说明 |
786
+ |------|------|
787
+ | `phase` | `none` 没有发生过迁移;`importing` 正在向旧应用取数据;`applying` 数据已取回,localStorage 等页面确认写入;`completed` 全部写好;`failed` 这个应用上没迁移成功过,且最近一次尝试失败 |
788
+ | `inProgress` | **正在迁移**:`phase` 是 `importing` 或 `applying` |
789
+ | `firstLaunch` | 迁移后的第一次启动:迁移成功,且就在取数据的那个进程里。进程被系统回收再启动后变回 `false`;同一进程里页面重新加载仍是 `true` |
790
+ | `imported` / `webApplied` / `fromPackage` / `importedAt` / `lastError` | 与 `Migration.getInfo()` 同名字段一致 |
791
+ | `supported` | 当前平台是否支持迁移。`false` 时其余字段都是"没有迁移"的默认值 |
792
+
793
+ 使用时注意:
794
+
795
+ - **任何平台都能直接调用**,不用先判断平台。iOS / Harmony / 桌面端、旧版 Android 壳、普通浏览器里不会报错,返回 `supported: false`、`inProgress: false`、`firstLaunch: false`。其它类型的错误照常抛出。
796
+ - 迁移的大部分发生在页面起来之前(后台取数据,页面还没出现)。所以页面启动时多半读到的是 `completed` 加 `firstLaunch: true`。`importing` 只在预热页面先于迁移跑起来时才读得到;`applying` 到页面确认写入 localStorage 为止。
797
+ - Cookie 和设备序列号在页面起来前就已写好;localStorage 由壳在页面文档开始时写入,页面脚本读到的已经是旧值。`inProgress` 为 `true` 时,不要用新生成的设备序列号发请求。
798
+ - 迁移有时限,不会让页面一直卡在"迁移中":取数据超过 30 秒、写入确认超过 60 秒都不再算迁移中。超时后 `phase` 变成 `completed`,`webApplied` 仍为 `false` 表示 localStorage 没写进去(例如入口页站点和旧应用不同)。
799
+ - `firstLaunch` 只能表示"这个进程"。业务上要"只做一次"的事情(欢迎提示、一次性数据导入),请自己存一个标记。
800
+ - 旧应用还没卸载(`Migration.getInfo().uninstallPending`)不算迁移中。
801
+
757
802
  **事件**
758
803
 
759
804
  ```typescript
@@ -779,15 +824,19 @@ const offMigration = Migration.onEvent((e) => {
779
824
 
780
825
  事件是 DOM 事件 `nativebridgeevent`(`detail = { name, payload }`),`Ota.onInstallEvent` / `Migration.onEvent` / `Native.on(name, fn)` 都是对它的封装。**页面还没加载好时发出的事件不补发**,页面启动时请用 `Ota.getInstallState()`、`Migration.getInfo()` 读当前状态。
781
826
 
827
+ `Ota.onInstallEvent` 的 `stage` 一般顺序为:`download-start` → `download-progress`(多次)→ `download-complete` → `install-start` → `install-prompt`(等用户在系统框里确认)→ `install-success`。失败或取消时为 `download-failed` / `install-canceled` / `install-failed`。同包升级走系统安装器(`ACTION_VIEW`),壳拿不到安装结果,不会发出 `install-success`,装完后也不会自动打开应用,需要用户手动打开。`install-prompt` 的 `foreground` 为 `false` 时,壳会改用通知提示用户确认。
828
+
782
829
  **接口**
783
830
 
784
831
  | 方法 | 说明 |
785
832
  |------|------|
786
833
  | `Ota.onInstallEvent(fn)` | 订阅下载与安装事件,返回取消订阅函数 |
834
+ | `Native.on(name, fn)` | 订阅原始事件,`name` 为 `'ota.install'` 或 `'migration'`,返回取消订阅函数 |
787
835
  | `Ota.getInstallState()` | 换包安装的阶段:`{ phase, targetPackage, targetVersion, handoffAttempts, startedAt, error }`,`phase` 为 `none / installing / installed / handoff / done / failed` |
788
836
  | `Ota.installAppPackage(options)` | 结果新增 `targetPackage`、`crossPackage` |
789
837
  | `Migration.setExtras({ extras?, cookieUrls? })` | 迁移前补充要带走的数据。建议登录后和登录态变化时调用 |
790
838
  | `Migration.continue()` | 新应用已装好但没自动打开时,由用户点按钮重试交接 |
839
+ | `Migration.getStatus()` | 新应用里判断是否正在迁移、是否迁移后首次启动:`{ supported, phase, inProgress, firstLaunch, imported, webApplied, fromPackage, importedAt, lastError }`(包版本 **1.8.1+**,各平台都可调用) |
791
840
  | `Migration.getInfo()` | 新应用里读迁移结果:`{ imported, fromPackage, importedAt, deviceIdAdopted, webApplied, truncated, uninstallPending, extras, lastError }` |
792
841
  | `Migration.requestUninstall('self' \| 'source')` | `self` 卸载当前应用(迁移完成后),`source` 在新应用里卸载旧应用。用户在系统框里取消后可再次发起 |
793
842
  | `Migration.onEvent(fn)` | 订阅迁移事件 |
@@ -796,12 +845,12 @@ const offMigration = Migration.onEvent((e) => {
796
845
 
797
846
  **限制**
798
847
 
799
- - 仅 **Android** 壳支持,iOS / Harmony / 桌面端调用 `Migration.*` 会报 `Unknown method`。
848
+ - 仅 **Android** 壳支持,iOS / Harmony / 桌面端调用 `Migration.*` 会报 `Unknown method`。唯一的例外是 `Migration.getStatus()`:它在这些平台上直接返回"没有迁移",不报错。
800
849
  - 安装和卸载的**系统确认框一定会弹**,Android 不允许普通应用静默安装或卸载。
801
850
  - Android 10 起后台应用不能直接拉起别的应用。装完时旧应用不在前台,会改发一条通知,点通知或回到旧应用时继续交接(最多重试 5 次),也可以由前端 `Migration.continue()` 手动触发。
802
851
  - 谷歌商店渠道(`canSideloadApkUpdate=false`)不走应用内安装,直接跳商店,没有迁移。
803
852
  - 新旧应用能互信靠的是同签名,或者两边打包进去的同一把平台密钥(HMAC)。用不同签名、也没有平台配置的包不会迁移。
804
- - 新应用会先让预热页面起来,再把迁移来的 localStorage 写入并重新加载入口页。服务端可能短暂见到一次新设备序列号,请求以 `Device.getInstallDeviceId()` 为准时请在 `Migration.getInfo().imported === true` 后再读。
853
+ - 新应用会先让预热页面起来,再把迁移来的 localStorage 写入并重新加载入口页。服务端可能短暂见到一次新设备序列号,请求以 `Device.getInstallDeviceId()` 为准时请等 `Migration.getStatus().inProgress` 变为 `false`(或 `Migration.getInfo().imported === true`)后再读。
805
854
 
806
855
  ### 5.4 Client API 请求参数加密(必选)
807
856
 
@@ -1667,7 +1716,7 @@ Http.request({
1667
1716
  | `Ota.installResourcePackage(options)` | 安装资源包 | `{ success, needsRestart, restarted, message }` |
1668
1717
  | `Ota.installAppPackage(options)` | 安装 APK 等 | `{ success, message, needsInstallPermission?, targetPackage?, crossPackage? }` |
1669
1718
  | `Ota.onInstallEvent(fn)` / `Ota.getInstallState()` | 下载与安装进度、换包安装阶段(Android) | 见 §5.3.1 |
1670
- | `Migration.setExtras` / `continue` / `getInfo` / `requestUninstall` / `onEvent` | 换包数据迁移(Android) | 见 §5.3.1 |
1719
+ | `Migration.setExtras` / `continue` / `getStatus` / `getInfo` / `requestUninstall` / `onEvent` | 换包数据迁移(Android) | 见 §5.3.1 |
1671
1720
  | `Ota.downloadAndInstallApk(url)` | 等同 `installAppPackage({ url })` | 同上 |
1672
1721
  | `Ota.checkResourceUpdate` / `Ota.checkApkUpdate` | 按 URL 检测 | `{ hasUpdate, version?/versionName?, url? }` |
1673
1722
  | `Ota.applyResourceUpdate` | 安装资源包不重启 | `{ success: true, needsRestart: true, restarted: false }` |
@@ -1933,7 +1982,27 @@ A:先看 `Icon.get()` 的 `supportsCustomFromResource`。iOS 和 HarmonyOS 会
1933
1982
 
1934
1983
  ---
1935
1984
 
1936
- ## 11. 相关文档
1985
+ ## 11. 版本更新记录
1986
+
1987
+ 以下只列影响接入的变化,完整类型见 `dist/types.d.ts`。
1988
+
1989
+ **1.8.1**
1990
+
1991
+ - 新增 `Migration.getStatus()`:新应用判断自己是否正在迁移、是否是迁移后的第一次启动,各平台都能直接调用。详见 §5.3.1。需要同时升级 Android 壳;旧壳上返回"不支持"。
1992
+
1993
+ **1.8.0**
1994
+
1995
+ - 新增换包更新与数据迁移(Android):`Migration` 插件,以及 `Ota.onInstallEvent`、`Ota.getInstallState`、`Native.on`、`onNativeEvent`。详见 §5.3.1。
1996
+ - `Ota.installAppPackage` 的结果新增 `targetPackage`、`crossPackage`。
1997
+ - `Device.getInstallDeviceId()` 在换包更新后沿用旧应用的设备序列号(Android)。
1998
+
1999
+ **1.7.0**
2000
+
2001
+ - 新增 `Device.setOrientation` / `Device.setFullscreen`,见各 API 标注的 `1.7.0+`。
2002
+
2003
+ ---
2004
+
2005
+ ## 12. 相关文档
1937
2006
 
1938
2007
  - [README.md](../README.md) — 包结构与快速上手
1939
2008
  - 仓库 `AppUpgradeOTASystem` 根目录 `README.md` — OTA 系统整体说明
@@ -91,6 +91,22 @@
91
91
  return readyPromise;
92
92
  }
93
93
 
94
+ function waitBriefly(maxMs) {
95
+ if (getNativeMessenger()) return Promise.resolve();
96
+ if (typeof document === 'undefined') return Promise.reject(new Error('Not in browser'));
97
+ return new Promise(function (resolve, reject) {
98
+ var timer = setTimeout(function () {
99
+ document.removeEventListener('nativebridgeready', onReady);
100
+ reject(new Error('Bridge timeout'));
101
+ }, maxMs);
102
+ function onReady() {
103
+ clearTimeout(timer);
104
+ resolve();
105
+ }
106
+ document.addEventListener('nativebridgeready', onReady, { once: true });
107
+ });
108
+ }
109
+
94
110
  function invokeNative(method, params) {
95
111
  return waitForBridge().then(function () { return callNative(method, params); });
96
112
  }
@@ -219,6 +235,23 @@
219
235
  },
220
236
  'continue': function (cb) { return withCallback(invokeNative('continueAppMigration'), cb); },
221
237
  getInfo: function (cb) { return withCallback(invokeNative('getMigrationInfo'), cb); },
238
+ getStatus: function (cb) {
239
+ // 普通浏览器里没有 Bridge:很快判定为不支持,不要卡满默认的 8 秒
240
+ // 不复用 waitForBridge:它的等待是全局共享的,短超时会让别处正在等待的调用提前失败
241
+ var promise = waitBriefly(1500)
242
+ .then(function () { return callNative('getMigrationStatus'); })
243
+ .catch(function (error) {
244
+ var message = error instanceof Error ? error.message : String(error);
245
+ if (/Unknown method|桌面壳未实现|Native bridge not available|Bridge timeout|Not in browser/i.test(message)) {
246
+ return {
247
+ supported: false, phase: 'none', inProgress: false, firstLaunch: false,
248
+ imported: false, webApplied: false, fromPackage: '', importedAt: 0, lastError: ''
249
+ };
250
+ }
251
+ throw error;
252
+ });
253
+ return withCallback(promise, cb);
254
+ },
222
255
  requestUninstall: function (target, cb) { return withCallback(invokeNative('requestUninstall', { target: target || 'self' }), cb); },
223
256
  onEvent: function (handler) { return onNativeEvent('migration', handler); }
224
257
  };
@@ -408,7 +441,7 @@
408
441
  };
409
442
 
410
443
  global.Native = {
411
- sdkVersion: '1.8.0',
444
+ sdkVersion: '1.8.2',
412
445
  getPlatform: getPlatform,
413
446
  isNativePlatform: isNativePlatform,
414
447
  isNativeBridgeAvailable: function () { return !!getNativeMessenger(); },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ota-native-bridge",
3
- "version": "1.8.0",
3
+ "version": "1.8.2",
4
4
  "description": "App OTA WebView 壳应用跨平台 Native Bridge TypeScript SDK(Android / iOS / HarmonyOS)",
5
5
  "keywords": [
6
6
  "ota",