create-expo-updates-server 0.3.0 → 0.6.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.
Files changed (191) hide show
  1. package/README.md +4 -2
  2. package/dist/template/Dockerfile +4 -6
  3. package/dist/template/README.md +5 -10
  4. package/dist/template/app/api/admin/device-favorites/route.test.ts +125 -0
  5. package/dist/template/app/api/admin/device-favorites/route.ts +91 -0
  6. package/dist/template/app/api/admin/distribution-history/restore/route.ts +39 -0
  7. package/dist/template/app/api/admin/distribution-history/route.test.ts +55 -0
  8. package/dist/template/app/api/admin/distribution-history/route.ts +24 -0
  9. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +2 -1
  10. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +2 -1
  11. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +2 -1
  12. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +2 -1
  13. package/dist/template/app/api/admin/updates/route.test.ts +21 -0
  14. package/dist/template/app/api/admin/updates/route.ts +12 -1
  15. package/dist/template/app/globals.css +65 -68
  16. package/dist/template/app/login/page.tsx +66 -42
  17. package/dist/template/app/updates/[encodedKey]/page.tsx +382 -248
  18. package/dist/template/app/updates/devices/page.tsx +187 -145
  19. package/dist/template/app/updates/embedded/page.tsx +80 -34
  20. package/dist/template/app/updates/emergency-redirects/page.tsx +138 -71
  21. package/dist/template/app/updates/layout.tsx +2 -1
  22. package/dist/template/app/updates/page.tsx +385 -274
  23. package/dist/template/app/updates/releases.test.tsx +156 -0
  24. package/dist/template/components/admin/admin-role.ts +5 -0
  25. package/dist/template/components/admin/admin-shell.tsx +166 -95
  26. package/dist/template/components/admin/confirm-action.tsx +123 -0
  27. package/dist/template/components/admin/language-switcher.tsx +27 -16
  28. package/dist/template/components/admin/release-badges.test.tsx +50 -0
  29. package/dist/template/components/admin/release-badges.tsx +101 -0
  30. package/dist/template/components/ui/alert.tsx +10 -3
  31. package/dist/template/components/ui/avatar.tsx +108 -0
  32. package/dist/template/components/ui/badge.tsx +2 -2
  33. package/dist/template/components/ui/breadcrumb.tsx +108 -0
  34. package/dist/template/components/ui/button.tsx +5 -5
  35. package/dist/template/components/ui/card.tsx +2 -2
  36. package/dist/template/components/ui/chart.tsx +1 -1
  37. package/dist/template/components/ui/collapsible.tsx +7 -0
  38. package/dist/template/components/ui/dialog.tsx +13 -4
  39. package/dist/template/components/ui/empty.tsx +103 -0
  40. package/dist/template/components/ui/field.tsx +248 -0
  41. package/dist/template/components/ui/input-group.tsx +170 -0
  42. package/dist/template/components/ui/input.tsx +1 -1
  43. package/dist/template/components/ui/native-select.tsx +1 -1
  44. package/dist/template/components/ui/radio-group.tsx +41 -0
  45. package/dist/template/components/ui/sheet.tsx +6 -2
  46. package/dist/template/components/ui/sidebar.tsx +62 -17
  47. package/dist/template/components/ui/status-tones.ts +15 -0
  48. package/dist/template/components/ui/table.tsx +1 -1
  49. package/dist/template/components/ui/textarea.tsx +1 -1
  50. package/dist/template/docs/admin-ui.md +22 -24
  51. package/dist/template/docs/device-targeting.md +6 -12
  52. package/dist/template/docs/doctor.md +2 -2
  53. package/dist/template/docs/expo-app-setup.md +9 -27
  54. package/dist/template/docs/getting-started.md +3 -4
  55. package/dist/template/docs/getting-started.ru.md +11 -544
  56. package/dist/template/docs/index.md +1 -1
  57. package/dist/template/docs/installation-telemetry.md +6 -12
  58. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +5 -0
  59. package/dist/template/docs/migrations/2026-11-25-device-favorites.sql +53 -0
  60. package/dist/template/docs/migrations/2026-11-25-download-on-postpone.sql +5 -0
  61. package/dist/template/docs/migrations/2026-11-25-public-distribution-history.sql +283 -0
  62. package/dist/template/docs/migrations/schema.sql +349 -0
  63. package/dist/template/docs/npm-installer.md +3 -3
  64. package/dist/template/docs/operations-guide.md +9 -7
  65. package/dist/template/docs/ota-client-lifecycle.md +30 -68
  66. package/dist/template/docs/ota-emergency-recovery.md +34 -57
  67. package/dist/template/docs/ota-update-policy.md +9 -20
  68. package/dist/template/docs/ru/admin-ui.md +33 -0
  69. package/dist/template/docs/ru/device-targeting.md +59 -0
  70. package/dist/template/docs/ru/doctor.md +98 -0
  71. package/dist/template/docs/ru/expo-app-setup.md +497 -0
  72. package/dist/template/docs/ru/getting-started.md +391 -0
  73. package/dist/template/docs/ru/index.md +50 -0
  74. package/dist/template/docs/ru/installation-telemetry.md +125 -0
  75. package/dist/template/docs/ru/npm-installer.md +71 -0
  76. package/dist/template/docs/ru/operations-guide.md +322 -0
  77. package/dist/template/docs/ru/ota-client-lifecycle.md +162 -0
  78. package/dist/template/docs/ru/ota-emergency-recovery.md +108 -0
  79. package/dist/template/docs/ru/ota-update-policy.md +69 -0
  80. package/dist/template/docs/ru/publishing-npm-installer.md +49 -0
  81. package/dist/template/docs/ru/supabase-setup.md +120 -0
  82. package/dist/template/docs/uk/admin-ui.md +33 -0
  83. package/dist/template/docs/uk/device-targeting.md +59 -0
  84. package/dist/template/docs/uk/doctor.md +98 -0
  85. package/dist/template/docs/uk/expo-app-setup.md +497 -0
  86. package/dist/template/docs/uk/getting-started.md +391 -0
  87. package/dist/template/docs/uk/index.md +50 -0
  88. package/dist/template/docs/uk/installation-telemetry.md +125 -0
  89. package/dist/template/docs/uk/npm-installer.md +71 -0
  90. package/dist/template/docs/uk/operations-guide.md +322 -0
  91. package/dist/template/docs/uk/ota-client-lifecycle.md +162 -0
  92. package/dist/template/docs/uk/ota-emergency-recovery.md +108 -0
  93. package/dist/template/docs/uk/ota-update-policy.md +69 -0
  94. package/dist/template/docs/uk/publishing-npm-installer.md +49 -0
  95. package/dist/template/docs/uk/supabase-setup.md +120 -0
  96. package/dist/template/lib/audience-ids.ts +4 -0
  97. package/dist/template/package-lock.json +46 -0
  98. package/dist/template/package.json +4 -1
  99. package/dist/template/scripts/configure-expo-app.mjs +3 -3
  100. package/dist/template/scripts/create-access-token.mjs +1 -1
  101. package/dist/template/scripts/lib/doctor.mjs +10 -7
  102. package/dist/template/scripts/lib/doctor.test.mjs +7 -5
  103. package/dist/template/scripts/lib/embedded-update-registrar.test.ts +22 -7
  104. package/dist/template/scripts/lib/expo-app-configurator.mjs +25 -22
  105. package/dist/template/scripts/lib/expo-app-configurator.test.ts +37 -2
  106. package/dist/template/scripts/lib/ota-client-configurator.mjs +152 -55
  107. package/dist/template/scripts/lib/ota-client-configurator.test.ts +60 -20
  108. package/dist/template/scripts/lib/ota-client-package.mjs +25 -0
  109. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +90 -32
  110. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +49 -6
  111. package/dist/template/scripts/tests/device-analytics-migrations.mjs +12 -1
  112. package/dist/template/scripts/tests/device-targeting-activation.mjs +2 -3
  113. package/dist/template/scripts/tests/e2e/client-lifecycle.mjs +161 -0
  114. package/dist/template/scripts/tests/e2e/client-lifecycle.scenario.jsx +465 -0
  115. package/dist/template/scripts/tests/e2e/client-vitest.mts +18 -0
  116. package/dist/template/scripts/tests/e2e/console.mjs +86 -0
  117. package/dist/template/scripts/tests/e2e/delivery.mjs +296 -0
  118. package/dist/template/scripts/tests/e2e/device-favorites.mjs +309 -0
  119. package/dist/template/scripts/tests/e2e/installations.mjs +132 -0
  120. package/dist/template/scripts/tests/e2e/policy.mjs +253 -0
  121. package/dist/template/scripts/tests/e2e/registrar-token.mjs +59 -0
  122. package/dist/template/scripts/tests/e2e/release-matrix.mjs +307 -0
  123. package/dist/template/scripts/tests/e2e/releases.mjs +162 -0
  124. package/dist/template/scripts/tests/e2e/run.mjs +224 -0
  125. package/dist/template/scripts/tests/manifest-identity.sql +7 -5
  126. package/dist/template/scripts/tests/public-distribution-history.mjs +102 -0
  127. package/dist/template/src/client/admin-api.ts +45 -10
  128. package/dist/template/src/client/admin-types.ts +35 -1
  129. package/dist/template/src/client/devices/analytics.tsx +169 -219
  130. package/dist/template/src/client/devices/cohorts.tsx +181 -0
  131. package/dist/template/src/client/devices/device-name.tsx +37 -21
  132. package/dist/template/src/client/devices/favorite-targets.tsx +381 -0
  133. package/dist/template/src/client/devices/registry.tsx +265 -233
  134. package/dist/template/src/client/devices/use-devices-report.test.tsx +98 -0
  135. package/dist/template/src/client/devices/use-devices-report.ts +53 -82
  136. package/dist/template/src/client/devices/version-adoption-chart.tsx +48 -38
  137. package/dist/template/src/client/distribution-control.tsx +98 -53
  138. package/dist/template/src/client/distribution-history.tsx +353 -0
  139. package/dist/template/src/client/guard-action-catalog.tsx +183 -0
  140. package/dist/template/src/client/guard-action-combobox.test.ts +16 -22
  141. package/dist/template/src/client/guard-action-combobox.tsx +134 -234
  142. package/dist/template/src/client/guard-action-options.ts +4 -6
  143. package/dist/template/src/client/i18n/en.json +335 -2
  144. package/dist/template/src/client/i18n/language-switching.test.tsx +233 -0
  145. package/dist/template/src/client/i18n/messages.test.ts +102 -19
  146. package/dist/template/src/client/i18n/messages.ts +31 -16
  147. package/dist/template/src/client/i18n/provider.tsx +6 -3
  148. package/dist/template/src/client/i18n/ru.json +619 -0
  149. package/dist/template/src/client/i18n/uk.json +619 -0
  150. package/dist/template/src/client/i18n/use-formatters.ts +5 -0
  151. package/dist/template/src/client/logout-button.tsx +3 -3
  152. package/dist/template/src/client/policy-draft.ts +138 -0
  153. package/dist/template/src/client/update-audience-editor.tsx +597 -199
  154. package/dist/template/src/client/update-policy-editor.test.ts +101 -29
  155. package/dist/template/src/client/update-policy-editor.tsx +466 -307
  156. package/dist/template/src/client/use-filtered-results.ts +55 -0
  157. package/dist/template/src/server/controllers/manifest.test.ts +23 -3
  158. package/dist/template/src/server/controllers/manifest.ts +15 -1
  159. package/dist/template/src/server/devices/audience.ts +9 -5
  160. package/dist/template/src/server/lib/admin-audience-activation.test.ts +37 -90
  161. package/dist/template/src/server/lib/admin-release-history.test.ts +138 -0
  162. package/dist/template/src/server/lib/admin-updates.ts +160 -534
  163. package/dist/template/src/server/lib/distribution-history.ts +97 -0
  164. package/dist/template/src/server/lib/supabase.js +24 -0
  165. package/dist/template/src/server/lib/supabase.test.ts +38 -1
  166. package/dist/template/src/server/lib/update-policy.test.ts +20 -0
  167. package/dist/template/src/server/lib/update-policy.ts +23 -10
  168. package/dist/template/src/server/manifest/manifest-repository.ts +11 -3
  169. package/dist/template/src/server/manifest/manifest-values.test.ts +2 -0
  170. package/dist/template/src/server/manifest/manifest-values.ts +21 -13
  171. package/dist/template/templates/expo-app/scripts/ota-publish/api/database-client.mjs +7 -30
  172. package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +2 -1
  173. package/dist/template/tsconfig.json +2 -2
  174. package/dist/template-manifest.json +571 -271
  175. package/package.json +1 -1
  176. package/dist/template/scripts/lib/device-identity.test.ts +0 -29
  177. package/dist/template/scripts/lib/ota-client.test.ts +0 -55
  178. package/dist/template/scripts/lib/ota-update-controller.test.ts +0 -232
  179. package/dist/template/scripts/lib/ota-updates-ui.test.tsx +0 -154
  180. package/dist/template/scripts/tests/ota-client-types.mjs +0 -69
  181. package/dist/template/templates/expo-app/ota-client/README.md +0 -73
  182. package/dist/template/templates/expo-app/ota-client/controller.ts +0 -107
  183. package/dist/template/templates/expo-app/ota-client/device-identity.ts +0 -48
  184. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +0 -61
  185. package/dist/template/templates/expo-app/ota-client/index.ts +0 -16
  186. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.ts +0 -97
  187. package/dist/template/templates/expo-app/ota-client/model/update-controller.ts +0 -293
  188. package/dist/template/templates/expo-app/ota-client/runtime.ts +0 -153
  189. package/dist/template/templates/expo-app/ota-client/types.ts +0 -85
  190. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.tsx +0 -25
  191. package/dist/template/templates/expo-app/ota-client/ui/ota-updates.tsx +0 -196
@@ -1,107 +0,0 @@
1
- interface Heartbeat {
2
- installationId: string;
3
- eventId: string;
4
- sequence: number;
5
- observedAt: string;
6
- [key: string]: unknown;
7
- }
8
- interface InstallationState {
9
- installationId: string;
10
- sequence: number;
11
- pending: Heartbeat | null;
12
- }
13
- interface InstallationDependencies {
14
- read(): Promise<string | null>;
15
- write(value: string): Promise<void>;
16
- uuid(): string;
17
- snapshot(): Record<string, unknown>;
18
- send(event: Heartbeat): Promise<void>;
19
- setIdentity(id: string): Promise<void>;
20
- now?(): string;
21
- }
22
-
23
- // Pure controller: storage and network are injected so ordering is testable.
24
- // One persisted envelope owns identity, sequence and the bounded outbox.
25
- export function createInstallationClient({
26
- read,
27
- write,
28
- uuid,
29
- snapshot,
30
- send,
31
- setIdentity,
32
- now = () => new Date().toISOString(),
33
- }: InstallationDependencies) {
34
- let state: InstallationState | undefined;
35
- let queue: Promise<unknown> = Promise.resolve();
36
- let flight: Promise<void> | undefined;
37
- const serial = <T>(work: () => Promise<T>): Promise<T> => {
38
- const result = queue.then(work);
39
- queue = result.catch(() => undefined);
40
- return result;
41
- };
42
- async function initialize() {
43
- if (state) return state;
44
- const stored = await read();
45
- if (stored) {
46
- const parsed = JSON.parse(stored);
47
- if (
48
- !parsed.installationId ||
49
- !Number.isSafeInteger(parsed.sequence) ||
50
- parsed.sequence < 0
51
- )
52
- throw new Error("Invalid OTA client state");
53
- state = parsed;
54
- } else {
55
- const next = { installationId: uuid(), sequence: 0, pending: null };
56
- await write(JSON.stringify(next));
57
- state = next;
58
- }
59
- return state!;
60
- }
61
- const ready = () =>
62
- serial(async () => {
63
- const current = await initialize();
64
- await setIdentity(current.installationId);
65
- return current.installationId;
66
- });
67
- async function flush() {
68
- if (flight) return flight;
69
- flight = (async () => {
70
- const pending = await serial(async () => (await initialize()).pending);
71
- if (!pending) return;
72
- await send(pending);
73
- await serial(async () => {
74
- if (state?.pending?.eventId !== pending.eventId) return;
75
- const next = { ...state, pending: null };
76
- await write(JSON.stringify(next));
77
- state = next;
78
- });
79
- })();
80
- try {
81
- await flight;
82
- } finally {
83
- flight = undefined;
84
- }
85
- }
86
- async function observe() {
87
- await serial(async () => {
88
- const current = await initialize();
89
- await setIdentity(current.installationId);
90
- if (current.sequence >= Number.MAX_SAFE_INTEGER)
91
- throw new Error("OTA sequence exhausted");
92
- const sequence = current.sequence + 1;
93
- const pending = {
94
- ...snapshot(),
95
- installationId: current.installationId,
96
- eventId: uuid(),
97
- sequence,
98
- observedAt: now(),
99
- };
100
- const next = { ...current, sequence, pending };
101
- await write(JSON.stringify(next));
102
- state = next;
103
- });
104
- await flush();
105
- }
106
- return { ready, observe, flush };
107
- }
@@ -1,48 +0,0 @@
1
- interface DeviceIdentityDependencies {
2
- platform: string;
3
- scope: string;
4
- androidId(): string | null;
5
- readSecure(key: string): Promise<string | null>;
6
- writeSecure(key: string, value: string): Promise<void>;
7
- uuid(): string;
8
- digest(value: string): Promise<string>;
9
- }
10
-
11
- // Dependencies are injected so reinstall behaviour can be tested without native modules.
12
- export function createDeviceIdentity({
13
- platform,
14
- scope,
15
- androidId,
16
- readSecure,
17
- writeSecure,
18
- uuid,
19
- digest,
20
- }: DeviceIdentityDependencies) {
21
- let flight: Promise<string | null> | undefined;
22
- async function resolve() {
23
- const namespace = await digest(`ota-device-v1:${scope}`);
24
- let seed;
25
- if (platform === "android") {
26
- seed = androidId();
27
- if (!seed) throw new Error("Android ID unavailable");
28
- } else if (platform === "ios") {
29
- const key = `ota-device-v1.${namespace}`;
30
- seed = await readSecure(key);
31
- if (!seed) {
32
- seed = uuid();
33
- await writeSecure(key, seed);
34
- }
35
- } else {
36
- return null;
37
- }
38
- return digest(`${namespace}:${platform}:${seed}`);
39
- }
40
- return () => {
41
- if (!flight)
42
- flight = resolve().catch((error) => {
43
- flight = undefined;
44
- throw error;
45
- });
46
- return flight;
47
- };
48
- }
@@ -1,61 +0,0 @@
1
- # Update lifecycle
2
-
3
- `configure-app` generates a formatted TypeScript client and renders `<OtaUpdates />`
4
- beside navigation in the root layout/App. The component calls `useOtaUpdates`
5
- internally; it does not wrap the app or provide React context. Mount it once in a
6
- persistent root, including loading/early-return paths.
7
-
8
- By default it checks automatically and shows **Download / Later** for an ordinary
9
- update, then **Restart / Later** when downloaded. `autoUpdate={false}` disables
10
- automatic downloading, not the prompt. A dismissed candidate stays hidden until the
11
- component remounts, a different candidate arrives, or its download state changes.
12
- Background updates remain silent; required updates cannot be dismissed.
13
-
14
- The lower-level `useOtaUpdates()` is still available for optional custom screens.
15
- It shares state/actions but defaults to no automation and renders no UI. Configure
16
- automation in one root; multiple configured consumers combine booleans with OR.
17
- Keep custom guard handlers stable.
18
-
19
- Identity is persisted and installed in Expo request parameters before any check/download.
20
- Launch/foreground heartbeats report only the **running** bundle, never a downloaded
21
- candidate. Network telemetry does not block app launch or update checks. Development,
22
- Expo Go, web and disabled-updates builds leave automation off.
23
-
24
- | Policy/options | Behavior |
25
- | --- | --- |
26
- | manual, default options | OtaUpdates offers download/restart; the hook alone exposes state |
27
- | autoCheck | Check on mount and foreground, minimum interval 60 seconds |
28
- | autoUpdate | Also download eligible manual candidates |
29
- | autoReload | Reload a pending non-background bundle while app is active |
30
- | delivery=background | Download silently; apply on next cold launch or manual reload |
31
- | guard=ota-force-update | Block with gate, download automatically; restart button when ready |
32
- | guard=ota-force-store-update | Block with gate; open store, never download this candidate |
33
- | custom/unknown guard | Block until guardHandlers[action] explicitly returns `allow` |
34
-
35
- Store guard payload: `{ "androidUrl": "market://details?id=com.example.app",
36
- "iosUrl": "https://apps.apple.com/app/id123" }`; `url` is a common fallback. Only
37
- https, market and itms-apps URLs are accepted. Native upgrades still require a store
38
- release; OTA cannot add native modules or change the installed runtime.
39
-
40
- The built-in gate is a non-dismissable modal that preserves mounted navigation and providers.
41
- Customize required UI with `renderBlocked`, and optional UI with `renderAvailable`.
42
- Keep `OtaUpdates` mounted beside navigation; a hook alone exposes `blocked` but cannot prevent interaction with
43
- your own screens. Unknown guards fail closed. Required checks are online policy,
44
- not authentication or a tamper-proof access restriction. Offline check failure keeps
45
- the running app usable unless a required candidate was already discovered or the running bundle requires a store/custom guard.
46
-
47
- Calls are single-flight per action; a different action while busy rejects. Errors are
48
- available in `error` and returned promises reject, so handle manual calls with try/catch.
49
- Retry rechecks the server and reevaluates a pending candidate's custom guard.
50
- Download reevaluates the fetched manifest's policy because it can differ from the
51
- checked candidate. A pending bundle owns the gate until reload; checking another
52
- candidate does not authorize an older cached bundle. Native rollback directives are
53
- supported. Expo controls cold-start loading of already downloaded bundles; JS guards
54
- cannot revoke that native cache. Store/custom guards are checked again from the running
55
- manifest on the next launch; force OTA is already fulfilled by launching that bundle.
56
- Do not mix direct expo-updates calls or native automatic
57
- checks with hook orchestration: configure-app uses checkAutomatically=NEVER.
58
-
59
- Legacy exports `checkForUpdateAsync`/`fetchUpdateAsync` remain identity-aware low-level
60
- APIs for existing integrations. They intentionally do not implement hook policies.
61
- No database/admin credentials are shipped: the server persists public heartbeat reports.
@@ -1,16 +0,0 @@
1
- export {
2
- start,
3
- getInstallationId,
4
- getDeviceId,
5
- checkForUpdateAsync,
6
- fetchUpdateAsync,
7
- } from "./runtime";
8
- export { useOtaUpdates } from "./model/hooks/useOtaUpdates";
9
- export { OtaUpdateGate } from "./ui/ota-update-gate";
10
- export { OtaUpdates } from "./ui/ota-updates";
11
- export type {
12
- OtaOptions,
13
- OtaController,
14
- OtaUpdatesProps,
15
- OtaPolicy,
16
- } from "./types";
@@ -1,97 +0,0 @@
1
- import type { OtaOptions, OtaController } from "../../types";
2
- import { useEffect, useRef, useSyncExternalStore } from "react";
3
- import * as Updates from "expo-updates";
4
- import { AppState, Linking, Platform } from "react-native";
5
- import {
6
- enabled,
7
- start,
8
- getInstallationId,
9
- getDeviceId,
10
- checkForUpdateAsync,
11
- fetchUpdateAsync,
12
- } from "../../runtime";
13
- import { createUpdateController } from "../update-controller";
14
-
15
- const controller = createUpdateController({
16
- enabled,
17
- start,
18
- identity: async () => ({
19
- installationId: await getInstallationId(),
20
- deviceId: await getDeviceId(),
21
- }),
22
- check: checkForUpdateAsync,
23
- fetch: fetchUpdateAsync,
24
- runningCandidate: () => ({ type: "new", manifest: Updates.manifest }),
25
- reload: () => Updates.reloadAsync(),
26
- isActive: () => AppState.currentState === "active",
27
- openStore: async (payload) => {
28
- const links =
29
- payload && typeof payload === "object"
30
- ? (payload as Record<string, unknown>)
31
- : {};
32
- const url = links[`${Platform.OS}Url`] || links.url;
33
- if (
34
- typeof url !== "string" ||
35
- !/^(https:\/\/|market:\/\/|itms-apps:\/\/)/i.test(url)
36
- ) {
37
- throw new Error(
38
- "The store update policy must provide a valid https/store URL",
39
- );
40
- }
41
- await Linking.openURL(url);
42
- },
43
- });
44
- const emptyOptions = Object.freeze({});
45
-
46
- /** Configure once in the root; additional consumers share identity, state and actions. */
47
- export function useOtaUpdates(
48
- options: OtaOptions = emptyOptions,
49
- ): OtaController {
50
- const owner = useRef(Symbol("ota-updates"));
51
- const state = useSyncExternalStore(
52
- controller.subscribe,
53
- controller.getSnapshot,
54
- controller.getSnapshot,
55
- );
56
- const native = Updates.useUpdates();
57
- const {
58
- autoCheck = false,
59
- autoUpdate = false,
60
- autoReload = false,
61
- guardHandlers,
62
- } = options;
63
- useEffect(() => {
64
- const token = owner.current;
65
- controller.configure(token, {
66
- autoCheck,
67
- autoUpdate,
68
- autoReload,
69
- guardHandlers,
70
- });
71
- void controller.initialize().catch(() => undefined);
72
- controller.automaticCheck();
73
- const subscription = AppState.addEventListener("change", (next) => {
74
- if (next === "active") controller.automaticCheck();
75
- });
76
- return () => {
77
- subscription.remove();
78
- controller.removeOwner(token);
79
- };
80
- }, [autoCheck, autoUpdate, autoReload, guardHandlers]);
81
- const downloaded = native.downloadedUpdate;
82
- useEffect(() => {
83
- if (!enabled || !downloaded || !native.isUpdatePending) return;
84
- void controller
85
- .syncPending({ type: downloaded.type, manifest: downloaded.manifest })
86
- .catch(() => undefined);
87
- }, [downloaded, native.isUpdatePending]);
88
- return {
89
- ...state,
90
- isBusy: state.status !== "idle",
91
- check: controller.check,
92
- download: controller.download,
93
- reload: controller.reload,
94
- retry: controller.retry,
95
- openStore: controller.openStore,
96
- };
97
- }
@@ -1,293 +0,0 @@
1
- import { manifestDetails } from "../types";
2
- import type {
3
- OtaCandidate,
4
- OtaCheckResult,
5
- OtaFetchResult,
6
- OtaOptions,
7
- OtaState,
8
- } from "../types";
9
-
10
- interface Dependencies {
11
- enabled: boolean;
12
- start(): void;
13
- identity(): Promise<{
14
- installationId: string | null;
15
- deviceId: string | null;
16
- }>;
17
- check(): Promise<OtaCheckResult>;
18
- fetch(): Promise<OtaFetchResult>;
19
- reload(): Promise<void>;
20
- isActive(): boolean;
21
- openStore(payload: unknown): Promise<void>;
22
- runningCandidate?(): OtaCandidate | null;
23
- now?(): number;
24
- }
25
-
26
- // Pure lifecycle model. Native APIs, storage and React live in adapters.
27
- export function createUpdateController(deps: Dependencies) {
28
- let state: Readonly<OtaState> = Object.freeze({
29
- enabled: deps.enabled,
30
- status: "idle",
31
- installationId: null,
32
- deviceId: null,
33
- available: false,
34
- pending: false,
35
- candidate: null,
36
- policy: null,
37
- blocked: false,
38
- blockReason: null,
39
- error: null,
40
- });
41
- const listeners = new Set<() => void>();
42
- const owners = new Map<symbol, OtaOptions>();
43
- let flight: Promise<unknown> | undefined;
44
- let flightKind: OtaState["status"] | undefined;
45
- let lastAutomaticCheck = -Infinity;
46
- let identityReady: Promise<void> | undefined;
47
- let pendingKey: string | undefined;
48
- let pendingGeneration = 0;
49
- const now = deps.now || Date.now;
50
- function patch(value: Partial<OtaState>) {
51
- state = Object.freeze({ ...state, ...value });
52
- for (const listener of listeners) listener();
53
- }
54
- function options() {
55
- const result: Required<OtaOptions> = {
56
- autoCheck: false,
57
- autoUpdate: false,
58
- autoReload: false,
59
- guardHandlers: {},
60
- };
61
- for (const owner of owners.values()) {
62
- for (const key of ["autoCheck", "autoUpdate", "autoReload"] as const)
63
- result[key] ||= owner[key] === true;
64
- Object.assign(result.guardHandlers, owner.guardHandlers);
65
- }
66
- return result;
67
- }
68
- function initialize() {
69
- deps.start();
70
- if (!deps.enabled) return Promise.resolve();
71
- if (!identityReady)
72
- identityReady = deps
73
- .identity()
74
- .then(async (identity) => {
75
- patch(identity);
76
- await inspectRunning();
77
- })
78
- .catch((error) => {
79
- identityReady = undefined;
80
- patch({ error });
81
- throw error;
82
- });
83
- return identityReady;
84
- }
85
- function run<T>(
86
- kind: OtaState["status"],
87
- task: () => Promise<T>,
88
- ): Promise<T> {
89
- if (!deps.enabled)
90
- return Promise.reject(
91
- new Error("OTA updates are unavailable in this build"),
92
- );
93
- if (flight) {
94
- if (flightKind === kind) return flight as Promise<T>;
95
- return Promise.reject(new Error("Another OTA operation is in progress"));
96
- }
97
- flightKind = kind;
98
- patch({ status: kind, error: null });
99
- const operation = Promise.resolve()
100
- .then(initialize)
101
- .then(task)
102
- .catch((error) => {
103
- patch({ error });
104
- throw error;
105
- })
106
- .finally(() => {
107
- flight = undefined;
108
- flightKind = undefined;
109
- patch({ status: "idle" });
110
- });
111
- flight = operation;
112
- return operation;
113
- }
114
- async function inspect(candidate: OtaCandidate | null) {
115
- const policy =
116
- manifestDetails(candidate?.manifest)?.extra?.updatePolicy ?? null;
117
- patch({ candidate, policy, blocked: false, blockReason: null });
118
- if (!policy) return;
119
- if (
120
- policy.schemaVersion !== 1 ||
121
- !["manual", "background"].includes(policy.delivery)
122
- ) {
123
- patch({ blocked: true, blockReason: "unsupported-policy" });
124
- return;
125
- }
126
- const guard = policy.guard;
127
- if (!guard) return;
128
- // Fail closed while an asynchronous application guard is being evaluated.
129
- patch({ blocked: true, blockReason: guard.action || "unsupported-policy" });
130
- if (
131
- guard.action === "ota-force-update" ||
132
- guard.action === "ota-force-store-update"
133
- )
134
- return;
135
- const handler = options().guardHandlers[guard.action];
136
- if (!handler) return;
137
- const decision = await handler({
138
- action: guard.action,
139
- payload: guard.payload,
140
- manifest: candidate?.manifest,
141
- });
142
- if (decision === "allow") patch({ blocked: false, blockReason: null });
143
- }
144
- async function inspectRunning() {
145
- const running = deps.runningCandidate?.();
146
- // Force OTA is fulfilled by launching it. Store/custom guards still apply
147
- // after a native cold start, including a bundle fetched during a release race.
148
- if (
149
- manifestDetails(running?.manifest)?.extra?.updatePolicy?.guard?.action ===
150
- "ota-force-update"
151
- )
152
- return inspect(null);
153
- return inspect(running || null);
154
- }
155
- function canDownload() {
156
- return !state.blocked || state.blockReason === "ota-force-update";
157
- }
158
- async function downloadInternal() {
159
- if (!state.available && !state.pending)
160
- throw new Error("Check for an update before downloading");
161
- if (!canDownload()) throw new Error("Update is blocked by its guard");
162
- patch({ status: "downloading" });
163
- const result = await deps.fetch();
164
- if (result.isNew || result.isRollBackToEmbedded) {
165
- const candidate = target(result);
166
- pendingKey = key(candidate);
167
- pendingGeneration += 1;
168
- // Fetch performs another manifest request: its policy can differ from check's.
169
- patch({ pending: true, available: true });
170
- await inspect(candidate);
171
- }
172
- return result;
173
- }
174
- async function reloadInternal() {
175
- if (!state.pending) throw new Error("No downloaded update is ready");
176
- if (!canDownload()) throw new Error("Update is blocked by its guard");
177
- if (!deps.isActive())
178
- throw new Error("Reload is only allowed while the app is active");
179
- patch({ status: "reloading" });
180
- return deps.reload();
181
- }
182
- async function automate(allowDownload = true) {
183
- const settings = options();
184
- if (
185
- allowDownload &&
186
- !state.pending &&
187
- state.available &&
188
- canDownload() &&
189
- (settings.autoUpdate ||
190
- state.policy?.delivery === "background" ||
191
- state.blockReason === "ota-force-update")
192
- ) {
193
- await downloadInternal();
194
- }
195
- // A background policy always wins over autoReload. Guards are re-evaluated after fetch.
196
- if (
197
- state.pending &&
198
- canDownload() &&
199
- settings.autoReload &&
200
- state.policy?.delivery !== "background" &&
201
- deps.isActive()
202
- )
203
- await reloadInternal();
204
- }
205
- function check() {
206
- return run("checking", async () => {
207
- const result = await deps.check();
208
- if (result.isAvailable || result.isRollBackToEmbedded) {
209
- patch({ available: true });
210
- // Never replace the policy governing an already downloaded bundle with a different candidate.
211
- if (!state.pending) await inspect(target(result));
212
- } else if (!state.pending) {
213
- patch({ available: false });
214
- await inspectRunning();
215
- }
216
- if (state.pending) await inspect(state.candidate);
217
- await automate();
218
- return result;
219
- });
220
- }
221
- function automaticCheck() {
222
- if (
223
- !deps.enabled ||
224
- !options().autoCheck ||
225
- !deps.isActive() ||
226
- flight ||
227
- now() - lastAutomaticCheck < 60000
228
- )
229
- return;
230
- lastAutomaticCheck = now();
231
- void check().catch(() => undefined);
232
- }
233
- const api = {
234
- getSnapshot: () => state,
235
- subscribe(listener: () => void) {
236
- listeners.add(listener);
237
- return () => listeners.delete(listener);
238
- },
239
- initialize,
240
- configure(owner: symbol, value: OtaOptions) {
241
- owners.set(owner, value);
242
- },
243
- removeOwner(owner: symbol) {
244
- owners.delete(owner);
245
- },
246
- automaticCheck,
247
- check,
248
- download: () =>
249
- run("downloading", async () => {
250
- const result = await downloadInternal();
251
- await automate(false);
252
- return result;
253
- }),
254
- reload: () => run("reloading", reloadInternal),
255
- retry: () => check(),
256
- openStore: () =>
257
- run("opening-store", async () => {
258
- if (state.blockReason !== "ota-force-store-update")
259
- throw new Error("No store upgrade is required");
260
- await deps.openStore(state.policy?.guard?.payload);
261
- }),
262
- syncPending(candidate: OtaCandidate | null): Promise<void> {
263
- if (!candidate || key(candidate) === pendingKey) return Promise.resolve();
264
- if (flight) {
265
- const observedGeneration = pendingGeneration;
266
- return flight
267
- .catch(() => undefined)
268
- .then(() => {
269
- if (pendingGeneration === observedGeneration)
270
- return api.syncPending(candidate);
271
- });
272
- }
273
- return run("checking", async () => {
274
- pendingKey = key(candidate);
275
- pendingGeneration += 1;
276
- patch({ pending: true, available: true });
277
- await inspect(candidate);
278
- // Synchronizing native state never implicitly reloads a restored bundle.
279
- });
280
- },
281
- };
282
- return api;
283
- }
284
-
285
- function target(result: OtaCheckResult | OtaFetchResult): OtaCandidate {
286
- if (result.isRollBackToEmbedded) return { type: "rollback", manifest: null };
287
- return { type: "new", manifest: result.manifest };
288
- }
289
- function key(candidate: OtaCandidate) {
290
- return candidate.type === "rollback"
291
- ? "rollback"
292
- : manifestDetails(candidate.manifest)?.id;
293
- }