@linked.cm/capacitor 1.0.0 → 1.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # @linked.cm/capacitor
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#28](https://github.com/linked-cm/capacitor/pull/28) [`c8b735a`](https://github.com/linked-cm/capacitor/commit/c8b735a276431afc3a62e980d13c0f2ae0d266c0) Thanks [@abdipramana](https://github.com/abdipramana)! - Add a presentation-free release-control engine that apps can adopt without coupling to a specific product status API.
8
+
9
+ **New exports**
10
+
11
+ - `@linked.cm/capacitor/hooks/useMandatoryNativeUpdate` — compare the installed iOS/Android binary to an app-supplied minimum, recheck on foreground/minimum changes, and open the store update flow
12
+ - `@linked.cm/capacitor/hooks/useReleaseGate` — inject `loadStatus`, apply maintenance first, enforce the native minimum second, and expose `otaEnabled`
13
+ - `@linked.cm/capacitor/utils/releaseStatus` — shared `ReleaseStatus` types plus `normalizeReleaseStatus` / `tryNormalizeReleaseStatus` / `pickReleaseStatus`
14
+ - `@linked.cm/capacitor/utils/releaseStatusCache` — injected `ReleaseStatusCache` with last-valid retention and `createReleaseStatusHandler`
15
+ - `@linked.cm/capacitor/utils/releaseStatusClient` — deduped `/status` client with last-valid fallback
16
+
17
+ **`useAutomaticUpdates` options (backward compatible defaults)**
18
+
19
+ - `enabled` (default `true`) — while `false`, still calls `notifyAppReady()`, but skips channel/health/store/OTA work
20
+ - `checkNativeStoreVersion` (default `true`) — disable when a mandatory native gate already owns store updates
21
+
22
+ **Typical composition**
23
+
24
+ ```ts
25
+ const gate = useReleaseGate({
26
+ loadStatus: () => statusClient.load(), // must return normalized ReleaseStatus
27
+ fallbackMinimumVersion: COMPILED_MINIMUM_NATIVE_VERSION,
28
+ });
29
+
30
+ useAutomaticUpdates({
31
+ enabled: gate.otaEnabled,
32
+ checkNativeStoreVersion: false,
33
+ });
34
+ ```
35
+
36
+ Server caches must call `load()` then `start()`, and `stop()` on dispose. See the package README for full examples.
37
+
3
38
  ## 1.0.0
4
39
 
5
40
  ### Major Changes
@@ -20,7 +20,17 @@ export type UseAutomaticUpdatesState = {
20
20
  retryOTA: () => void;
21
21
  retryMaintenanceCheck: () => void;
22
22
  };
23
+ export type UseAutomaticUpdatesOptions = {
24
+ /** Pause channel, health, store, and OTA work without delaying app render. */
25
+ enabled?: boolean;
26
+ /** Disable when a separate mandatory native-version hook owns store updates. */
27
+ checkNativeStoreVersion?: boolean;
28
+ };
29
+ export declare const resolveAutomaticUpdateOptions: (options?: UseAutomaticUpdatesOptions) => {
30
+ enabled: boolean;
31
+ checkNativeStoreVersion: boolean;
32
+ };
23
33
  export declare const getDownloadOptions: (latest: LatestVersion & {
24
34
  url: string;
25
35
  }) => DownloadOptions;
26
- export declare const useAutomaticUpdates: () => UseAutomaticUpdatesState;
36
+ export declare const useAutomaticUpdates: (options?: UseAutomaticUpdatesOptions) => UseAutomaticUpdatesState;
@@ -15,6 +15,13 @@ import { useEffect, useRef, useState, useCallback } from 'react';
15
15
  import { CapacitorUpdater, } from '@capgo/capacitor-updater';
16
16
  import { AppUpdate, AppUpdateAvailability, } from '@capawesome/capacitor-app-update';
17
17
  import { Capacitor } from '@capacitor/core';
18
+ export const resolveAutomaticUpdateOptions = (options = {}) => {
19
+ var _a, _b;
20
+ return ({
21
+ enabled: (_a = options.enabled) !== null && _a !== void 0 ? _a : true,
22
+ checkNativeStoreVersion: (_b = options.checkNativeStoreVersion) !== null && _b !== void 0 ? _b : true,
23
+ });
24
+ };
18
25
  const MAINTENANCE_CHECK_INTERVAL_MS = 60 * 1000; // 1 minute
19
26
  const getIosAppStoreId = () => { var _a; return ((_a = process.env.IOS_APP_STORE_ID) === null || _a === void 0 ? void 0 : _a.trim()) || ''; };
20
27
  const isNoUpdateCondition = (error) => {
@@ -43,7 +50,8 @@ export const getDownloadOptions = (latest) => ({
43
50
  sessionKey: latest.sessionKey,
44
51
  manifest: latest.manifest,
45
52
  });
46
- export const useAutomaticUpdates = () => {
53
+ export const useAutomaticUpdates = (options = {}) => {
54
+ const { enabled, checkNativeStoreVersion } = resolveAutomaticUpdateOptions(options);
47
55
  const [otaStatus, setOtaStatus] = useState('idle');
48
56
  const [otaProgress, setOtaProgress] = useState(0);
49
57
  const [maintenanceMode, setMaintenanceMode] = useState(false);
@@ -133,21 +141,26 @@ export const useAutomaticUpdates = () => {
133
141
  }
134
142
  }, []);
135
143
  const retryOTA = useCallback(() => {
144
+ if (!enabled)
145
+ return;
136
146
  setOtaStatus('idle');
137
147
  setOtaProgress(0);
138
148
  checkAndDownloadOTA();
139
- }, [checkAndDownloadOTA]);
149
+ }, [checkAndDownloadOTA, enabled]);
140
150
  const retryMaintenanceCheck = useCallback(async () => {
151
+ if (!enabled)
152
+ return;
141
153
  const serverUp = await checkMaintenance();
142
154
  if (serverUp) {
143
155
  console.log('✅ [MaintenanceCheck] Server back, checking OTA...');
144
156
  otaCheckedRef.current = true;
145
157
  await checkAndDownloadOTA();
146
158
  }
147
- }, [checkMaintenance, checkAndDownloadOTA]);
159
+ }, [checkMaintenance, checkAndDownloadOTA, enabled]);
148
160
  useEffect(() => {
149
161
  if (Capacitor.getPlatform() === 'web')
150
162
  return;
163
+ let disposed = false;
151
164
  (async () => {
152
165
  // Step 1: Confirm current bundle is OK (prevents Capgo rollback)
153
166
  try {
@@ -156,6 +169,10 @@ export const useAutomaticUpdates = () => {
156
169
  catch (err) {
157
170
  console.warn('⚠️ [UpdateCheck] notifyAppReady failed:', err);
158
171
  }
172
+ // Rendering is independent from OTA. A mandatory binary check can pause
173
+ // all update work while still confirming this bundle to prevent rollback.
174
+ if (disposed || !enabled)
175
+ return;
159
176
  // Step 2: Ensure we're on production channel
160
177
  try {
161
178
  const channelInfo = await CapacitorUpdater.getChannel();
@@ -178,18 +195,24 @@ export const useAutomaticUpdates = () => {
178
195
  catch (error) {
179
196
  console.warn('⚠️ Could not get Capgo channel:', error);
180
197
  }
198
+ if (disposed)
199
+ return;
181
200
  // Step 3: Check native app version (store update takes priority over OTA)
182
- if (Capacitor.isNativePlatform()) {
201
+ if (checkNativeStoreVersion && Capacitor.isNativePlatform()) {
183
202
  const nativeUpdateAvailable = await checkNativeVersion();
184
203
  if (nativeUpdateAvailable) {
185
204
  console.log('🛑 [UpdateCheck] Native update required, stopping OTA');
186
205
  return;
187
206
  }
188
207
  }
208
+ if (disposed)
209
+ return;
189
210
  // Step 4: Maintenance check
190
211
  const serverUp = await checkMaintenance();
191
212
  // Step 5: Poll maintenance every 1 minute; trigger OTA when server recovers
192
213
  maintenanceIntervalRef.current = setInterval(async () => {
214
+ if (disposed)
215
+ return;
193
216
  const up = await checkMaintenance();
194
217
  if (up && !otaCheckedRef.current) {
195
218
  console.log('✅ [MaintenanceCheck] Server recovered, checking OTA...');
@@ -208,11 +231,18 @@ export const useAutomaticUpdates = () => {
208
231
  }
209
232
  })();
210
233
  return () => {
234
+ disposed = true;
211
235
  if (maintenanceIntervalRef.current) {
212
236
  clearInterval(maintenanceIntervalRef.current);
237
+ maintenanceIntervalRef.current = null;
213
238
  }
214
239
  };
215
- }, [checkMaintenance, checkAndDownloadOTA]);
240
+ }, [
241
+ checkMaintenance,
242
+ checkAndDownloadOTA,
243
+ checkNativeStoreVersion,
244
+ enabled,
245
+ ]);
216
246
  // --- Native (store) update: uses @capawesome/capacitor-app-update ---
217
247
  const checkNativeVersion = async () => {
218
248
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"useAutomaticUpdates.js","sourceRoot":"","sources":["../../../src/hooks/useAutomaticUpdates.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EACL,gBAAgB,GAGjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,SAAS,EACT,qBAAqB,GAEtB,MA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BAAgB,CAAC,oBAAoB,GAAG,CAAC;YAC3G,CAAC;iBAAM,IAAI,gBAAgB,CAAC,oBAAoB,EAAE,CAAC;gBACjD,gBAAgB,GAAG,gBAAgB,CAAC,oBAAoB,CAAC;YAC3D,CAAC;iBAAM,CAAC;gBACN,gBAAgB,GAAG,QAAQ,CAAC;YAC9B,CAAC;YAED,MAAM,MAAM,CAAC,KAAK,CAAC;gBACjB,KAAK,EAAE,iBAAiB;gBACxB,OAAO,EAAE,kBAAkB,gBAAgB,gDAAgD;gBAC3F,WAAW,EAAE,QAAQ;aACtB,CAAC,CAAC;YAEH,IAAI,gBAAgB,CAAC,sBAAsB,EAAE,CAAC;gBAC5C,MAAM,SAAS,CAAC,sBAAsB,EAAE,CAAC;YAC3C,CAAC;iBAAM,CAAC;gBACN,MAAM,SAAS,CAAC,YAAY,CAAC;oBAC3B,kBAAkB,EAAE,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE;oBAC5C,gFAAgF;oBAChF,KAAK,EAAE,gBAAgB,EAAE;iBAC1B,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,KAAK,CAAC,CAAC;QACxE,CAAC;IACH,CAAC,CAAC;IAEF,OAAO;QACL,SAAS;QACT,WAAW;QACX,eAAe;QACf,QAAQ;QACR,qBAAqB;KACtB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/**\n * useAutomaticUpdates\n *\n * Handles OTA (over-the-air) updates and maintenance mode detection for Capacitor apps.\n * Only runs on native platforms (iOS/Android); skips on web.\n *\n * With autoUpdate: false in capacitor.config.ts, we have full manual control:\n * 1. notifyAppReady → confirm current bundle (prevent rollback)\n * 2. Check Capgo channel → switch to production if needed\n * 3. Check native app version → if outdated, show store update and stop\n * 4. Check maintenance (HEAD request to SITE_ROOT) → on start + every 1 min\n * 5. If server up → getLatest() → download with progress → set + reload\n */\n\nimport { useEffect, useRef, useState, useCallback } from 'react';\nimport {\n CapacitorUpdater,\n type DownloadOptions,\n type LatestVersion,\n} from '@capgo/capacitor-updater';\nimport {\n AppUpdate,\n AppUpdateAvailability,\n AppUpdateInfo,\n} from '@capawesome/capacitor-app-update';\nimport { Capacitor } from '@capacitor/core';\n\nexport type OTAStatus = 'idle' | 'downloading' | 'complete' | 'error';\n\nexport type UseAutomaticUpdatesState = {\n otaStatus: OTAStatus;\n otaProgress: number;\n maintenanceMode: boolean;\n retryOTA: () => void;\n retryMaintenanceCheck: () => void;\n};\n\nconst MAINTENANCE_CHECK_INTERVAL_MS = 60 * 1000; // 1 minute\nconst getIosAppStoreId = () => process.env.IOS_APP_STORE_ID?.trim() || '';\n\nconst isNoUpdateCondition = (error: unknown) => {\n let message = '';\n\n if (typeof error === 'string') {\n message = error.toLowerCase();\n } else if (error && typeof error === 'object') {\n const fields = [\n 'message' in error ? String(error.message ?? '') : '',\n 'error' in error ? String(error.error ?? '') : '',\n 'errorMessage' in error ? String(error.errorMessage ?? '') : '',\n JSON.stringify(error),\n ];\n message = fields.join(' ').toLowerCase();\n }\n\n return (\n message.includes('no new version available') ||\n message.includes('no_new_version_available') ||\n message.includes('disable_auto_update')\n );\n};\n\nexport const getDownloadOptions = (\n latest: LatestVersion & { url: string }\n): DownloadOptions => ({\n url: latest.url,\n version: latest.version,\n checksum: latest.checksum,\n sessionKey: latest.sessionKey,\n manifest: latest.manifest,\n});\n\nexport const useAutomaticUpdates = (): UseAutomaticUpdatesState => {\n const [otaStatus, setOtaStatus] = useState<OTAStatus>('idle');\n const [otaProgress, setOtaProgress] = useState(0);\n const [maintenanceMode, setMaintenanceMode] = useState(false);\n\n const maintenanceIntervalRef = useRef<ReturnType<typeof setInterval> | null>(\n null\n );\n const otaCheckedRef = useRef(false); // Track whether OTA check has already run\n\n // --- Maintenance check: HEAD request to SITE_ROOT ---\n const checkMaintenance = useCallback(async (): Promise<boolean> => {\n const siteRoot = process.env.SITE_ROOT;\n if (!siteRoot) return true;\n\n try {\n const res = await fetch(`${siteRoot}/__health`, {\n method: 'HEAD',\n cache: 'no-store',\n });\n const up = res.ok;\n setMaintenanceMode(!up);\n if (up) {\n console.log('✅ [MaintenanceCheck] Server is up');\n } else {\n console.log('⚠️ [MaintenanceCheck] Server returned', res.status);\n }\n return up;\n } catch (err) {\n console.warn('⚠️ [MaintenanceCheck] Server unreachable:', err);\n setMaintenanceMode(true);\n return false;\n }\n }, []);\n\n // --- Manual OTA: getLatest → download (with progress) → set → reload ---\n const checkAndDownloadOTA = useCallback(async () => {\n try {\n // getLatest() returns LatestVersion { url, version, error, message, ... }\n const latest = await CapacitorUpdater.getLatest();\n if (latest.error) {\n if (isNoUpdateCondition(latest.error) || isNoUpdateCondition(latest)) {\n console.log('ℹ️ [UpdateCheck] Already on latest OTA bundle');\n setOtaStatus('idle');\n setOtaProgress(0);\n return;\n }\n console.warn('⚠️ [UpdateCheck] getLatest error:', latest.error);\n setOtaStatus('error');\n return;\n }\n if (!latest.url) {\n console.log('✅ [UpdateCheck] Already on latest version');\n setOtaStatus('idle');\n setOtaProgress(0);\n return;\n }\n\n console.log(`🔄 [UpdateCheck] OTA update available: ${latest.version}`);\n setOtaStatus('downloading');\n setOtaProgress(0);\n\n // 'download' event fires during download() with progress percentage\n const progressHandle = await CapacitorUpdater.addListener(\n 'download',\n (event: { percent?: number }) => {\n setOtaProgress(Math.min(100, Math.max(0, event.percent ?? 0)));\n }\n );\n\n try {\n // download() resolves when complete and returns BundleInfo { id, version, ... }\n const bundle = await CapacitorUpdater.download(\n getDownloadOptions({ ...latest, url: latest.url })\n );\n\n progressHandle.remove();\n\n // Show \"Update ready, restarting...\" briefly before reload\n setOtaStatus('complete');\n setOtaProgress(100);\n await new Promise((r) => setTimeout(r, 1500));\n // set() takes BundleId { id } — sets bundle and reloads the app\n await CapacitorUpdater.set({ id: bundle.id });\n } catch (err) {\n progressHandle.remove();\n throw err;\n }\n } catch (err: any) {\n if (isNoUpdateCondition(err)) {\n console.log('ℹ️ [UpdateCheck] No OTA update needed');\n setOtaStatus('idle');\n setOtaProgress(0);\n return;\n }\n console.error('❌ [UpdateCheck] OTA error:', err);\n setOtaStatus('error');\n }\n }, []);\n\n const retryOTA = useCallback(() => {\n setOtaStatus('idle');\n setOtaProgress(0);\n checkAndDownloadOTA();\n }, [checkAndDownloadOTA]);\n\n const retryMaintenanceCheck = useCallback(async () => {\n const serverUp = await checkMaintenance();\n if (serverUp) {\n console.log('✅ [MaintenanceCheck] Server back, checking OTA...');\n otaCheckedRef.current = true;\n await checkAndDownloadOTA();\n }\n }, [checkMaintenance, checkAndDownloadOTA]);\n\n useEffect(() => {\n if (Capacitor.getPlatform() === 'web') return;\n\n (async () => {\n // Step 1: Confirm current bundle is OK (prevents Capgo rollback)\n try {\n await CapacitorUpdater.notifyAppReady();\n } catch (err) {\n console.warn('⚠️ [UpdateCheck] notifyAppReady failed:', err);\n }\n\n // Step 2: Ensure we're on production channel\n try {\n const channelInfo = await CapacitorUpdater.getChannel();\n console.log('📦 Capgo channel:', channelInfo.channel, channelInfo);\n\n const targetChannel = 'production';\n if (\n channelInfo.channel &&\n channelInfo.channel !== targetChannel &&\n channelInfo.allowSet\n ) {\n try {\n await CapacitorUpdater.setChannel({\n channel: targetChannel,\n triggerAutoUpdate: false,\n });\n } catch (error) {\n console.warn(`⚠️ Could not switch to ${targetChannel}:`, error);\n }\n }\n } catch (error) {\n console.warn('⚠️ Could not get Capgo channel:', error);\n }\n\n // Step 3: Check native app version (store update takes priority over OTA)\n if (Capacitor.isNativePlatform()) {\n const nativeUpdateAvailable = await checkNativeVersion();\n if (nativeUpdateAvailable) {\n console.log('🛑 [UpdateCheck] Native update required, stopping OTA');\n return;\n }\n }\n\n // Step 4: Maintenance check\n const serverUp = await checkMaintenance();\n\n // Step 5: Poll maintenance every 1 minute; trigger OTA when server recovers\n maintenanceIntervalRef.current = setInterval(async () => {\n const up = await checkMaintenance();\n if (up && !otaCheckedRef.current) {\n console.log(\n '✅ [MaintenanceCheck] Server recovered, checking OTA...'\n );\n otaCheckedRef.current = true;\n await checkAndDownloadOTA();\n }\n }, MAINTENANCE_CHECK_INTERVAL_MS);\n\n // Step 6: Check OTA only when server is up\n if (serverUp) {\n console.log('✅ [UpdateCheck] Native is up to date, checking OTA...');\n otaCheckedRef.current = true;\n await checkAndDownloadOTA();\n } else {\n console.log(\n '⏸️ [UpdateCheck] Server down, skipping OTA check until Retry'\n );\n }\n })();\n\n return () => {\n if (maintenanceIntervalRef.current) {\n clearInterval(maintenanceIntervalRef.current);\n }\n };\n }, [checkMaintenance, checkAndDownloadOTA]);\n\n // --- Native (store) update: uses @capawesome/capacitor-app-update ---\n const checkNativeVersion = async (): Promise<boolean> => {\n try {\n const nativeUpdateInfo = await AppUpdate.getAppUpdateInfo();\n if (\n nativeUpdateInfo.updateAvailability ===\n AppUpdateAvailability.UPDATE_AVAILABLE\n ) {\n await showNativeUpdate(nativeUpdateInfo);\n return true;\n }\n return false;\n } catch (error) {\n console.error('❌ [UpdateCheck] Error checking native version:', error);\n return false;\n }\n };\n\n const showNativeUpdate = async (nativeUpdateInfo: AppUpdateInfo) => {\n try {\n const { Dialog } = await import('@capacitor/dialog');\n let availableVersion: string;\n if (\n nativeUpdateInfo.availableVersionName &&\n nativeUpdateInfo.availableVersionCode\n ) {\n availableVersion = `${nativeUpdateInfo.availableVersionName} (${nativeUpdateInfo.availableVersionCode})`;\n } else if (nativeUpdateInfo.availableVersionName) {\n availableVersion = nativeUpdateInfo.availableVersionName;\n } else {\n availableVersion = 'latest';\n }\n\n await Dialog.alert({\n title: 'Update Required',\n message: `A new version (${availableVersion}) is available. Please update now to continue.`,\n buttonTitle: 'Update',\n });\n\n if (nativeUpdateInfo.immediateUpdateAllowed) {\n await AppUpdate.performImmediateUpdate();\n } else {\n await AppUpdate.openAppStore({\n androidPackageName: process.env.APP_ID || '',\n // On iOS the plugin expects the numeric Apple App ID, not a full App Store URL.\n appId: getIosAppStoreId(),\n });\n }\n } catch (error) {\n console.error('❌ [UpdateCheck] Error applying native update:', error);\n }\n };\n\n return {\n otaStatus,\n otaProgress,\n maintenanceMode,\n retryOTA,\n retryMaintenanceCheck,\n };\n};\n"]}
1
+ {"version":3,"file":"useAutomaticUpdates.js","sourceRoot":"","sources":["../../../src/hooks/useAutomaticUpdates.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EACL,gBAAgB,GAGjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,SAAS,EACT,qBAAqB,GAEtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAmB5C,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAC3C,UAAsC,EAAE,EACxC,EAAE;;IAAC,OAAA,CAAC;QACJ,OAAO,EAAE,MAAA,OAAO,CAAC,OAAO,mCAAI,IAAI;QAChC,uBAAuB,EAAE,MAAA,OAAO,CAAC,uBAAuB,mCAAI,IAAI;KACjE,CAAC,CAAA;CAAA,CAAC;AAEH,MAAM,6BAA6B,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,WAAW;AAC5D,MAAM,gBAAgB,GAAG,GAAG,EAAE,WAAC,OAAA,CAAA,MAAA,OAAO,CAAC,GAAG,CAAC,gBAAgB,0CAAE,IAAI,EAAE,KAAI,EAAE,CAAA,EAAA,CAAC;AAE1E,MAAM,mBAAmB,GAAG,CAAC,KAAc,EAAE,EAAE;;IAC7C,IAAI,OAAO,GAAG,EAAE,CAAC;IAEjB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;IAChC,CAAC;SAAM,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9C,MAAM,MAAM,GAAG;YACb,SA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C;iBAAM,IAAI,gBAAgB,CAAC,oBAAoB,EAAE,CAAC;gBACjD,gBAAgB,GAAG,gBAAgB,CAAC,oBAAoB,CAAC;YAC3D,CAAC;iBAAM,CAAC;gBACN,gBAAgB,GAAG,QAAQ,CAAC;YAC9B,CAAC;YAED,MAAM,MAAM,CAAC,KAAK,CAAC;gBACjB,KAAK,EAAE,iBAAiB;gBACxB,OAAO,EAAE,kBAAkB,gBAAgB,gDAAgD;gBAC3F,WAAW,EAAE,QAAQ;aACtB,CAAC,CAAC;YAEH,IAAI,gBAAgB,CAAC,sBAAsB,EAAE,CAAC;gBAC5C,MAAM,SAAS,CAAC,sBAAsB,EAAE,CAAC;YAC3C,CAAC;iBAAM,CAAC;gBACN,MAAM,SAAS,CAAC,YAAY,CAAC;oBAC3B,kBAAkB,EAAE,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE;oBAC5C,gFAAgF;oBAChF,KAAK,EAAE,gBAAgB,EAAE;iBAC1B,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,KAAK,CAAC,CAAC;QACxE,CAAC;IACH,CAAC,CAAC;IAEF,OAAO;QACL,SAAS;QACT,WAAW;QACX,eAAe;QACf,QAAQ;QACR,qBAAqB;KACtB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/**\n * useAutomaticUpdates\n *\n * Handles OTA (over-the-air) updates and maintenance mode detection for Capacitor apps.\n * Only runs on native platforms (iOS/Android); skips on web.\n *\n * With autoUpdate: false in capacitor.config.ts, we have full manual control:\n * 1. notifyAppReady → confirm current bundle (prevent rollback)\n * 2. Check Capgo channel → switch to production if needed\n * 3. Check native app version → if outdated, show store update and stop\n * 4. Check maintenance (HEAD request to SITE_ROOT) → on start + every 1 min\n * 5. If server up → getLatest() → download with progress → set + reload\n */\n\nimport { useEffect, useRef, useState, useCallback } from 'react';\nimport {\n CapacitorUpdater,\n type DownloadOptions,\n type LatestVersion,\n} from '@capgo/capacitor-updater';\nimport {\n AppUpdate,\n AppUpdateAvailability,\n AppUpdateInfo,\n} from '@capawesome/capacitor-app-update';\nimport { Capacitor } from '@capacitor/core';\n\nexport type OTAStatus = 'idle' | 'downloading' | 'complete' | 'error';\n\nexport type UseAutomaticUpdatesState = {\n otaStatus: OTAStatus;\n otaProgress: number;\n maintenanceMode: boolean;\n retryOTA: () => void;\n retryMaintenanceCheck: () => void;\n};\n\nexport type UseAutomaticUpdatesOptions = {\n /** Pause channel, health, store, and OTA work without delaying app render. */\n enabled?: boolean;\n /** Disable when a separate mandatory native-version hook owns store updates. */\n checkNativeStoreVersion?: boolean;\n};\n\nexport const resolveAutomaticUpdateOptions = (\n options: UseAutomaticUpdatesOptions = {}\n) => ({\n enabled: options.enabled ?? true,\n checkNativeStoreVersion: options.checkNativeStoreVersion ?? true,\n});\n\nconst MAINTENANCE_CHECK_INTERVAL_MS = 60 * 1000; // 1 minute\nconst getIosAppStoreId = () => process.env.IOS_APP_STORE_ID?.trim() || '';\n\nconst isNoUpdateCondition = (error: unknown) => {\n let message = '';\n\n if (typeof error === 'string') {\n message = error.toLowerCase();\n } else if (error && typeof error === 'object') {\n const fields = [\n 'message' in error ? String(error.message ?? '') : '',\n 'error' in error ? String(error.error ?? '') : '',\n 'errorMessage' in error ? String(error.errorMessage ?? '') : '',\n JSON.stringify(error),\n ];\n message = fields.join(' ').toLowerCase();\n }\n\n return (\n message.includes('no new version available') ||\n message.includes('no_new_version_available') ||\n message.includes('disable_auto_update')\n );\n};\n\nexport const getDownloadOptions = (\n latest: LatestVersion & { url: string }\n): DownloadOptions => ({\n url: latest.url,\n version: latest.version,\n checksum: latest.checksum,\n sessionKey: latest.sessionKey,\n manifest: latest.manifest,\n});\n\nexport const useAutomaticUpdates = (\n options: UseAutomaticUpdatesOptions = {}\n): UseAutomaticUpdatesState => {\n const { enabled, checkNativeStoreVersion } =\n resolveAutomaticUpdateOptions(options);\n const [otaStatus, setOtaStatus] = useState<OTAStatus>('idle');\n const [otaProgress, setOtaProgress] = useState(0);\n const [maintenanceMode, setMaintenanceMode] = useState(false);\n\n const maintenanceIntervalRef = useRef<ReturnType<typeof setInterval> | null>(\n null\n );\n const otaCheckedRef = useRef(false); // Track whether OTA check has already run\n\n // --- Maintenance check: HEAD request to SITE_ROOT ---\n const checkMaintenance = useCallback(async (): Promise<boolean> => {\n const siteRoot = process.env.SITE_ROOT;\n if (!siteRoot) return true;\n\n try {\n const res = await fetch(`${siteRoot}/__health`, {\n method: 'HEAD',\n cache: 'no-store',\n });\n const up = res.ok;\n setMaintenanceMode(!up);\n if (up) {\n console.log('✅ [MaintenanceCheck] Server is up');\n } else {\n console.log('⚠️ [MaintenanceCheck] Server returned', res.status);\n }\n return up;\n } catch (err) {\n console.warn('⚠️ [MaintenanceCheck] Server unreachable:', err);\n setMaintenanceMode(true);\n return false;\n }\n }, []);\n\n // --- Manual OTA: getLatest → download (with progress) → set → reload ---\n const checkAndDownloadOTA = useCallback(async () => {\n try {\n // getLatest() returns LatestVersion { url, version, error, message, ... }\n const latest = await CapacitorUpdater.getLatest();\n if (latest.error) {\n if (isNoUpdateCondition(latest.error) || isNoUpdateCondition(latest)) {\n console.log('ℹ️ [UpdateCheck] Already on latest OTA bundle');\n setOtaStatus('idle');\n setOtaProgress(0);\n return;\n }\n console.warn('⚠️ [UpdateCheck] getLatest error:', latest.error);\n setOtaStatus('error');\n return;\n }\n if (!latest.url) {\n console.log('✅ [UpdateCheck] Already on latest version');\n setOtaStatus('idle');\n setOtaProgress(0);\n return;\n }\n\n console.log(`🔄 [UpdateCheck] OTA update available: ${latest.version}`);\n setOtaStatus('downloading');\n setOtaProgress(0);\n\n // 'download' event fires during download() with progress percentage\n const progressHandle = await CapacitorUpdater.addListener(\n 'download',\n (event: { percent?: number }) => {\n setOtaProgress(Math.min(100, Math.max(0, event.percent ?? 0)));\n }\n );\n\n try {\n // download() resolves when complete and returns BundleInfo { id, version, ... }\n const bundle = await CapacitorUpdater.download(\n getDownloadOptions({ ...latest, url: latest.url })\n );\n\n progressHandle.remove();\n\n // Show \"Update ready, restarting...\" briefly before reload\n setOtaStatus('complete');\n setOtaProgress(100);\n await new Promise((r) => setTimeout(r, 1500));\n // set() takes BundleId { id } — sets bundle and reloads the app\n await CapacitorUpdater.set({ id: bundle.id });\n } catch (err) {\n progressHandle.remove();\n throw err;\n }\n } catch (err: any) {\n if (isNoUpdateCondition(err)) {\n console.log('ℹ️ [UpdateCheck] No OTA update needed');\n setOtaStatus('idle');\n setOtaProgress(0);\n return;\n }\n console.error('❌ [UpdateCheck] OTA error:', err);\n setOtaStatus('error');\n }\n }, []);\n\n const retryOTA = useCallback(() => {\n if (!enabled) return;\n setOtaStatus('idle');\n setOtaProgress(0);\n checkAndDownloadOTA();\n }, [checkAndDownloadOTA, enabled]);\n\n const retryMaintenanceCheck = useCallback(async () => {\n if (!enabled) return;\n const serverUp = await checkMaintenance();\n if (serverUp) {\n console.log('✅ [MaintenanceCheck] Server back, checking OTA...');\n otaCheckedRef.current = true;\n await checkAndDownloadOTA();\n }\n }, [checkMaintenance, checkAndDownloadOTA, enabled]);\n\n useEffect(() => {\n if (Capacitor.getPlatform() === 'web') return;\n\n let disposed = false;\n\n (async () => {\n // Step 1: Confirm current bundle is OK (prevents Capgo rollback)\n try {\n await CapacitorUpdater.notifyAppReady();\n } catch (err) {\n console.warn('⚠️ [UpdateCheck] notifyAppReady failed:', err);\n }\n\n // Rendering is independent from OTA. A mandatory binary check can pause\n // all update work while still confirming this bundle to prevent rollback.\n if (disposed || !enabled) return;\n\n // Step 2: Ensure we're on production channel\n try {\n const channelInfo = await CapacitorUpdater.getChannel();\n console.log('📦 Capgo channel:', channelInfo.channel, channelInfo);\n\n const targetChannel = 'production';\n if (\n channelInfo.channel &&\n channelInfo.channel !== targetChannel &&\n channelInfo.allowSet\n ) {\n try {\n await CapacitorUpdater.setChannel({\n channel: targetChannel,\n triggerAutoUpdate: false,\n });\n } catch (error) {\n console.warn(`⚠️ Could not switch to ${targetChannel}:`, error);\n }\n }\n } catch (error) {\n console.warn('⚠️ Could not get Capgo channel:', error);\n }\n\n if (disposed) return;\n\n // Step 3: Check native app version (store update takes priority over OTA)\n if (checkNativeStoreVersion && Capacitor.isNativePlatform()) {\n const nativeUpdateAvailable = await checkNativeVersion();\n if (nativeUpdateAvailable) {\n console.log('🛑 [UpdateCheck] Native update required, stopping OTA');\n return;\n }\n }\n\n if (disposed) return;\n\n // Step 4: Maintenance check\n const serverUp = await checkMaintenance();\n\n // Step 5: Poll maintenance every 1 minute; trigger OTA when server recovers\n maintenanceIntervalRef.current = setInterval(async () => {\n if (disposed) return;\n const up = await checkMaintenance();\n if (up && !otaCheckedRef.current) {\n console.log(\n '✅ [MaintenanceCheck] Server recovered, checking OTA...'\n );\n otaCheckedRef.current = true;\n await checkAndDownloadOTA();\n }\n }, MAINTENANCE_CHECK_INTERVAL_MS);\n\n // Step 6: Check OTA only when server is up\n if (serverUp) {\n console.log('✅ [UpdateCheck] Native is up to date, checking OTA...');\n otaCheckedRef.current = true;\n await checkAndDownloadOTA();\n } else {\n console.log(\n '⏸️ [UpdateCheck] Server down, skipping OTA check until Retry'\n );\n }\n })();\n\n return () => {\n disposed = true;\n if (maintenanceIntervalRef.current) {\n clearInterval(maintenanceIntervalRef.current);\n maintenanceIntervalRef.current = null;\n }\n };\n }, [\n checkMaintenance,\n checkAndDownloadOTA,\n checkNativeStoreVersion,\n enabled,\n ]);\n\n // --- Native (store) update: uses @capawesome/capacitor-app-update ---\n const checkNativeVersion = async (): Promise<boolean> => {\n try {\n const nativeUpdateInfo = await AppUpdate.getAppUpdateInfo();\n if (\n nativeUpdateInfo.updateAvailability ===\n AppUpdateAvailability.UPDATE_AVAILABLE\n ) {\n await showNativeUpdate(nativeUpdateInfo);\n return true;\n }\n return false;\n } catch (error) {\n console.error('❌ [UpdateCheck] Error checking native version:', error);\n return false;\n }\n };\n\n const showNativeUpdate = async (nativeUpdateInfo: AppUpdateInfo) => {\n try {\n const { Dialog } = await import('@capacitor/dialog');\n let availableVersion: string;\n if (\n nativeUpdateInfo.availableVersionName &&\n nativeUpdateInfo.availableVersionCode\n ) {\n availableVersion = `${nativeUpdateInfo.availableVersionName} (${nativeUpdateInfo.availableVersionCode})`;\n } else if (nativeUpdateInfo.availableVersionName) {\n availableVersion = nativeUpdateInfo.availableVersionName;\n } else {\n availableVersion = 'latest';\n }\n\n await Dialog.alert({\n title: 'Update Required',\n message: `A new version (${availableVersion}) is available. Please update now to continue.`,\n buttonTitle: 'Update',\n });\n\n if (nativeUpdateInfo.immediateUpdateAllowed) {\n await AppUpdate.performImmediateUpdate();\n } else {\n await AppUpdate.openAppStore({\n androidPackageName: process.env.APP_ID || '',\n // On iOS the plugin expects the numeric Apple App ID, not a full App Store URL.\n appId: getIosAppStoreId(),\n });\n }\n } catch (error) {\n console.error('❌ [UpdateCheck] Error applying native update:', error);\n }\n };\n\n return {\n otaStatus,\n otaProgress,\n maintenanceMode,\n retryOTA,\n retryMaintenanceCheck,\n };\n};\n"]}
@@ -0,0 +1,47 @@
1
+ import { AppUpdate } from '@capawesome/capacitor-app-update';
2
+ export type NativePlatform = 'ios' | 'android';
3
+ export type MandatoryNativeUpdateState = {
4
+ status: 'not-native';
5
+ } | {
6
+ status: 'checking';
7
+ } | {
8
+ status: 'supported';
9
+ currentVersion: string;
10
+ minimumVersion: string;
11
+ } | {
12
+ status: 'required';
13
+ platform: NativePlatform;
14
+ currentVersion: string;
15
+ minimumVersion: string;
16
+ updating: boolean;
17
+ error?: string;
18
+ } | {
19
+ status: 'error';
20
+ minimumVersion: string;
21
+ error: string;
22
+ };
23
+ export type UseMandatoryNativeUpdateOptions = {
24
+ minimumVersion?: string;
25
+ fallbackMinimumVersion: string;
26
+ iosAppStoreId?: string;
27
+ androidPackageName?: string;
28
+ };
29
+ export type UseMandatoryNativeUpdateResult = {
30
+ state: MandatoryNativeUpdateState;
31
+ requestUpdate: () => Promise<void>;
32
+ retryCheck: () => Promise<void>;
33
+ };
34
+ export declare function compareNativeVersions(a: string, b: string): number;
35
+ export declare function effectiveMinimumVersion(fallbackMinimumVersion: string, minimumVersion?: string): string;
36
+ export declare function nativeUpdateRequirement(currentVersion: string, fallbackMinimumVersion: string, minimumVersion?: string): {
37
+ supported: boolean;
38
+ minimumVersion: string;
39
+ };
40
+ type NativeUpdateApi = Pick<typeof AppUpdate, 'getAppUpdateInfo' | 'performImmediateUpdate' | 'openAppStore'>;
41
+ export declare function openRequiredNativeUpdate({ platform, iosAppStoreId, androidPackageName, }: {
42
+ platform: NativePlatform;
43
+ iosAppStoreId?: string;
44
+ androidPackageName?: string;
45
+ }, api?: NativeUpdateApi): Promise<void>;
46
+ export declare function useMandatoryNativeUpdate({ minimumVersion, fallbackMinimumVersion, iosAppStoreId, androidPackageName, }: UseMandatoryNativeUpdateOptions): UseMandatoryNativeUpdateResult;
47
+ export {};
@@ -0,0 +1,160 @@
1
+ import { App as NativeApp } from '@capacitor/app';
2
+ import { Capacitor } from '@capacitor/core';
3
+ import { AppUpdate, AppUpdateResultCode, } from '@capawesome/capacitor-app-update';
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
5
+ const STABLE_VERSION = /^\d+\.\d+\.\d+$/;
6
+ export function compareNativeVersions(a, b) {
7
+ const left = a.trim();
8
+ const right = b.trim();
9
+ if (!STABLE_VERSION.test(left) || !STABLE_VERSION.test(right)) {
10
+ throw new Error('Native versions must use stable X.Y.Z format');
11
+ }
12
+ const leftParts = left.split('.').map(Number);
13
+ const rightParts = right.split('.').map(Number);
14
+ for (let index = 0; index < 3; index += 1) {
15
+ if (leftParts[index] !== rightParts[index]) {
16
+ return leftParts[index] > rightParts[index] ? 1 : -1;
17
+ }
18
+ }
19
+ return 0;
20
+ }
21
+ export function effectiveMinimumVersion(fallbackMinimumVersion, minimumVersion) {
22
+ const fallback = fallbackMinimumVersion.trim();
23
+ if (!STABLE_VERSION.test(fallback)) {
24
+ throw new Error('fallbackMinimumVersion must use stable X.Y.Z format');
25
+ }
26
+ if (!minimumVersion)
27
+ return fallback;
28
+ const candidate = minimumVersion.trim();
29
+ if (!STABLE_VERSION.test(candidate))
30
+ return fallback;
31
+ return compareNativeVersions(candidate, fallback) > 0 ? candidate : fallback;
32
+ }
33
+ export function nativeUpdateRequirement(currentVersion, fallbackMinimumVersion, minimumVersion) {
34
+ const effectiveMinimum = effectiveMinimumVersion(fallbackMinimumVersion, minimumVersion);
35
+ return {
36
+ supported: compareNativeVersions(currentVersion, effectiveMinimum) >= 0,
37
+ minimumVersion: effectiveMinimum,
38
+ };
39
+ }
40
+ export async function openRequiredNativeUpdate({ platform, iosAppStoreId, androidPackageName, }, api = AppUpdate) {
41
+ if (platform === 'ios') {
42
+ const appId = iosAppStoreId === null || iosAppStoreId === void 0 ? void 0 : iosAppStoreId.trim();
43
+ if (!appId)
44
+ throw new Error('iosAppStoreId is not configured');
45
+ await api.openAppStore({ appId });
46
+ return;
47
+ }
48
+ try {
49
+ const info = await api.getAppUpdateInfo();
50
+ if (info.immediateUpdateAllowed) {
51
+ const result = await api.performImmediateUpdate();
52
+ if (result.code === AppUpdateResultCode.OK)
53
+ return;
54
+ }
55
+ }
56
+ catch (error) {
57
+ console.warn('Immediate update unavailable; opening Google Play:', error);
58
+ }
59
+ await api.openAppStore({ androidPackageName });
60
+ }
61
+ export function useMandatoryNativeUpdate({ minimumVersion, fallbackMinimumVersion, iosAppStoreId, androidPackageName, }) {
62
+ const capacitorPlatform = Capacitor.getPlatform();
63
+ const platform = capacitorPlatform === 'ios' || capacitorPlatform === 'android'
64
+ ? capacitorPlatform
65
+ : null;
66
+ const effectiveMinimum = useMemo(() => effectiveMinimumVersion(fallbackMinimumVersion, minimumVersion), [fallbackMinimumVersion, minimumVersion]);
67
+ const [state, setState] = useState(platform ? { status: 'checking' } : { status: 'not-native' });
68
+ // Drop stale App.getInfo() results after a newer check or unmount.
69
+ const checkSequence = useRef(0);
70
+ const check = useCallback(async () => {
71
+ const sequence = ++checkSequence.current;
72
+ if (!platform) {
73
+ setState({ status: 'not-native' });
74
+ return;
75
+ }
76
+ try {
77
+ const { version } = await NativeApp.getInfo();
78
+ if (sequence !== checkSequence.current)
79
+ return;
80
+ if (compareNativeVersions(version, effectiveMinimum) >= 0) {
81
+ setState({
82
+ status: 'supported',
83
+ currentVersion: version,
84
+ minimumVersion: effectiveMinimum,
85
+ });
86
+ }
87
+ else {
88
+ setState({
89
+ status: 'required',
90
+ platform,
91
+ currentVersion: version,
92
+ minimumVersion: effectiveMinimum,
93
+ updating: false,
94
+ });
95
+ }
96
+ }
97
+ catch (error) {
98
+ if (sequence !== checkSequence.current)
99
+ return;
100
+ console.error('Unable to read the native app version:', error);
101
+ setState({
102
+ status: 'error',
103
+ minimumVersion: effectiveMinimum,
104
+ error: 'We could not verify this app version. Please try again.',
105
+ });
106
+ }
107
+ }, [effectiveMinimum, platform]);
108
+ useEffect(() => {
109
+ void check();
110
+ if (!platform)
111
+ return;
112
+ let disposed = false;
113
+ let removeListener;
114
+ void NativeApp.addListener('appStateChange', ({ isActive }) => {
115
+ if (isActive)
116
+ void check();
117
+ })
118
+ .then((handle) => {
119
+ if (disposed)
120
+ void handle.remove();
121
+ else
122
+ removeListener = handle.remove;
123
+ })
124
+ .catch((error) => {
125
+ console.error('Unable to register the app state listener:', error);
126
+ });
127
+ return () => {
128
+ disposed = true;
129
+ checkSequence.current += 1;
130
+ if (removeListener)
131
+ void removeListener();
132
+ };
133
+ }, [check, platform]);
134
+ const requestUpdate = useCallback(async () => {
135
+ if (state.status !== 'required')
136
+ return;
137
+ const required = state;
138
+ setState({ ...required, updating: true, error: undefined });
139
+ try {
140
+ await openRequiredNativeUpdate({
141
+ platform: required.platform,
142
+ iosAppStoreId,
143
+ androidPackageName,
144
+ });
145
+ setState({ ...required, updating: false });
146
+ }
147
+ catch (error) {
148
+ console.error('Unable to start the required native app update:', error);
149
+ setState({
150
+ ...required,
151
+ updating: false,
152
+ error: required.platform === 'ios'
153
+ ? "We couldn't open the App Store. Please try again."
154
+ : "We couldn't open Google Play. Please try again.",
155
+ });
156
+ }
157
+ }, [androidPackageName, iosAppStoreId, state]);
158
+ return useMemo(() => ({ state, requestUpdate, retryCheck: check }), [check, requestUpdate, state]);
159
+ }
160
+ //# sourceMappingURL=useMandatoryNativeUpdate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useMandatoryNativeUpdate.js","sourceRoot":"","sources":["../../../src/hooks/useMandatoryNativeUpdate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,IAAI,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACL,SAAS,EACT,mBAAmB,GACpB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAmC1E,MAAM,cAAc,GAAG,iBAAiB,CAAC;AAEzC,MAAM,UAAU,qBAAqB,CAAC,CAAS,EAAE,CAAS;IACxD,MAAM,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IACtB,MAAM,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IACvB,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9D,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,UAAU,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAChD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,K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AC,QAAQ;gBAC3B,aAAa;gBACb,kBAAkB;aACnB,CAAC,CAAC;YACH,QAAQ,CAAC,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;YACxE,QAAQ,CAAC;gBACP,GAAG,QAAQ;gBACX,QAAQ,EAAE,KAAK;gBACf,KAAK,EACH,QAAQ,CAAC,QAAQ,KAAK,KAAK;oBACzB,CAAC,CAAC,mDAAmD;oBACrD,CAAC,CAAC,iDAAiD;aACxD,CAAC,CAAC;QACL,CAAC;IACH,CAAC,EAAE,CAAC,kBAAkB,EAAE,aAAa,EAAE,KAAK,CAAC,CAAC,CAAC;IAE/C,OAAO,OAAO,CACZ,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,EACnD,CAAC,KAAK,EAAE,aAAa,EAAE,KAAK,CAAC,CAC9B,CAAC;AACJ,CAAC","sourcesContent":["import { App as NativeApp } from '@capacitor/app';\nimport { Capacitor } from '@capacitor/core';\nimport {\n AppUpdate,\n AppUpdateResultCode,\n} from '@capawesome/capacitor-app-update';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nexport type NativePlatform = 'ios' | 'android';\n\nexport type MandatoryNativeUpdateState =\n | { status: 'not-native' }\n | { status: 'checking' }\n | {\n status: 'supported';\n currentVersion: string;\n minimumVersion: string;\n }\n | {\n status: 'required';\n platform: NativePlatform;\n currentVersion: string;\n minimumVersion: string;\n updating: boolean;\n error?: string;\n }\n | { status: 'error'; minimumVersion: string; error: string };\n\nexport type UseMandatoryNativeUpdateOptions = {\n minimumVersion?: string;\n fallbackMinimumVersion: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n};\n\nexport type UseMandatoryNativeUpdateResult = {\n state: MandatoryNativeUpdateState;\n requestUpdate: () => Promise<void>;\n retryCheck: () => Promise<void>;\n};\n\nconst STABLE_VERSION = /^\\d+\\.\\d+\\.\\d+$/;\n\nexport function compareNativeVersions(a: string, b: string): number {\n const left = a.trim();\n const right = b.trim();\n if (!STABLE_VERSION.test(left) || !STABLE_VERSION.test(right)) {\n throw new Error('Native versions must use stable X.Y.Z format');\n }\n const leftParts = left.split('.').map(Number);\n const rightParts = right.split('.').map(Number);\n for (let index = 0; index < 3; index += 1) {\n if (leftParts[index] !== rightParts[index]) {\n return leftParts[index] > rightParts[index] ? 1 : -1;\n }\n }\n return 0;\n}\n\nexport function effectiveMinimumVersion(\n fallbackMinimumVersion: string,\n minimumVersion?: string\n): string {\n const fallback = fallbackMinimumVersion.trim();\n if (!STABLE_VERSION.test(fallback)) {\n throw new Error('fallbackMinimumVersion must use stable X.Y.Z format');\n }\n if (!minimumVersion) return fallback;\n const candidate = minimumVersion.trim();\n if (!STABLE_VERSION.test(candidate)) return fallback;\n return compareNativeVersions(candidate, fallback) > 0 ? candidate : fallback;\n}\n\nexport function nativeUpdateRequirement(\n currentVersion: string,\n fallbackMinimumVersion: string,\n minimumVersion?: string\n) {\n const effectiveMinimum = effectiveMinimumVersion(\n fallbackMinimumVersion,\n minimumVersion\n );\n return {\n supported: compareNativeVersions(currentVersion, effectiveMinimum) >= 0,\n minimumVersion: effectiveMinimum,\n };\n}\n\ntype NativeUpdateApi = Pick<\n typeof AppUpdate,\n | 'getAppUpdateInfo'\n | 'performImmediateUpdate'\n | 'openAppStore'\n>;\n\nexport async function openRequiredNativeUpdate(\n {\n platform,\n iosAppStoreId,\n androidPackageName,\n }: {\n platform: NativePlatform;\n iosAppStoreId?: string;\n androidPackageName?: string;\n },\n api: NativeUpdateApi = AppUpdate\n): Promise<void> {\n if (platform === 'ios') {\n const appId = iosAppStoreId?.trim();\n if (!appId) throw new Error('iosAppStoreId is not configured');\n await api.openAppStore({ appId });\n return;\n }\n\n try {\n const info = await api.getAppUpdateInfo();\n if (info.immediateUpdateAllowed) {\n const result = await api.performImmediateUpdate();\n if (result.code === AppUpdateResultCode.OK) return;\n }\n } catch (error) {\n console.warn('Immediate update unavailable; opening Google Play:', error);\n }\n await api.openAppStore({ androidPackageName });\n}\n\nexport function useMandatoryNativeUpdate({\n minimumVersion,\n fallbackMinimumVersion,\n iosAppStoreId,\n androidPackageName,\n}: UseMandatoryNativeUpdateOptions): UseMandatoryNativeUpdateResult {\n const capacitorPlatform = Capacitor.getPlatform();\n const platform =\n capacitorPlatform === 'ios' || capacitorPlatform === 'android'\n ? capacitorPlatform\n : null;\n const effectiveMinimum = useMemo(\n () => effectiveMinimumVersion(fallbackMinimumVersion, minimumVersion),\n [fallbackMinimumVersion, minimumVersion]\n );\n const [state, setState] = useState<MandatoryNativeUpdateState>(\n platform ? { status: 'checking' } : { status: 'not-native' }\n );\n // Drop stale App.getInfo() results after a newer check or unmount.\n const checkSequence = useRef(0);\n\n const check = useCallback(async () => {\n const sequence = ++checkSequence.current;\n if (!platform) {\n setState({ status: 'not-native' });\n return;\n }\n try {\n const { version } = await NativeApp.getInfo();\n if (sequence !== checkSequence.current) return;\n if (compareNativeVersions(version, effectiveMinimum) >= 0) {\n setState({\n status: 'supported',\n currentVersion: version,\n minimumVersion: effectiveMinimum,\n });\n } else {\n setState({\n status: 'required',\n platform,\n currentVersion: version,\n minimumVersion: effectiveMinimum,\n updating: false,\n });\n }\n } catch (error) {\n if (sequence !== checkSequence.current) return;\n console.error('Unable to read the native app version:', error);\n setState({\n status: 'error',\n minimumVersion: effectiveMinimum,\n error: 'We could not verify this app version. Please try again.',\n });\n }\n }, [effectiveMinimum, platform]);\n\n useEffect(() => {\n void check();\n if (!platform) return;\n\n let disposed = false;\n let removeListener: (() => Promise<void>) | undefined;\n void NativeApp.addListener('appStateChange', ({ isActive }) => {\n if (isActive) void check();\n })\n .then((handle) => {\n if (disposed) void handle.remove();\n else removeListener = handle.remove;\n })\n .catch((error) => {\n console.error('Unable to register the app state listener:', error);\n });\n return () => {\n disposed = true;\n checkSequence.current += 1;\n if (removeListener) void removeListener();\n };\n }, [check, platform]);\n\n const requestUpdate = useCallback(async () => {\n if (state.status !== 'required') return;\n const required = state;\n setState({ ...required, updating: true, error: undefined });\n try {\n await openRequiredNativeUpdate({\n platform: required.platform,\n iosAppStoreId,\n androidPackageName,\n });\n setState({ ...required, updating: false });\n } catch (error) {\n console.error('Unable to start the required native app update:', error);\n setState({\n ...required,\n updating: false,\n error:\n required.platform === 'ios'\n ? \"We couldn't open the App Store. Please try again.\"\n : \"We couldn't open Google Play. Please try again.\",\n });\n }\n }, [androidPackageName, iosAppStoreId, state]);\n\n return useMemo(\n () => ({ state, requestUpdate, retryCheck: check }),\n [check, requestUpdate, state]\n );\n}\n"]}
@@ -0,0 +1,39 @@
1
+ import { type ReleaseStatus } from '../utils/releaseStatus.js';
2
+ export type ReleaseGateState = {
3
+ status: 'checking';
4
+ } | {
5
+ status: 'maintenance';
6
+ message?: string;
7
+ } | {
8
+ status: 'supported';
9
+ currentVersion?: string;
10
+ } | {
11
+ status: 'required';
12
+ platform: 'ios' | 'android';
13
+ currentVersion: string;
14
+ minimumVersion: string;
15
+ updating: boolean;
16
+ error?: string;
17
+ } | {
18
+ status: 'error';
19
+ minimumVersion: string;
20
+ error: string;
21
+ };
22
+ export type UseReleaseGateOptions = {
23
+ loadStatus: () => Promise<ReleaseStatus>;
24
+ fallbackMinimumVersion: string;
25
+ iosAppStoreId?: string;
26
+ androidPackageName?: string;
27
+ };
28
+ export type ReleaseGateResult = {
29
+ state: ReleaseGateState;
30
+ store?: 'App Store' | 'Google Play';
31
+ otaEnabled: boolean;
32
+ requestUpdate: () => Promise<void>;
33
+ retryCheck: () => Promise<void>;
34
+ };
35
+ /**
36
+ * Headless release gate. Status loading never delays application rendering;
37
+ * consumers decide how to present maintenance and mandatory-update states.
38
+ */
39
+ export declare function useReleaseGate({ loadStatus, fallbackMinimumVersion, iosAppStoreId, androidPackageName, }: UseReleaseGateOptions): ReleaseGateResult;