Open History to see the last commit
1import * as Updates from "expo-updates";
2
3import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 reportAtomCommandResult,
7 settlePromise,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10
11export type AppUpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
12
13export interface AppUpdateClient {
14 readonly isEnabled: boolean;
15 readonly checkForUpdateAsync: () => Promise<{
16 readonly isAvailable: boolean;
17 readonly isRollBackToEmbedded: boolean;
18 }>;
19 readonly fetchUpdateAsync: () => Promise<{
20 readonly isNew: boolean;
21 readonly isRollBackToEmbedded: boolean;
22 }>;
23 readonly reloadAsync: () => Promise<void>;
24}
25
26interface AppUpdateCheckOptions {
27 readonly client?: AppUpdateClient;
28 readonly onFailure?: (message: string) => void;
29 readonly onStateChange?: (state: AppUpdateCheckState) => void;
30}
31
32interface AppUpdateCheckProgress {
33 failure: string | undefined;
34 state: AppUpdateCheckState | undefined;
35}
36
37interface AppUpdateCheckInFlight {
38 readonly failureListeners: Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>;
39 readonly progress: AppUpdateCheckProgress;
40 readonly promise: Promise<void>;
41 readonly stateListeners: Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>;
42}
43
44interface Deferred {
45 readonly promise: Promise<void>;
46 readonly reject: (cause: unknown) => void;
47 readonly resolve: () => void;
48}
49
50const HIDDEN_UPDATE_TAP_COUNT = 5;
51let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
52
53/**
54 * Keeps the manual update affordance discoverable only to someone deliberately
55 * tapping the version row five times.
56 */
57export function registerHiddenUpdateTap(count: number): {
58 readonly nextCount: number;
59 readonly shouldCheck: boolean;
60} {
61 const nextCount = count + 1;
62 if (nextCount >= HIDDEN_UPDATE_TAP_COUNT) {
63 return {
64 nextCount: 0,
65 shouldCheck: true,
66 };
67 }
68 return {
69 nextCount,
70 shouldCheck: false,
71 };
72}
73
74export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
75 const client = options.client ?? Updates;
76 if (!client.isEnabled) return;
77
78 if (appUpdateCheckInFlight) {
79 await observeAppUpdateCheck(appUpdateCheckInFlight, options);
80 return;
81 }
82
83 const progress: AppUpdateCheckProgress = {
84 failure: undefined,
85 state: undefined,
86 };
87 const failureListeners = new Set<NonNullable<AppUpdateCheckOptions["onFailure"]>>();
88 const stateListeners = new Set<NonNullable<AppUpdateCheckOptions["onStateChange"]>>();
89 if (options.onFailure) failureListeners.add(options.onFailure);
90 if (options.onStateChange) stateListeners.add(options.onStateChange);
91
92 const deferred = createDeferred();
93 const inFlight: AppUpdateCheckInFlight = {
94 failureListeners,
95 progress,
96 promise: deferred.promise,
97 stateListeners,
98 };
99 // Publish the operation before any state listener can synchronously re-enter.
100 appUpdateCheckInFlight = inFlight;
101
102 const execution = performAppUpdateCheck(client, {
103 onFailure: (message) => {
104 progress.failure = message;
105 notifyListeners(failureListeners, message);
106 },
107 onStateChange: (state) => {
108 progress.state = state;
109 notifyListeners(stateListeners, state);
110 },
111 });
112 void execution.then(deferred.resolve, deferred.reject);
113
114 try {
115 await deferred.promise;
116 } finally {
117 if (appUpdateCheckInFlight === inFlight) {
118 appUpdateCheckInFlight = undefined;
119 }
120 }
121}
122
123function createDeferred(): Deferred {
124 let reject!: Deferred["reject"];
125 let resolve!: Deferred["resolve"];
126 const promise = new Promise<void>((resolvePromise, rejectPromise) => {
127 resolve = () => resolvePromise();
128 reject = rejectPromise;
129 });
130 return { promise, reject, resolve };
131}
132
133function notifyListeners<A>(listeners: ReadonlySet<(value: A) => void>, value: A): void {
134 // A listener can synchronously subscribe another caller. Snapshot so that
135 // caller receives only observeAppUpdateCheck's explicit current-value replay.
136 const snapshot = Array.from(listeners);
137 for (const listener of snapshot) listener(value);
138}
139
140async function observeAppUpdateCheck(
141 inFlight: AppUpdateCheckInFlight,
142 options: AppUpdateCheckOptions,
143): Promise<void> {
144 const onFailure = options.onFailure;
145 const onStateChange = options.onStateChange;
146
147 if (onFailure) {
148 inFlight.failureListeners.add(onFailure);
149 if (inFlight.progress.failure) onFailure(inFlight.progress.failure);
150 }
151 if (onStateChange) {
152 inFlight.stateListeners.add(onStateChange);
153 if (inFlight.progress.state) onStateChange(inFlight.progress.state);
154 }
155
156 try {
157 await inFlight.promise;
158 } finally {
159 if (onFailure) inFlight.failureListeners.delete(onFailure);
160 if (onStateChange) inFlight.stateListeners.delete(onStateChange);
161 }
162}
163
164async function performAppUpdateCheck(
165 client: AppUpdateClient,
166 options: AppUpdateCheckOptions,
167): Promise<void> {
168 const setState = options.onStateChange ?? (() => {});
169
170 setState("checking");
171 const check = await settlePromise(() => client.checkForUpdateAsync());
172 if (check._tag === "Failure") {
173 reportUpdateFailure(check, "Could not check for updates.", options.onFailure);
174 setState("idle");
175 return;
176 }
177 // A rollback directive (`eas update:rollback`) arrives as isAvailable: false
178 // with isRollBackToEmbedded: true. The running OTA still has to be dropped.
179 if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
180 setState("current");
181 return;
182 }
183
184 setState("downloading");
185 const fetched = await settlePromise(() => client.fetchUpdateAsync());
186 if (fetched._tag === "Failure") {
187 reportUpdateFailure(fetched, "Could not download the update.", options.onFailure);
188 setState("idle");
189 return;
190 }
191 // isNew is always false for a rollback, so it cannot be the sole gate.
192 if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
193 setState("current");
194 return;
195 }
196
197 setState("restarting");
198 const reloaded = await settlePromise(() => client.reloadAsync());
199 if (reloaded._tag === "Failure") {
200 reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
201 setState("idle");
202 }
203}
204
205function reportUpdateFailure(
206 result: AtomCommandResult<unknown, unknown>,
207 fallback: string,
208 onFailure: AppUpdateCheckOptions["onFailure"],
209): void {
210 reportAtomCommandResult(result, { label: "app update check" });
211 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
212 const error = squashAtomCommandFailure(result);
213 onFailure?.(error instanceof Error ? error.message : fallback);
214}
215
216export function createAppUpdateLaunchCheck(
217 client: AppUpdateClient = Updates,
218): () => Promise<void> | undefined {
219 let started = false;
220
221 return () => {
222 if (started || !client.isEnabled) return undefined;
223 started = true;
224 return runAppUpdateCheck({ client });
225 };
226}
227
228export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();