create-expo-updates-server 0.4.0 → 0.6.1

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 (175) hide show
  1. package/README.md +4 -2
  2. package/dist/template/Dockerfile +4 -6
  3. package/dist/template/README.md +4 -9
  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 +375 -263
  18. package/dist/template/app/updates/devices/page.tsx +188 -152
  19. package/dist/template/app/updates/embedded/page.tsx +63 -29
  20. package/dist/template/app/updates/emergency-redirects/page.tsx +93 -58
  21. package/dist/template/app/updates/layout.tsx +2 -1
  22. package/dist/template/app/updates/page.tsx +381 -283
  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 -101
  26. package/dist/template/components/admin/confirm-action.tsx +123 -0
  27. package/dist/template/components/admin/language-switcher.tsx +25 -17
  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/empty.tsx +103 -0
  39. package/dist/template/components/ui/field.tsx +248 -0
  40. package/dist/template/components/ui/input-group.tsx +170 -0
  41. package/dist/template/components/ui/input.tsx +1 -1
  42. package/dist/template/components/ui/native-select.tsx +1 -1
  43. package/dist/template/components/ui/radio-group.tsx +41 -0
  44. package/dist/template/components/ui/status-tones.ts +15 -0
  45. package/dist/template/components/ui/table.tsx +1 -1
  46. package/dist/template/components/ui/textarea.tsx +1 -1
  47. package/dist/template/docs/admin-ui.md +7 -3
  48. package/dist/template/docs/device-targeting.md +2 -7
  49. package/dist/template/docs/doctor.md +2 -2
  50. package/dist/template/docs/expo-app-setup.md +9 -27
  51. package/dist/template/docs/getting-started.md +3 -4
  52. package/dist/template/docs/installation-telemetry.md +2 -8
  53. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +5 -0
  54. package/dist/template/docs/migrations/2026-11-25-device-favorites.sql +53 -0
  55. package/dist/template/docs/migrations/2026-11-25-download-on-postpone.sql +5 -0
  56. package/dist/template/docs/migrations/2026-11-25-public-distribution-history.sql +283 -0
  57. package/dist/template/docs/migrations/schema.sql +349 -0
  58. package/dist/template/docs/npm-installer.md +3 -3
  59. package/dist/template/docs/operations-guide.md +8 -6
  60. package/dist/template/docs/ota-client-lifecycle.md +30 -68
  61. package/dist/template/docs/ota-update-policy.md +9 -20
  62. package/dist/template/docs/ru/admin-ui.md +7 -3
  63. package/dist/template/docs/ru/device-targeting.md +2 -2
  64. package/dist/template/docs/ru/doctor.md +2 -2
  65. package/dist/template/docs/ru/expo-app-setup.md +9 -9
  66. package/dist/template/docs/ru/getting-started.md +3 -3
  67. package/dist/template/docs/ru/installation-telemetry.md +2 -2
  68. package/dist/template/docs/ru/npm-installer.md +3 -3
  69. package/dist/template/docs/ru/operations-guide.md +8 -3
  70. package/dist/template/docs/ru/ota-client-lifecycle.md +30 -35
  71. package/dist/template/docs/ru/ota-update-policy.md +9 -7
  72. package/dist/template/docs/ru/publishing-npm-installer.md +2 -2
  73. package/dist/template/docs/uk/admin-ui.md +7 -3
  74. package/dist/template/docs/uk/device-targeting.md +2 -2
  75. package/dist/template/docs/uk/doctor.md +2 -2
  76. package/dist/template/docs/uk/expo-app-setup.md +9 -9
  77. package/dist/template/docs/uk/getting-started.md +3 -3
  78. package/dist/template/docs/uk/installation-telemetry.md +2 -2
  79. package/dist/template/docs/uk/npm-installer.md +3 -3
  80. package/dist/template/docs/uk/operations-guide.md +8 -3
  81. package/dist/template/docs/uk/ota-client-lifecycle.md +30 -35
  82. package/dist/template/docs/uk/ota-update-policy.md +9 -7
  83. package/dist/template/docs/uk/publishing-npm-installer.md +2 -2
  84. package/dist/template/lib/audience-ids.ts +4 -0
  85. package/dist/template/package-lock.json +46 -0
  86. package/dist/template/package.json +3 -1
  87. package/dist/template/scripts/configure-expo-app.mjs +3 -3
  88. package/dist/template/scripts/create-access-token.mjs +1 -1
  89. package/dist/template/scripts/lib/doctor.mjs +10 -7
  90. package/dist/template/scripts/lib/doctor.test.mjs +7 -5
  91. package/dist/template/scripts/lib/embedded-update-registrar.test.ts +22 -7
  92. package/dist/template/scripts/lib/expo-app-configurator.mjs +25 -22
  93. package/dist/template/scripts/lib/expo-app-configurator.test.ts +37 -2
  94. package/dist/template/scripts/lib/ota-client-configurator.mjs +152 -55
  95. package/dist/template/scripts/lib/ota-client-configurator.test.ts +60 -20
  96. package/dist/template/scripts/lib/ota-client-package.mjs +25 -0
  97. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +90 -32
  98. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +49 -6
  99. package/dist/template/scripts/tests/device-analytics-migrations.mjs +12 -1
  100. package/dist/template/scripts/tests/device-targeting-activation.mjs +2 -3
  101. package/dist/template/scripts/tests/e2e/client-lifecycle.mjs +161 -0
  102. package/dist/template/scripts/tests/e2e/client-lifecycle.scenario.jsx +465 -0
  103. package/dist/template/scripts/tests/e2e/client-vitest.mts +18 -0
  104. package/dist/template/scripts/tests/e2e/console.mjs +86 -0
  105. package/dist/template/scripts/tests/e2e/delivery.mjs +296 -0
  106. package/dist/template/scripts/tests/e2e/device-favorites.mjs +309 -0
  107. package/dist/template/scripts/tests/e2e/installations.mjs +132 -0
  108. package/dist/template/scripts/tests/e2e/policy.mjs +253 -0
  109. package/dist/template/scripts/tests/e2e/registrar-token.mjs +59 -0
  110. package/dist/template/scripts/tests/e2e/release-matrix.mjs +303 -0
  111. package/dist/template/scripts/tests/e2e/releases.mjs +162 -0
  112. package/dist/template/scripts/tests/e2e/run.mjs +224 -0
  113. package/dist/template/scripts/tests/manifest-identity.sql +7 -5
  114. package/dist/template/scripts/tests/public-distribution-history.mjs +102 -0
  115. package/dist/template/src/client/admin-api.ts +45 -10
  116. package/dist/template/src/client/admin-types.ts +35 -1
  117. package/dist/template/src/client/devices/analytics.tsx +168 -231
  118. package/dist/template/src/client/devices/cohorts.tsx +181 -0
  119. package/dist/template/src/client/devices/device-name.tsx +37 -23
  120. package/dist/template/src/client/devices/favorite-targets.tsx +381 -0
  121. package/dist/template/src/client/devices/registry.tsx +258 -245
  122. package/dist/template/src/client/devices/use-devices-report.test.tsx +98 -0
  123. package/dist/template/src/client/devices/use-devices-report.ts +53 -82
  124. package/dist/template/src/client/devices/version-adoption-chart.tsx +47 -49
  125. package/dist/template/src/client/distribution-control.tsx +89 -57
  126. package/dist/template/src/client/distribution-history.tsx +353 -0
  127. package/dist/template/src/client/guard-action-catalog.tsx +183 -0
  128. package/dist/template/src/client/guard-action-combobox.test.ts +16 -22
  129. package/dist/template/src/client/guard-action-combobox.tsx +133 -239
  130. package/dist/template/src/client/guard-action-options.ts +4 -6
  131. package/dist/template/src/client/i18n/en.json +133 -2
  132. package/dist/template/src/client/i18n/language-switching.test.tsx +12 -3
  133. package/dist/template/src/client/i18n/ru.json +133 -2
  134. package/dist/template/src/client/i18n/uk.json +133 -2
  135. package/dist/template/src/client/logout-button.tsx +3 -3
  136. package/dist/template/src/client/policy-draft.ts +138 -0
  137. package/dist/template/src/client/update-audience-editor.tsx +597 -206
  138. package/dist/template/src/client/update-policy-editor.test.ts +101 -29
  139. package/dist/template/src/client/update-policy-editor.tsx +454 -320
  140. package/dist/template/src/client/use-filtered-results.ts +55 -0
  141. package/dist/template/src/server/controllers/manifest.test.ts +25 -3
  142. package/dist/template/src/server/controllers/manifest.ts +1 -2
  143. package/dist/template/src/server/devices/audience.ts +9 -5
  144. package/dist/template/src/server/lib/admin-audience-activation.test.ts +37 -90
  145. package/dist/template/src/server/lib/admin-release-history.test.ts +138 -0
  146. package/dist/template/src/server/lib/admin-updates.ts +160 -534
  147. package/dist/template/src/server/lib/distribution-history.ts +97 -0
  148. package/dist/template/src/server/lib/supabase.js +24 -0
  149. package/dist/template/src/server/lib/supabase.test.ts +38 -1
  150. package/dist/template/src/server/lib/update-policy.test.ts +20 -0
  151. package/dist/template/src/server/lib/update-policy.ts +23 -10
  152. package/dist/template/src/server/manifest/manifest-repository.ts +2 -2
  153. package/dist/template/src/server/manifest/manifest-values.test.ts +2 -0
  154. package/dist/template/src/server/manifest/manifest-values.ts +21 -13
  155. package/dist/template/templates/expo-app/scripts/ota-publish/api/database-client.mjs +7 -30
  156. package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +2 -1
  157. package/dist/template/tsconfig.json +2 -2
  158. package/dist/template-manifest.json +445 -300
  159. package/package.json +1 -1
  160. package/dist/template/scripts/lib/device-identity.test.ts +0 -29
  161. package/dist/template/scripts/lib/ota-client.test.ts +0 -55
  162. package/dist/template/scripts/lib/ota-update-controller.test.ts +0 -232
  163. package/dist/template/scripts/lib/ota-updates-ui.test.tsx +0 -154
  164. package/dist/template/scripts/tests/ota-client-types.mjs +0 -69
  165. package/dist/template/templates/expo-app/ota-client/README.md +0 -73
  166. package/dist/template/templates/expo-app/ota-client/controller.ts +0 -107
  167. package/dist/template/templates/expo-app/ota-client/device-identity.ts +0 -48
  168. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +0 -61
  169. package/dist/template/templates/expo-app/ota-client/index.ts +0 -16
  170. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.ts +0 -97
  171. package/dist/template/templates/expo-app/ota-client/model/update-controller.ts +0 -293
  172. package/dist/template/templates/expo-app/ota-client/runtime.ts +0 -153
  173. package/dist/template/templates/expo-app/ota-client/types.ts +0 -85
  174. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.tsx +0 -25
  175. package/dist/template/templates/expo-app/ota-client/ui/ota-updates.tsx +0 -196
@@ -6,8 +6,9 @@ import {
6
6
  UpdatePolicyValidationError,
7
7
  validateUpdatePolicy,
8
8
  } from "./update-policy";
9
- import { getManifestAppVersion } from "../manifest/manifest-values";
9
+ import { getManifestAppVersion, getAppVersionFromFields } from "../manifest/manifest-values";
10
10
  import { assertOtaDistributionAllowed } from "./distribution-control";
11
+ import { changeDistribution } from "./distribution-history";
11
12
 
12
13
  type UpdateStatus = "active" | "disabled";
13
14
 
@@ -62,6 +63,37 @@ export type OtaChannelRow = {
62
63
  modified_at: string;
63
64
  };
64
65
 
66
+ const listColumns = [
67
+ "id",
68
+ "update_id",
69
+ "comment",
70
+ "runtime_version",
71
+ "channel",
72
+ "platform",
73
+ "created_at",
74
+ "created_at_path",
75
+ "storage_base_path",
76
+ "is_active",
77
+ "audience_mode",
78
+ "assets_count",
79
+ "launch_asset_path",
80
+ "delivery_mode",
81
+ "guard_action",
82
+ "policy_version",
83
+ "policy_published_at",
84
+ ] as const;
85
+ type ListRow = Pick<OtaUpdateRow, (typeof listColumns)[number]>;
86
+ type ListChannel = Pick<
87
+ OtaChannelRow,
88
+ | "id"
89
+ | "runtime_version"
90
+ | "channel"
91
+ | "platform"
92
+ | "latest_update_id"
93
+ | "active_update_id"
94
+ >;
95
+ type VersionProjection = { app_version: unknown; legacy_version: unknown };
96
+
65
97
  export type UpdateRecord = {
66
98
  key: string;
67
99
  encodedKey: string;
@@ -95,6 +127,7 @@ export type UpdateRecord = {
95
127
  };
96
128
 
97
129
  export type UpdateDetail = UpdateRecord & {
130
+ isNewestInScope: boolean;
98
131
  updateInfo: Record<string, unknown>;
99
132
  updateMeta: UpdateMetaState;
100
133
  metadata: Record<string, unknown> | null;
@@ -117,6 +150,12 @@ type ListOptions = {
117
150
  pageSize: number;
118
151
  sortBy: SortField;
119
152
  order: SortOrder;
153
+ q?: string;
154
+ platform?: string;
155
+ channel?: string;
156
+ runtime?: string;
157
+ status?: string;
158
+ audience?: string;
120
159
  };
121
160
 
122
161
  type Scope = {
@@ -157,7 +196,7 @@ function extractUpdateIdFromKey(key: string): string {
157
196
  return tail;
158
197
  }
159
198
 
160
- function makeUpdateKey(row: OtaUpdateRow): string {
199
+ function makeUpdateKey(row: ListRow): string {
161
200
  return `${row.runtime_version}/${row.platform}/${row.channel}/${row.update_id}`;
162
201
  }
163
202
 
@@ -216,8 +255,9 @@ async function getNewestUpdateByScope(
216
255
  }
217
256
 
218
257
  export function mapRowToRecord(
219
- row: OtaUpdateRow,
220
- channel: OtaChannelRow | null,
258
+ row: ListRow & { manifest?: unknown },
259
+ channel: ListChannel | null,
260
+ appVersion = getManifestAppVersion(row.manifest),
221
261
  ): UpdateRecord {
222
262
  const key = makeUpdateKey(row);
223
263
  const isLatest = channel?.latest_update_id === row.update_id;
@@ -234,7 +274,7 @@ export function mapRowToRecord(
234
274
  return {
235
275
  key,
236
276
  encodedKey: encodeUpdateKey(row.update_id),
237
- appVersion: getManifestAppVersion(row.manifest),
277
+ appVersion,
238
278
  comment: row.comment,
239
279
  runtimeVersion: row.runtime_version,
240
280
  platform: row.platform,
@@ -256,7 +296,7 @@ export function mapRowToRecord(
256
296
  isIgnoredByRollback,
257
297
  launchAssetPath: row.launch_asset_path,
258
298
  assetsCount: row.assets_count,
259
- deliveryMode: row.delivery_mode === "background" ? "background" : "manual",
299
+ deliveryMode: row.delivery_mode === "background" || row.delivery_mode === "manual-postpone" ? row.delivery_mode : "manual",
260
300
  hasGuard:
261
301
  typeof row.guard_action === "string" && row.guard_action.length > 0,
262
302
  policyVersion:
@@ -496,94 +536,6 @@ async function getChannelRow(scope: Scope): Promise<OtaChannelRow | null> {
496
536
  return (data as OtaChannelRow | null) || null;
497
537
  }
498
538
 
499
- async function upsertChannelRow(
500
- scope: Scope,
501
- payload: Partial<OtaChannelRow>,
502
- ): Promise<OtaChannelRow> {
503
- // INSERT ... ON CONFLICT runs INSERT guards before checking the conflict.
504
- // Update an existing scope directly so incident deactivation cleanup can be
505
- // validated against OLD pointers while the global switch is blocked.
506
- const existing = await supabase
507
- .from("ota_update_channels")
508
- .update(payload)
509
- .eq("runtime_version", scope.runtimeVersion)
510
- .eq("channel", scope.channel)
511
- .eq("platform", scope.platform)
512
- .select("*")
513
- .maybeSingle();
514
- if (existing.error) {
515
- throw new Error(`Failed to update ota_update_channels row: ${existing.error.message}`);
516
- }
517
- if (existing.data) return existing.data as OtaChannelRow;
518
-
519
- const { data, error } = await supabase
520
- .from("ota_update_channels")
521
- .upsert(
522
- {
523
- runtime_version: scope.runtimeVersion,
524
- channel: scope.channel,
525
- platform: scope.platform,
526
- ...payload,
527
- },
528
- {
529
- onConflict: "runtime_version,channel,platform",
530
- },
531
- )
532
- .select("*")
533
- .single();
534
-
535
- if (error || !data) {
536
- throw new Error(
537
- `Failed to upsert ota_update_channels row: ${error?.message}`,
538
- );
539
- }
540
-
541
- return data as OtaChannelRow;
542
- }
543
-
544
- async function clearRollbackForOtherRuntimes(scope: Scope) {
545
- const { error } = await supabase
546
- .from("ota_update_channels")
547
- .update({
548
- active_update_id: null,
549
- active_changed_at: new Date().toISOString(),
550
- })
551
- .eq("channel", scope.channel)
552
- .eq("platform", scope.platform)
553
- .neq("runtime_version", scope.runtimeVersion)
554
- .not("active_update_id", "is", null)
555
- .execute();
556
-
557
- if (error) {
558
- throw new Error(
559
- `Failed to clear rollback for other runtimes: ${error.message}`,
560
- );
561
- }
562
- }
563
-
564
- async function getLatestRuntimeForChannelPlatform(params: {
565
- channel: string;
566
- platform: "ios" | "android";
567
- }): Promise<string | null> {
568
- const { data, error } = await supabase
569
- .from("ota_update_channels")
570
- .select("runtime_version, latest_created_at")
571
- .eq("channel", params.channel)
572
- .eq("platform", params.platform)
573
- .not("latest_update_id", "is", null)
574
- .order("latest_created_at", { ascending: false, nullsFirst: false })
575
- .limit(1)
576
- .maybeSingle();
577
-
578
- if (error) {
579
- throw new Error(
580
- `Failed to resolve latest runtime for channel/platform: ${error.message}`,
581
- );
582
- }
583
-
584
- return data?.runtime_version || null;
585
- }
586
-
587
539
  async function getUpdateRowById(updateId: string): Promise<OtaUpdateRow> {
588
540
  const { data, error } = await supabase
589
541
  .from("ota_updates")
@@ -598,25 +550,7 @@ async function getUpdateRowById(updateId: string): Promise<OtaUpdateRow> {
598
550
  return data as OtaUpdateRow;
599
551
  }
600
552
 
601
- async function getUpdateRowsByScope(scope: Scope): Promise<OtaUpdateRow[]> {
602
- const { data, error } = await supabase
603
- .from("ota_updates")
604
- .select("*")
605
- .eq("runtime_version", scope.runtimeVersion)
606
- .eq("channel", scope.channel)
607
- .eq("platform", scope.platform)
608
- .order("created_at", { ascending: false })
609
- .order("update_id", { ascending: false })
610
- .execute();
611
-
612
- if (error) {
613
- throw new Error(`Failed to load updates by scope: ${error.message}`);
614
- }
615
-
616
- return (data || []) as OtaUpdateRow[];
617
- }
618
-
619
- function makeScopeFromRow(row: OtaUpdateRow): Scope {
553
+ function makeScopeFromRow(row: ListRow): Scope {
620
554
  return {
621
555
  runtimeVersion: row.runtime_version,
622
556
  channel: row.channel,
@@ -624,64 +558,6 @@ function makeScopeFromRow(row: OtaUpdateRow): Scope {
624
558
  };
625
559
  }
626
560
 
627
- async function recalculateChannelPointers(scope: Scope) {
628
- const rows = await getUpdateRowsByScope(scope);
629
- const latestActive = rows.find((row) => row.is_active) || null;
630
-
631
- const existingChannelRow = await getChannelRow(scope);
632
- const existingRollbackId = existingChannelRow?.active_update_id || null;
633
- const hasValidRollback =
634
- Boolean(existingRollbackId) &&
635
- existingRollbackId !== latestActive?.update_id &&
636
- rows.some((row) => row.update_id === existingRollbackId && row.is_active);
637
-
638
- const nextRollbackId = hasValidRollback ? existingRollbackId : null;
639
- const now = new Date().toISOString();
640
-
641
- const payload: Partial<OtaChannelRow> = {
642
- latest_update_id: latestActive?.update_id || null,
643
- latest_created_at: latestActive?.created_at || null,
644
- latest_created_at_path: latestActive?.created_at_path || null,
645
- active_update_id: nextRollbackId,
646
- active_changed_at:
647
- nextRollbackId !== (existingChannelRow?.active_update_id || null)
648
- ? now
649
- : existingChannelRow?.active_changed_at || now,
650
- };
651
-
652
- const channelRow = await upsertChannelRow(scope, payload);
653
- return { channelRow, latestActive, rollbackId: nextRollbackId };
654
- }
655
-
656
- async function assignRollbackForScope(
657
- scope: Scope,
658
- rollbackUpdateId: string | null,
659
- ) {
660
- const rows = await getUpdateRowsByScope(scope);
661
- const latestActive = rows.find((row) => row.is_active) || null;
662
-
663
- const validRollback =
664
- rollbackUpdateId &&
665
- rows.some((row) => row.update_id === rollbackUpdateId && row.is_active)
666
- ? rollbackUpdateId
667
- : null;
668
-
669
- const normalizedRollback =
670
- validRollback && validRollback !== latestActive?.update_id
671
- ? validRollback
672
- : null;
673
-
674
- const channelRow = await upsertChannelRow(scope, {
675
- latest_update_id: latestActive?.update_id || null,
676
- latest_created_at: latestActive?.created_at || null,
677
- latest_created_at_path: latestActive?.created_at_path || null,
678
- active_update_id: normalizedRollback,
679
- active_changed_at: new Date().toISOString(),
680
- });
681
-
682
- return { channelRow, latestActive, rollbackId: normalizedRollback };
683
- }
684
-
685
561
  function extractMetadataFromManifest(
686
562
  manifest: Record<string, unknown>,
687
563
  ): Record<string, unknown> | null {
@@ -692,37 +568,6 @@ function extractMetadataFromManifest(
692
568
  return null;
693
569
  }
694
570
 
695
- function parseUpdateMetaContent(content: Record<string, unknown>): {
696
- is_active: boolean;
697
- updated_at: string;
698
- disabled_at: string | null;
699
- } {
700
- const now = new Date().toISOString();
701
- const nextIsActive = content.isActive !== false;
702
-
703
- return {
704
- is_active: nextIsActive,
705
- updated_at: now,
706
- disabled_at: nextIsActive ? null : now,
707
- };
708
- }
709
-
710
- function buildLatestPayload(row: OtaUpdateRow, reason: string) {
711
- return {
712
- id: row.update_id,
713
- updateId: row.update_id,
714
- buildId: row.build_id,
715
- runtimeVersion: row.runtime_version,
716
- channel: row.channel,
717
- platform: row.platform,
718
- createdAt: row.created_at,
719
- createdAtPath: row.created_at_path,
720
- isActive: row.is_active,
721
- updatedAt: row.updated_at,
722
- reason,
723
- };
724
- }
725
-
726
571
  export function encodeUpdateKey(value: string): string {
727
572
  return Buffer.from(value, "utf-8").toString("base64url");
728
573
  }
@@ -737,66 +582,114 @@ export function parseUpdateKey(key: string) {
737
582
  };
738
583
  }
739
584
 
740
- export async function getUpdatesPage(options: ListOptions) {
741
- const { data, error } = await supabase
742
- .from("ota_updates")
743
- .select("*")
744
- .order("created_at", { ascending: false })
745
- .order("update_id", { ascending: false })
746
- .execute();
747
-
748
- if (error) {
749
- throw new Error(`Failed to fetch ota_updates: ${error.message}`);
585
+ // A server may cap each PostgREST response below our requested batch size.
586
+ // Advance on the unique indexed key until the next query is empty.
587
+ async function* readHistory<T extends { id: string | number }>(
588
+ table: "ota_updates" | "ota_update_channels",
589
+ columns: string,
590
+ ) {
591
+ let cursor: string | number | undefined;
592
+ for (;;) {
593
+ const query = supabase.from(table).select(columns).order("id").limit(200);
594
+ if (cursor !== undefined) query.gt("id", cursor);
595
+ const { data, error } = await query.execute();
596
+ if (error) throw new Error(`Failed to fetch ${table}: ${error.message}`);
597
+ const rows = (data ?? []) as T[];
598
+ if (!rows.length) return;
599
+ yield rows;
600
+ cursor = rows[rows.length - 1].id;
750
601
  }
602
+ }
751
603
 
752
- const rows = (data || []) as OtaUpdateRow[];
753
- const scopeKeys = Array.from(
754
- new Set(
755
- rows.map(
756
- (row) => `${row.runtime_version}::${row.channel}::${row.platform}`,
757
- ),
758
- ),
759
- );
604
+ function scopeKey(
605
+ row: Pick<OtaUpdateRow, "runtime_version" | "channel" | "platform">,
606
+ ) {
607
+ return JSON.stringify([row.runtime_version, row.channel, row.platform]);
608
+ }
760
609
 
761
- const channelsByScope = new Map<string, OtaChannelRow | null>();
762
- await Promise.all(
763
- scopeKeys.map(async (scopeKey) => {
764
- const [runtimeVersion, channel, platform] = scopeKey.split("::");
765
- const channelRow = await getChannelRow({
766
- runtimeVersion,
767
- channel,
768
- platform: platform as "ios" | "android",
769
- });
770
- channelsByScope.set(scopeKey, channelRow);
771
- }),
610
+ function matchesRelease(
611
+ item: UpdateRecord,
612
+ options: ListOptions,
613
+ search: string,
614
+ ) {
615
+ if (options.platform && item.platform !== options.platform) return false;
616
+ if (options.channel && item.channel !== options.channel) return false;
617
+ if (options.runtime && item.runtimeVersion !== options.runtime) return false;
618
+ if (options.audience && item.audienceMode !== options.audience) return false;
619
+ if (options.status === "rollback") {
620
+ if (!item.isRollbackActive) return false;
621
+ } else if (
622
+ options.status &&
623
+ options.status !== (item.policyEditable ? "draft" : item.status)
624
+ ) {
625
+ return false;
626
+ }
627
+ return (
628
+ !search ||
629
+ [
630
+ item.comment,
631
+ item.updateId,
632
+ item.appVersion,
633
+ item.runtimeVersion,
634
+ item.channel,
635
+ ].some((value) => value?.toLowerCase().includes(search))
772
636
  );
637
+ }
773
638
 
774
- const allUpdates = rows.map((row) => {
775
- const scopeKey = `${row.runtime_version}::${row.channel}::${row.platform}`;
776
- const channelRow = channelsByScope.get(scopeKey) || null;
777
- return mapRowToRecord(row, channelRow);
778
- });
639
+ export async function getUpdatesPage(options: ListOptions) {
640
+ const search = options.q?.trim().toLowerCase() || "";
641
+ const channelsByScope = new Map<string, ListChannel>();
642
+ for await (const batch of readHistory<ListChannel>(
643
+ "ota_update_channels",
644
+ "id,runtime_version,channel,platform,latest_update_id,active_update_id",
645
+ )) {
646
+ for (const channel of batch)
647
+ channelsByScope.set(scopeKey(channel), channel);
648
+ }
649
+
650
+ const matching: UpdateRecord[] = [];
651
+ const scopes = new Map<string, Scope>();
652
+ const channels = new Set<string>();
653
+ const runtimes = new Set<string>();
654
+ const columns = [
655
+ ...listColumns,
656
+ "app_version:manifest->extra->expoClient->version",
657
+ "legacy_version:manifest->expoClient->version",
658
+ ].join(",");
659
+ for await (const batch of readHistory<ListRow & VersionProjection>(
660
+ "ota_updates",
661
+ columns,
662
+ )) {
663
+ for (const row of batch) {
664
+ const key = scopeKey(row);
665
+ scopes.set(key, makeScopeFromRow(row));
666
+ channels.add(row.channel);
667
+ runtimes.add(row.runtime_version);
668
+ const item = mapRowToRecord(
669
+ row,
670
+ channelsByScope.get(key) ?? null,
671
+ getAppVersionFromFields(row.app_version, row.legacy_version),
672
+ );
673
+ if (matchesRelease(item, options, search)) matching.push(item);
674
+ }
675
+ }
779
676
 
780
- const rollbackLockByScope = scopeKeys.map((scopeKey) => {
781
- const [runtimeVersion, channel, platform] = scopeKey.split("::");
782
- const channelRow = channelsByScope.get(scopeKey) || null;
677
+ const rollbackLockByScope = Array.from(scopes, ([key, scope]) => {
678
+ const channel = channelsByScope.get(key);
783
679
  const rollbackActive =
784
- Boolean(channelRow?.active_update_id) &&
785
- channelRow?.active_update_id !== channelRow?.latest_update_id;
786
-
680
+ Boolean(channel?.active_update_id) &&
681
+ channel?.active_update_id !== channel?.latest_update_id;
787
682
  return {
788
- scopeKey,
789
- runtimeVersion,
790
- channel,
791
- platform: platform as "ios" | "android",
683
+ ...scope,
684
+ scopeKey: `${scope.runtimeVersion}::${scope.channel}::${scope.platform}`,
792
685
  rollbackActive,
793
686
  autoDeliveryEnabled: !rollbackActive,
794
- activeUpdateId: channelRow?.active_update_id || null,
795
- latestUpdateId: channelRow?.latest_update_id || null,
687
+ activeUpdateId: channel?.active_update_id ?? null,
688
+ latestUpdateId: channel?.latest_update_id ?? null,
796
689
  };
797
690
  });
798
691
 
799
- const sorted = sortUpdates(allUpdates, options.sortBy, options.order);
692
+ const sorted = sortUpdates(matching, options.sortBy, options.order);
800
693
  const total = sorted.length;
801
694
  const totalPages = Math.max(1, Math.ceil(total / options.pageSize));
802
695
  const page = Math.min(Math.max(1, options.page), totalPages);
@@ -805,6 +698,7 @@ export async function getUpdatesPage(options: ListOptions) {
805
698
 
806
699
  return {
807
700
  items: sorted.slice(start, end),
701
+ filters: { channels: [...channels].sort(), runtimes: [...runtimes].sort() },
808
702
  total,
809
703
  page,
810
704
  pageSize: options.pageSize,
@@ -830,6 +724,7 @@ export async function getUpdateDetailByKey(key: string): Promise<UpdateDetail> {
830
724
 
831
725
  return {
832
726
  ...record,
727
+ isNewestInScope: newestRow?.update_id === row.update_id,
833
728
  updateInfo: manifest,
834
729
  updateMeta: mapUpdateMeta(row),
835
730
  metadata: extractMetadataFromManifest(manifest),
@@ -846,19 +741,16 @@ export async function deleteUpdateByKey(
846
741
  ): Promise<{ removedFiles: number }> {
847
742
  const updateId = extractUpdateIdFromKey(key);
848
743
  const row = await getUpdateRowById(updateId);
849
- const scope = makeScopeFromRow(row);
850
-
851
- // Repair serving pointers before FK cleanup erases the retired target. This
852
- // also keeps deletion available during a global stop with a public fallback,
853
- // and stops new manifests referencing assets that are about to be removed.
854
- await setUpdateDisabledByKey(updateId, true);
744
+ // Retire the row under the distribution lock before removing its assets,
745
+ // so it cannot be restored concurrently while storage cleanup is in flight.
746
+ await changeDistribution(updateId, "retire");
855
747
 
856
748
  let removedFiles = 0;
857
749
  const bucket = row.storage_bucket || SUPABASE_BUCKET;
858
750
  const basePath = toPosixPath(row.storage_base_path || "");
859
751
 
860
752
  if (basePath) {
861
- const files = await listAllFilesRecursive(bucket, basePath).catch(() => []);
753
+ const files = await listAllFilesRecursive(bucket, basePath);
862
754
  removedFiles = files.length;
863
755
 
864
756
  if (files.length > 0) {
@@ -873,18 +765,7 @@ export async function deleteUpdateByKey(
873
765
  }
874
766
  }
875
767
 
876
- const { error: deleteError } = await supabase
877
- .from("ota_updates")
878
- .delete()
879
- .eq("update_id", updateId)
880
- .execute();
881
-
882
- if (deleteError) {
883
- throw new Error(`Failed to delete ota_updates row: ${deleteError.message}`);
884
- }
885
-
886
- await recalculateChannelPointers(scope);
887
-
768
+ await changeDistribution(updateId, "delete");
888
769
  return { removedFiles };
889
770
  }
890
771
 
@@ -912,7 +793,6 @@ export async function updateJsonFileByKey(
912
793
 
913
794
  const updateId = extractUpdateIdFromKey(key);
914
795
  const row = await getUpdateRowById(updateId);
915
- const scope = makeScopeFromRow(row);
916
796
 
917
797
  if (fileName === "update-info.json") {
918
798
  const assets = Array.isArray(content.assets) ? content.assets : [];
@@ -967,24 +847,9 @@ export async function updateJsonFileByKey(
967
847
  }
968
848
 
969
849
  if (fileName === "update-meta.json") {
970
- const parsedMeta = parseUpdateMetaContent(content);
971
-
972
- const { error } = await supabase
973
- .from("ota_updates")
974
- .update({
975
- ...parsedMeta,
976
- ...(parsedMeta.is_active && !row.policy_published_at
977
- ? { policy_published_at: parsedMeta.updated_at }
978
- : {}),
979
- })
980
- .eq("update_id", updateId)
981
- .execute();
982
-
983
- if (error) {
984
- throw new Error(`Failed to update ota meta fields: ${error.message}`);
985
- }
986
-
987
- await recalculateChannelPointers(scope);
850
+ if (typeof content.isActive !== "boolean")
851
+ throw new Error("update-meta.json requires an explicit boolean isActive.");
852
+ await changeDistribution(updateId, content.isActive ? "activate" : "stop");
988
853
  return { path: `${row.storage_base_path}/update-meta.json` };
989
854
  }
990
855
 
@@ -1001,25 +866,9 @@ export async function updateJsonFileByKey(
1001
866
  }
1002
867
 
1003
868
  const channelTarget = await getUpdateRowById(channelTargetIdRaw);
1004
- const channelScope = makeScopeFromRow(channelTarget);
1005
- const currentChannelRow = await getChannelRow(channelScope);
1006
- const rollbackActive =
1007
- Boolean(currentChannelRow?.active_update_id) &&
1008
- currentChannelRow?.active_update_id !== currentChannelRow?.latest_update_id;
1009
-
1010
- if (rollbackActive) {
1011
- throw new Error(
1012
- "Rollback is active. New updates are ignored until rollback is disabled via Promote.",
1013
- );
1014
- }
1015
-
1016
- await upsertChannelRow(channelScope, {
1017
- latest_update_id: channelTarget.update_id,
1018
- latest_created_at: channelTarget.created_at,
1019
- latest_created_at_path: channelTarget.created_at_path,
1020
- active_update_id: null,
1021
- active_changed_at: new Date().toISOString(),
1022
- });
869
+ if (scopeKey(channelTarget) !== scopeKey(row))
870
+ throw new Error("The channel target must belong to the same scope.");
871
+ await changeDistribution(channelTarget.update_id, "select-latest");
1023
872
 
1024
873
  return {
1025
874
  path: `${channelTarget.runtime_version}/${channelTarget.platform}/channels/${channelTarget.channel}/latest.json`,
@@ -1031,241 +880,18 @@ export async function rollbackToUpdateByKey(
1031
880
  options?: RollbackOptions,
1032
881
  ) {
1033
882
  await assertOtaDistributionAllowed();
1034
- const updateId = extractUpdateIdFromKey(key);
1035
- const row = await getUpdateRowById(updateId);
1036
- const scope = makeScopeFromRow(row);
1037
- const now = new Date().toISOString();
1038
-
1039
- const latestRuntime = await getLatestRuntimeForChannelPlatform({
1040
- channel: row.channel,
1041
- platform: row.platform,
1042
- });
1043
-
1044
- if (latestRuntime && latestRuntime !== row.runtime_version) {
1045
- throw new Error(
1046
- `Rollback is allowed only for runtimeVersion=${latestRuntime}. Selected update runtimeVersion=${row.runtime_version}`,
1047
- );
1048
- }
1049
-
1050
- const currentChannel = await getChannelRow(scope);
1051
- const currentServedUpdateId =
1052
- currentChannel?.active_update_id ||
1053
- currentChannel?.latest_update_id ||
1054
- null;
1055
-
1056
- if (!currentServedUpdateId) {
1057
- throw new Error(
1058
- "Rollback is not available: no active update is currently served for this scope.",
1059
- );
1060
- }
1061
-
1062
- if (currentServedUpdateId === updateId) {
1063
- throw new Error(
1064
- "Rollback is not available for the currently served update.",
1065
- );
1066
- }
1067
-
1068
- const currentServedRow = await getUpdateRowById(currentServedUpdateId);
1069
- if (!currentServedRow.is_active) {
1070
- throw new Error(
1071
- "Rollback is not available: currently served update is not active.",
1072
- );
1073
- }
1074
-
1075
- const currentServedCreatedAt = parseDate(
1076
- currentServedRow.created_at || currentServedRow.created_at_path,
1077
- );
1078
- const targetCreatedAt = parseDate(row.created_at || row.created_at_path);
1079
- if (currentServedCreatedAt <= targetCreatedAt) {
1080
- throw new Error(
1081
- "Rollback is allowed only when a newer active update exists in the same scope.",
1082
- );
1083
- }
1084
-
1085
- // The database atomically applies audience-aware peer deactivation.
1086
-
1087
- const { error: activationError } = await supabase
1088
- .from("ota_updates")
1089
- .update({
1090
- is_active: true,
1091
- updated_at: now,
1092
- disabled_at: null,
1093
- policy_published_at: row.policy_published_at || now,
1094
- })
1095
- .eq("update_id", updateId)
1096
- .execute();
1097
-
1098
- if (activationError) {
1099
- throw new Error(
1100
- `Failed to activate rollback target: ${activationError.message}`,
1101
- );
1102
- }
1103
-
1104
- await supabase
1105
- .from("ota_updates")
1106
- .update({
1107
- rolled_back_from_update_id:
1108
- currentServedUpdateId && currentServedUpdateId !== updateId
1109
- ? currentServedUpdateId
1110
- : null,
1111
- updated_at: now,
1112
- })
1113
- .eq("update_id", updateId)
1114
- .execute();
1115
-
1116
- const refreshed = await getUpdateRowById(updateId);
1117
- const newestRow = await getNewestUpdateByScope(scope);
1118
- const rollbackLatestRow = newestRow || currentServedRow;
1119
-
1120
- await clearRollbackForOtherRuntimes(scope);
1121
-
1122
- const channelRow = await upsertChannelRow(scope, {
1123
- // Keep latest pointer on the newest update in scope.
1124
- latest_update_id: rollbackLatestRow.update_id,
1125
- latest_created_at: rollbackLatestRow.created_at,
1126
- latest_created_at_path: rollbackLatestRow.created_at_path,
1127
- // Enable rollback mode by pinning active pointer to an older update.
1128
- active_update_id: refreshed.update_id,
1129
- active_changed_at: now,
1130
- });
1131
-
1132
- return {
1133
- ...buildLatestPayload(refreshed, options?.reason || "rollback"),
1134
- activeChangedAt: channelRow.active_changed_at,
1135
- rollbackAssigned:
1136
- Boolean(channelRow.active_update_id) &&
1137
- channelRow.active_update_id !== channelRow.latest_update_id,
1138
- };
883
+ const result = await changeDistribution(extractUpdateIdFromKey(key), "rollback");
884
+ return { ...result, reason: options?.reason || "rollback" };
1139
885
  }
1140
886
 
1141
887
  export async function promoteLatestByKey(key: string) {
1142
888
  await assertOtaDistributionAllowed();
1143
- const updateId = extractUpdateIdFromKey(key);
1144
- const row = await getUpdateRowById(updateId);
1145
- const scope = makeScopeFromRow(row);
1146
-
1147
- const channelRow = await getChannelRow(scope);
1148
- const latestUpdateId = channelRow?.latest_update_id || null;
1149
- const rollbackActive =
1150
- Boolean(channelRow?.active_update_id) &&
1151
- channelRow?.active_update_id !== channelRow?.latest_update_id;
1152
-
1153
- if (!latestUpdateId) {
1154
- throw new Error("Cannot promote: latest update is not set for this scope.");
1155
- }
1156
-
1157
- if (latestUpdateId !== row.update_id) {
1158
- throw new Error("Promote is allowed only on the latest update.");
1159
- }
1160
-
1161
- if (!rollbackActive) {
1162
- throw new Error("Promote is not available because rollback is not active.");
1163
- }
1164
-
1165
- const promoteNow = new Date().toISOString();
1166
-
1167
- // Keep audience selection and peer deactivation in the activation statement.
1168
-
1169
- const { error: activateLatestError } = await supabase
1170
- .from("ota_updates")
1171
- .update({
1172
- is_active: true,
1173
- updated_at: promoteNow,
1174
- disabled_at: null,
1175
- policy_published_at: row.policy_published_at || promoteNow,
1176
- })
1177
- .eq("update_id", latestUpdateId)
1178
- .execute();
1179
-
1180
- if (activateLatestError) {
1181
- throw new Error(
1182
- `Failed to activate latest update during promote: ${activateLatestError.message}`,
1183
- );
1184
- }
1185
-
1186
- const updatedChannel = await upsertChannelRow(scope, {
1187
- latest_update_id: channelRow?.latest_update_id || row.update_id,
1188
- latest_created_at: channelRow?.latest_created_at || row.created_at,
1189
- latest_created_at_path:
1190
- channelRow?.latest_created_at_path || row.created_at_path,
1191
- active_update_id: null,
1192
- active_changed_at: promoteNow,
1193
- });
1194
-
1195
- return {
1196
- promoted: true,
1197
- latestUpdateId: updatedChannel.latest_update_id,
1198
- activeUpdateId: updatedChannel.active_update_id,
1199
- rollbackActive: false,
1200
- };
889
+ return changeDistribution(extractUpdateIdFromKey(key), "promote");
1201
890
  }
1202
891
 
1203
892
  export async function setUpdateDisabledByKey(key: string, disabled: boolean) {
1204
- if (!disabled) {
1205
- await assertOtaDistributionAllowed();
1206
- }
1207
- const updateId = extractUpdateIdFromKey(key);
1208
- const row = await getUpdateRowById(updateId);
1209
- const scope = makeScopeFromRow(row);
1210
- const now = new Date().toISOString();
1211
-
1212
- const scopeChannelRow = await getChannelRow(scope);
1213
- const rollbackActive =
1214
- Boolean(scopeChannelRow?.active_update_id) &&
1215
- scopeChannelRow?.active_update_id !== scopeChannelRow?.latest_update_id;
1216
- const newestRow = await getNewestUpdateByScope(scope);
1217
- const isNewestInScope = newestRow?.update_id === updateId;
1218
-
1219
- if (!disabled) {
1220
- if (!isNewestInScope) {
1221
- throw new Error(
1222
- "Direct activation is allowed only for the newest update in scope. Use Rollback for older updates.",
1223
- );
1224
- }
1225
-
1226
- if (rollbackActive) {
1227
- throw new Error(
1228
- "Direct activation is unavailable while rollback mode is active. Use Promote on the newest update.",
1229
- );
1230
- }
1231
-
1232
- // Peer deactivation is performed atomically by the database trigger.
1233
- }
1234
-
1235
- const { error } = await supabase
1236
- .from("ota_updates")
1237
- .update({
1238
- is_active: !disabled,
1239
- updated_at: now,
1240
- disabled_at: disabled ? now : null,
1241
- ...(!disabled && !row.policy_published_at
1242
- ? { policy_published_at: now }
1243
- : {}),
1244
- })
1245
- .eq("update_id", updateId)
1246
- .execute();
1247
-
1248
- if (error) {
1249
- throw new Error(`Failed to change update active state: ${error.message}`);
1250
- }
1251
-
1252
- const currentChannel = await getChannelRow(scope);
1253
- const shouldClearRollback =
1254
- disabled && currentChannel?.active_update_id === updateId;
1255
-
1256
- const { channelRow, latestActive, rollbackId } = shouldClearRollback
1257
- ? await assignRollbackForScope(scope, null)
1258
- : await recalculateChannelPointers(scope);
1259
-
1260
- return {
1261
- updated: true,
1262
- disabled,
1263
- state: disabled ? "disabled" : "active",
1264
- fallbackApplied: Boolean(latestActive),
1265
- activeUpdateId: channelRow.active_update_id,
1266
- latestUpdateId: channelRow.latest_update_id,
1267
- rollbackActive: Boolean(rollbackId),
1268
- };
893
+ if (!disabled) await assertOtaDistributionAllowed();
894
+ return changeDistribution(extractUpdateIdFromKey(key), disabled ? "stop" : "activate");
1269
895
  }
1270
896
 
1271
897
  export function normalizeSortBy(value: string | null): SortField {