create-expo-updates-server 0.2.1 → 0.4.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 (103) hide show
  1. package/dist/template/README.md +1 -1
  2. package/dist/template/app/updates/[encodedKey]/page.tsx +55 -33
  3. package/dist/template/app/updates/devices/page.tsx +13 -7
  4. package/dist/template/app/updates/embedded/page.tsx +25 -13
  5. package/dist/template/app/updates/emergency-redirects/page.tsx +70 -38
  6. package/dist/template/app/updates/page.tsx +33 -20
  7. package/dist/template/components/admin/admin-shell.tsx +11 -5
  8. package/dist/template/components/admin/language-switcher.tsx +5 -2
  9. package/dist/template/components/ui/dialog.tsx +13 -4
  10. package/dist/template/components/ui/sheet.tsx +6 -2
  11. package/dist/template/components/ui/sidebar.tsx +62 -17
  12. package/dist/template/docs/admin-ui.md +18 -24
  13. package/dist/template/docs/device-targeting.md +4 -5
  14. package/dist/template/docs/expo-app-setup.md +8 -12
  15. package/dist/template/docs/getting-started.md +5 -5
  16. package/dist/template/docs/getting-started.ru.md +11 -544
  17. package/dist/template/docs/index.md +1 -1
  18. package/dist/template/docs/installation-telemetry.md +4 -4
  19. package/dist/template/docs/operations-guide.md +1 -1
  20. package/dist/template/docs/ota-client-lifecycle.md +46 -42
  21. package/dist/template/docs/ota-emergency-recovery.md +34 -57
  22. package/dist/template/docs/ru/admin-ui.md +29 -0
  23. package/dist/template/docs/ru/device-targeting.md +59 -0
  24. package/dist/template/docs/ru/doctor.md +98 -0
  25. package/dist/template/docs/ru/expo-app-setup.md +497 -0
  26. package/dist/template/docs/ru/getting-started.md +391 -0
  27. package/dist/template/docs/ru/index.md +50 -0
  28. package/dist/template/docs/ru/installation-telemetry.md +125 -0
  29. package/dist/template/docs/ru/npm-installer.md +71 -0
  30. package/dist/template/docs/ru/operations-guide.md +317 -0
  31. package/dist/template/docs/ru/ota-client-lifecycle.md +167 -0
  32. package/dist/template/docs/ru/ota-emergency-recovery.md +108 -0
  33. package/dist/template/docs/ru/ota-update-policy.md +67 -0
  34. package/dist/template/docs/ru/publishing-npm-installer.md +49 -0
  35. package/dist/template/docs/ru/supabase-setup.md +120 -0
  36. package/dist/template/docs/uk/admin-ui.md +29 -0
  37. package/dist/template/docs/uk/device-targeting.md +59 -0
  38. package/dist/template/docs/uk/doctor.md +98 -0
  39. package/dist/template/docs/uk/expo-app-setup.md +497 -0
  40. package/dist/template/docs/uk/getting-started.md +391 -0
  41. package/dist/template/docs/uk/index.md +50 -0
  42. package/dist/template/docs/uk/installation-telemetry.md +125 -0
  43. package/dist/template/docs/uk/npm-installer.md +71 -0
  44. package/dist/template/docs/uk/operations-guide.md +317 -0
  45. package/dist/template/docs/uk/ota-client-lifecycle.md +167 -0
  46. package/dist/template/docs/uk/ota-emergency-recovery.md +108 -0
  47. package/dist/template/docs/uk/ota-update-policy.md +67 -0
  48. package/dist/template/docs/uk/publishing-npm-installer.md +49 -0
  49. package/dist/template/docs/uk/supabase-setup.md +120 -0
  50. package/dist/template/package-lock.json +589 -0
  51. package/dist/template/package.json +2 -0
  52. package/dist/template/scripts/lib/device-identity.test.ts +2 -2
  53. package/dist/template/scripts/lib/doctor.mjs +3 -3
  54. package/dist/template/scripts/lib/doctor.test.mjs +1 -1
  55. package/dist/template/scripts/lib/ota-client-configurator.mjs +116 -34
  56. package/dist/template/scripts/lib/ota-client-configurator.test.ts +210 -61
  57. package/dist/template/scripts/lib/ota-client.test.ts +1 -1
  58. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +435 -118
  59. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +243 -86
  60. package/dist/template/scripts/lib/ota-update-controller.test.ts +10 -9
  61. package/dist/template/scripts/lib/ota-updates-ui.test.tsx +154 -0
  62. package/dist/template/scripts/tests/fixtures/react-native-ui.tsx +34 -0
  63. package/dist/template/scripts/tests/ota-client-types.mjs +69 -0
  64. package/dist/template/src/client/devices/analytics.tsx +21 -8
  65. package/dist/template/src/client/devices/device-name.tsx +3 -1
  66. package/dist/template/src/client/devices/registry.tsx +38 -19
  67. package/dist/template/src/client/devices/version-adoption-chart.tsx +22 -10
  68. package/dist/template/src/client/distribution-control.tsx +27 -14
  69. package/dist/template/src/client/guard-action-combobox.test.ts +1 -1
  70. package/dist/template/src/client/guard-action-combobox.tsx +16 -10
  71. package/dist/template/src/client/i18n/en.json +203 -1
  72. package/dist/template/src/client/i18n/language-switching.test.tsx +224 -0
  73. package/dist/template/src/client/i18n/messages.test.ts +102 -19
  74. package/dist/template/src/client/i18n/messages.ts +31 -16
  75. package/dist/template/src/client/i18n/provider.tsx +6 -3
  76. package/dist/template/src/client/i18n/ru.json +488 -0
  77. package/dist/template/src/client/i18n/uk.json +488 -0
  78. package/dist/template/src/client/i18n/use-formatters.ts +5 -0
  79. package/dist/template/src/client/update-audience-editor.tsx +18 -11
  80. package/dist/template/src/client/update-policy-editor.tsx +64 -39
  81. package/dist/template/templates/expo-app/ota-client/README.md +16 -2
  82. package/dist/template/templates/expo-app/ota-client/controller.ts +107 -0
  83. package/dist/template/templates/expo-app/ota-client/device-identity.ts +48 -0
  84. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +18 -9
  85. package/dist/template/templates/expo-app/ota-client/index.ts +16 -0
  86. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.ts +97 -0
  87. package/dist/template/templates/expo-app/ota-client/model/update-controller.ts +293 -0
  88. package/dist/template/templates/expo-app/ota-client/runtime.ts +153 -0
  89. package/dist/template/templates/expo-app/ota-client/types.ts +85 -0
  90. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.tsx +25 -0
  91. package/dist/template/templates/expo-app/ota-client/ui/ota-updates.tsx +196 -0
  92. package/dist/template/tsconfig.json +3 -1
  93. package/dist/template/vitest.config.mts +3 -0
  94. package/dist/template-manifest.json +302 -127
  95. package/package.json +1 -1
  96. package/dist/template/templates/expo-app/ota-client/controller.js +0 -60
  97. package/dist/template/templates/expo-app/ota-client/device-identity.js +0 -26
  98. package/dist/template/templates/expo-app/ota-client/index.d.ts +0 -47
  99. package/dist/template/templates/expo-app/ota-client/index.js +0 -3
  100. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +0 -48
  101. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +0 -182
  102. package/dist/template/templates/expo-app/ota-client/runtime.js +0 -112
  103. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +0 -56
@@ -1,4 +1,6 @@
1
1
  "use client";
2
+ import type { TranslationMessage } from "@/src/client/i18n/messages";
3
+ import { useI18n } from "@/src/client/i18n/provider";
2
4
 
3
5
  import { Textarea } from "@/components/ui/textarea";
4
6
 
@@ -43,10 +45,11 @@ export default function UpdatePolicyEditor({
43
45
  encodedKey: string;
44
46
  onSaved: () => Promise<void>;
45
47
  }) {
48
+ const { t, formatLocale } = useI18n();
46
49
  const [policy, setPolicy] = useState<UpdatePolicy | null>(null);
47
50
  const [payload, setPayload] = useState("");
48
51
  const [error, setError] = useState("");
49
- const [message, setMessage] = useState("");
52
+ const [message, setMessage] = useState<TranslationMessage>("");
50
53
  const [saving, setSaving] = useState(false);
51
54
  const [guardActions, setGuardActions] = useState<GuardActionItem[]>([]);
52
55
  const [canWriteGuardActions, setCanWriteGuardActions] = useState(false);
@@ -90,7 +93,7 @@ export default function UpdatePolicyEditor({
90
93
  if (!policy) {
91
94
  return (
92
95
  <Card className="rounded-xl border border-border bg-card p-5 text-sm shadow-none">
93
- {error || "Loading update policy…"}
96
+ {t(error || "Loading update policy…")}
94
97
  </Card>
95
98
  );
96
99
  }
@@ -169,7 +172,10 @@ export default function UpdatePolicyEditor({
169
172
  if (
170
173
  !option.id ||
171
174
  !window.confirm(
172
- `Delete "${option.actionKey}" from the action catalog? Existing policies are unaffected.`,
175
+ t(
176
+ 'Delete "{0}" from the action catalog? Existing policies are unaffected.',
177
+ [option.actionKey],
178
+ ),
173
179
  )
174
180
  ) {
175
181
  return;
@@ -201,7 +207,9 @@ export default function UpdatePolicyEditor({
201
207
  const trimmedPayload = payload.trim();
202
208
  guard = {
203
209
  action: policy.guard.action,
204
- ...(trimmedPayload ? { payload: JSON.parse(trimmedPayload) } : {}),
210
+ ...(trimmedPayload
211
+ ? { payload: JSON.parse(trimmedPayload) }
212
+ : {}),
205
213
  };
206
214
  }
207
215
  const saved = await putUpdatePolicy(
@@ -211,7 +219,10 @@ export default function UpdatePolicyEditor({
211
219
  );
212
220
  setPolicy(saved);
213
221
  setPayload(payloadText(saved.guard));
214
- setMessage(`Policy saved as version ${saved.policyVersion}.`);
222
+ setMessage({
223
+ key: "Policy saved as version {0}.",
224
+ values: [saved.policyVersion],
225
+ });
215
226
  await onSaved();
216
227
  } catch (saveError: unknown) {
217
228
  setError(
@@ -228,16 +239,18 @@ export default function UpdatePolicyEditor({
228
239
  <Card className="gap-4 p-5 shadow-none">
229
240
  <div className="flex flex-wrap items-center justify-between gap-3">
230
241
  <div>
231
- <h2 className="font-semibold">Update policy</h2>
242
+ <h2 className="font-semibold">{t("Update policy")}</h2>
232
243
  <p className="text-xs text-muted-foreground">
233
- Version {policy.policyVersion}
244
+ {t("Version {0}", [policy.policyVersion])}
234
245
  {policy.publishedAt
235
- ? ` · published ${new Date(policy.publishedAt).toLocaleString()}`
236
- : " · draft"}
246
+ ? t(" · published {0}", [
247
+ new Date(policy.publishedAt).toLocaleString(formatLocale),
248
+ ])
249
+ : t(" · draft")}
237
250
  </p>
238
251
  </div>
239
252
  <label className="text-sm">
240
- Delivery{" "}
253
+ {t("Delivery")}{" "}
241
254
  <NativeSelect
242
255
  value={policy.delivery}
243
256
  disabled={editingDisabled}
@@ -249,40 +262,46 @@ export default function UpdatePolicyEditor({
249
262
  }
250
263
  className="rounded-md border border-input bg-background px-2 py-2 "
251
264
  >
252
- <option value="manual">Manual</option>
253
- <option value="background">Background</option>
265
+ <option value="manual">{t("Manual")}</option>
266
+ <option value="background">{t("Background")}</option>
254
267
  </NativeSelect>
255
268
  </label>
256
269
  </div>
257
270
 
258
271
  {readOnly ? (
259
272
  <div className="rounded-md border border-border bg-muted/30 p-3 text-sm ">
260
- Published policies are read-only. Publish a new update ID to change
261
- policy.
273
+ {t(
274
+ "Published policies are read-only. Publish a new update ID to change policy.",
275
+ )}
262
276
  </div>
263
277
  ) : null}
264
278
  {policy.guard && policy.delivery === "manual" ? (
265
279
  <div className="rounded-md border border-blue-300 bg-blue-50 p-3 text-sm text-blue-900 dark:border-blue-800 dark:bg-blue-950/30 dark:text-blue-200">
266
- <strong>Note:</strong> a Guard is usually paired with Background
267
- delivery so the candidate can fetch silently. Activation is still
268
- allowed.
280
+ <strong>{t("Note:")}</strong>{" "}
281
+ {t(
282
+ "a Guard is usually paired with Background delivery so the candidate can fetch silently. Activation is still allowed.",
283
+ )}
269
284
  </div>
270
285
  ) : null}
271
- {error ? <p className="text-sm text-red-600">{error}</p> : null}
272
- {message ? <p className="text-sm text-emerald-600">{message}</p> : null}
286
+ {error ? <p className="text-sm text-red-600">{t(error)}</p> : null}
287
+ {message ? (
288
+ <p className="text-sm text-emerald-600">{t(message)}</p>
289
+ ) : null}
273
290
  {catalogError ? (
274
291
  <div
275
292
  role="status"
276
293
  className="flex items-center gap-2 text-sm text-amber-700 dark:text-amber-300"
277
294
  >
278
- <span>Action catalog: {catalogError}</span>
295
+ <span>
296
+ {t("Action catalog:")} {t(catalogError)}
297
+ </span>
279
298
  <Button
280
299
  variant="outline"
281
300
  size="sm"
282
301
  type="button"
283
302
  onClick={() => void loadGuardActions()}
284
303
  >
285
- Retry
304
+ {t("Retry")}
286
305
  </Button>
287
306
  </div>
288
307
  ) : null}
@@ -292,7 +311,7 @@ export default function UpdatePolicyEditor({
292
311
  className="flex flex-wrap items-end gap-2 rounded-md border border-border p-3 "
293
312
  >
294
313
  <label className="min-w-56 flex-1 text-xs text-muted-foreground">
295
- Add action to catalog
314
+ {t("Add action to catalog")}
296
315
  <TextInput
297
316
  value={catalogCreateValue}
298
317
  maxLength={100}
@@ -303,7 +322,7 @@ export default function UpdatePolicyEditor({
303
322
  }}
304
323
  aria-describedby="guard-action-catalog-create-help"
305
324
  className="mt-1 w-full rounded border border-input bg-background p-2 text-sm "
306
- placeholder="Reusable action name"
325
+ placeholder={t("Reusable action name")}
307
326
  />
308
327
  </label>
309
328
  <Button
@@ -312,32 +331,34 @@ export default function UpdatePolicyEditor({
312
331
  type="submit"
313
332
  disabled={catalogCreatePending}
314
333
  >
315
- {catalogCreatePending ? "Adding…" : "Add to catalog"}
334
+ {catalogCreatePending ? t("Adding…") : t("Add to catalog")}
316
335
  </Button>
317
336
  <p
318
337
  id="guard-action-catalog-create-help"
319
338
  className="w-full text-xs text-muted-foreground"
320
339
  >
321
- Adds a reusable catalog item without changing this policy.
340
+ {t(
341
+ "Adds a reusable catalog item without changing this policy.",
342
+ )}
322
343
  </p>
323
344
  {catalogCreateError ? (
324
345
  <div
325
346
  role="status"
326
347
  className="flex w-full items-center gap-2 text-xs text-amber-700 dark:text-amber-300"
327
348
  >
328
- <span>{catalogCreateError}</span>
349
+ <span>{t(catalogCreateError)}</span>
329
350
  <Button variant="outline" size="sm" type="submit">
330
- Retry
351
+ {t("Retry")}
331
352
  </Button>
332
353
  </div>
333
354
  ) : null}
334
355
  </form>
335
356
  ) : null}
336
357
  <div className="space-y-2 rounded-md border border-border p-3 ">
337
- <h3 className="text-sm font-medium">Action catalog</h3>
358
+ <h3 className="text-sm font-medium">{t("Action catalog")}</h3>
338
359
  {guardActions.length > 0 ? (
339
360
  <ul
340
- aria-label="Guard action catalog entries"
361
+ aria-label={t("Guard action catalog entries")}
341
362
  className="max-h-40 space-y-1 overflow-auto"
342
363
  >
343
364
  {guardActions.map((item) => (
@@ -353,7 +374,9 @@ export default function UpdatePolicyEditor({
353
374
  variant="destructive"
354
375
  size="sm"
355
376
  type="button"
356
- aria-label={`Delete ${item.actionKey} from action catalog`}
377
+ aria-label={t("Delete {0} from action catalog", [
378
+ item.actionKey,
379
+ ])}
357
380
  onClick={() =>
358
381
  void removeGuardAction({
359
382
  id: item.id,
@@ -362,7 +385,7 @@ export default function UpdatePolicyEditor({
362
385
  })
363
386
  }
364
387
  >
365
- Delete
388
+ {t("Delete")}
366
389
  </Button>
367
390
  ) : null}
368
391
  </li>
@@ -370,14 +393,15 @@ export default function UpdatePolicyEditor({
370
393
  </ul>
371
394
  ) : (
372
395
  <p className="text-xs text-muted-foreground">
373
- No catalog actions found.
396
+ {t("No catalog actions found.")}
374
397
  </p>
375
398
  )}
376
399
  </div>
377
400
 
378
401
  <div className="space-y-3 rounded-lg border border-input p-3 ">
379
402
  <label className="flex items-center gap-2 text-sm font-medium">
380
- <input className="size-4 rounded border-input accent-primary"
403
+ <input
404
+ className="size-4 rounded border-input accent-primary"
381
405
  type="checkbox"
382
406
  checked={policy.guard !== null}
383
407
  disabled={editingDisabled}
@@ -393,11 +417,12 @@ export default function UpdatePolicyEditor({
393
417
  if (!event.target.checked) setPayload("");
394
418
  }}
395
419
  />
396
- Guard enabled
420
+ {t("Guard enabled")}
397
421
  </label>
398
422
  <p className="text-xs text-muted-foreground">
399
- When enabled, this Guard applies unconditionally whenever this OTA is
400
- selected for a client.
423
+ {t(
424
+ "When enabled, this Guard applies unconditionally whenever this OTA is selected for a client.",
425
+ )}
401
426
  </p>
402
427
  {policy.guard ? (
403
428
  <>
@@ -417,7 +442,7 @@ export default function UpdatePolicyEditor({
417
442
  }
418
443
  />
419
444
  <label className="block text-xs text-muted-foreground">
420
- Optional custom JSON payload
445
+ {t("Optional custom JSON payload")}
421
446
  <Textarea
422
447
  value={payload}
423
448
  disabled={editingDisabled}
@@ -429,7 +454,7 @@ export default function UpdatePolicyEditor({
429
454
  </>
430
455
  ) : (
431
456
  <p className="text-sm text-muted-foreground">
432
- No Guard will be emitted in the update manifest.
457
+ {t("No Guard will be emitted in the update manifest.")}
433
458
  </p>
434
459
  )}
435
460
  </div>
@@ -441,7 +466,7 @@ export default function UpdatePolicyEditor({
441
466
  disabled={editingDisabled}
442
467
  onClick={() => void save()}
443
468
  >
444
- Save policy
469
+ {t("Save policy")}
445
470
  </Button>
446
471
  </Card>
447
472
  );
@@ -7,7 +7,7 @@ required native modules to an older binary via OTA. Keep these native dependenci
7
7
  in the same runtime compatibility boundary as the rest of your application.
8
8
 
9
9
  `ota-entry.js` starts telemetry without waiting, then synchronously loads the original
10
- entry saved in `ota-client-entry.json`. The configurator also patches the root layout with the update hook and gate. Development,
10
+ entry saved in `ota-client-entry.json`. The configurator also patches the root layout with the standalone OtaUpdates component. Development,
11
11
  Expo Go, web and disabled-updates builds do not report. Original OTA check policy
12
12
  remains under the application/configurator's control.
13
13
 
@@ -49,7 +49,9 @@ SecureStore; do not deliver this client to older binaries lacking the native dep
49
49
  ## Update hook
50
50
 
51
51
  `useOtaUpdates` shares identity, state and lifecycle actions across the application.
52
- The configurator inserts it and `OtaUpdateGate` in the root layout automatically.
52
+ The configurator renders `<OtaUpdates />` beside navigation. It calls the hook
53
+ internally, shows optional download/restart prompts, and blocks required updates.
54
+ The generated implementation uses TypeScript and JSX, with no context wrapper.
53
55
  See [Update lifecycle](./docs/update-lifecycle.md) for manual/automatic/background
54
56
  updates, force OTA versus store upgrades, custom guards and option defaults.
55
57
 
@@ -57,3 +59,15 @@ For a custom root that could not be patched, see the complete
57
59
  [manual integration guide](https://tonichiga.github.io/expo-updates-server/ota-client-lifecycle#manual-integration)
58
60
  (or `docs/ota-client-lifecycle.md` in the server repository). It covers both an
59
61
  already generated client and copying/configuring the client without the generator.
62
+
63
+ ## Type checking
64
+
65
+ Run `npx tsc --noEmit` in the Expo application. The server itself does not depend
66
+ on React Native. Maintainers can check the template against an application's
67
+ installed Expo dependencies without changing that application:
68
+
69
+ ```bash
70
+ node scripts/tests/ota-client-types.mjs /path/to/expo-app
71
+ ```
72
+
73
+ Run that command from the server repository.
@@ -0,0 +1,107 @@
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
+ }
@@ -0,0 +1,48 @@
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,11 +1,20 @@
1
1
  # Update lifecycle
2
2
 
3
- `configure-app` inserts `useOtaUpdates({ autoCheck: true, autoUpdate: false,
4
- autoReload: false })` in the root layout/App and wraps its content in `OtaUpdateGate`.
5
- All screens can call `useOtaUpdates()` to observe the same state and use `check()`,
6
- `download()` and `reload()`. No provider is needed. Configure automation in one root;
7
- additional consumers default to observation/manual actions. Multiple configured roots
8
- combine boolean options with OR. Guard handlers should be stable references.
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.
9
18
 
10
19
  Identity is persisted and installed in Expo request parameters before any check/download.
11
20
  Launch/foreground heartbeats report only the **running** bundle, never a downloaded
@@ -14,7 +23,7 @@ Expo Go, web and disabled-updates builds leave automation off.
14
23
 
15
24
  | Policy/options | Behavior |
16
25
  | --- | --- |
17
- | manual, default options | Check exposes candidate; caller downloads and reloads |
26
+ | manual, default options | OtaUpdates offers download/restart; the hook alone exposes state |
18
27
  | autoCheck | Check on mount and foreground, minimum interval 60 seconds |
19
28
  | autoUpdate | Also download eligible manual candidates |
20
29
  | autoReload | Reload a pending non-background bundle while app is active |
@@ -29,8 +38,8 @@ https, market and itms-apps URLs are accepted. Native upgrades still require a s
29
38
  release; OTA cannot add native modules or change the installed runtime.
30
39
 
31
40
  The built-in gate is a non-dismissable modal that preserves mounted navigation and providers.
32
- It is customizable with `renderBlocked`. Keep the gate mounted around
33
- the application; a hook alone exposes `blocked` but cannot prevent interaction with
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
34
43
  your own screens. Unknown guards fail closed. Required checks are online policy,
35
44
  not authentication or a tamper-proof access restriction. Offline check failure keeps
36
45
  the running app usable unless a required candidate was already discovered or the running bundle requires a store/custom guard.
@@ -0,0 +1,16 @@
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";
@@ -0,0 +1,97 @@
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
+ }