@linked.cm/capacitor 0.3.6 → 0.3.7

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,11 @@
1
1
  # @linked.cm/capacitor
2
2
 
3
+ ## 0.3.7
4
+
5
+ ### Patch Changes
6
+
7
+ - [#24](https://github.com/linked-cm/capacitor/pull/24) [`c975917`](https://github.com/linked-cm/capacitor/commit/c975917de2b4d53822a2e6ea751960e2b183b21a) Thanks [@abdipramana](https://github.com/abdipramana)! - Fix manual Capgo OTA downloads by forwarding the checksum returned by `getLatest()` to the native downloader. Encrypted and delta updates now also receive the returned session key and manifest.
8
+
3
9
  ## 0.3.6
4
10
 
5
11
  ### Patch Changes
@@ -0,0 +1,69 @@
1
+ ---
2
+ summary: Fixed manual Capgo OTA downloads so integrity, encryption, and delta metadata returned by the update service reaches the native downloader.
3
+ ---
4
+
5
+ # OTA download metadata forwarding
6
+
7
+ ## Outcome
8
+
9
+ The automatic-update hook now passes all download-specific metadata returned by
10
+ `CapacitorUpdater.getLatest()` into `CapacitorUpdater.download()`. Previously it
11
+ passed only the bundle URL and version, which caused native installations that
12
+ require integrity verification to reject an otherwise valid update with
13
+ `Checksum required`.
14
+
15
+ The forwarded fields are:
16
+
17
+ - `checksum`, for native bundle integrity verification;
18
+ - `sessionKey`, for encrypted bundles; and
19
+ - `manifest`, for multi-file delta updates.
20
+
21
+ URL and version forwarding is unchanged.
22
+
23
+ ## Implementation
24
+
25
+ `src/hooks/useAutomaticUpdates.ts` owns the manual update sequence. Its new
26
+ `getDownloadOptions()` mapping keeps the boundary between the update-service
27
+ response and the native download call explicit and independently testable. The
28
+ hook uses that mapping only after confirming that `getLatest()` returned a URL.
29
+
30
+ The helper is exported from the existing hook subpath. This keeps the mapping
31
+ available to package consumers that need to construct the same native download
32
+ options without duplicating the security-sensitive field list.
33
+
34
+ ## Decisions
35
+
36
+ The hook forwards the complete set of fields accepted by Capgo's
37
+ `DownloadOptions`, instead of fixing only the observed checksum omission. This
38
+ avoids equivalent failures when encrypted or delta delivery is enabled.
39
+
40
+ Optional fields remain optional. Unencrypted full-ZIP updates therefore retain
41
+ their existing behavior while checksum-bearing responses preserve their
42
+ integrity contract.
43
+
44
+ No architecture document changed. The update flow and package boundary remain
45
+ the same; this corrects metadata propagation inside the existing flow.
46
+
47
+ ## Verification
48
+
49
+ `tests/automatic-updates.test.mjs` covers complete metadata forwarding and the
50
+ absence of optional metadata. The package test suite builds the ESM output
51
+ before executing tests, so the assertions exercise the same compiled helper
52
+ that consumers import.
53
+
54
+ Validation completed successfully:
55
+
56
+ - package test suite: 28 tests passed;
57
+ - full package build: passed; and
58
+ - whitespace/error check with `git diff --check`: passed.
59
+
60
+ ## Release and operational notes
61
+
62
+ The change has a patch changeset because it fixes published behavior without
63
+ changing the existing hook API. Applications whose currently installed native
64
+ bundle contains the broken downloader still require a native store release to
65
+ receive this fix; that broken downloader cannot install its own corrective OTA.
66
+ Once a native build containing the corrected package is installed, subsequent
67
+ checksum-protected OTA updates can use the normal channel flow.
68
+
69
+ No remaining code or documentation gaps were found in this scope.
@@ -11,6 +11,7 @@
11
11
  * 4. Check maintenance (HEAD request to SITE_ROOT) → on start + every 1 min
12
12
  * 5. If server up → getLatest() → download with progress → set + reload
13
13
  */
14
+ import { type DownloadOptions, type LatestVersion } from '@capgo/capacitor-updater';
14
15
  export type OTAStatus = 'idle' | 'downloading' | 'complete' | 'error';
15
16
  export type UseAutomaticUpdatesState = {
16
17
  otaStatus: OTAStatus;
@@ -19,4 +20,7 @@ export type UseAutomaticUpdatesState = {
19
20
  retryOTA: () => void;
20
21
  retryMaintenanceCheck: () => void;
21
22
  };
23
+ export declare const getDownloadOptions: (latest: LatestVersion & {
24
+ url: string;
25
+ }) => DownloadOptions;
22
26
  export declare const useAutomaticUpdates: () => UseAutomaticUpdatesState;
@@ -12,7 +12,7 @@
12
12
  * 5. If server up → getLatest() → download with progress → set + reload
13
13
  */
14
14
  import { useEffect, useRef, useState, useCallback } from 'react';
15
- import { CapacitorUpdater } from '@capgo/capacitor-updater';
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
18
  const MAINTENANCE_CHECK_INTERVAL_MS = 60 * 1000; // 1 minute
@@ -36,6 +36,13 @@ const isNoUpdateCondition = (error) => {
36
36
  message.includes('no_new_version_available') ||
37
37
  message.includes('disable_auto_update'));
38
38
  };
39
+ export const getDownloadOptions = (latest) => ({
40
+ url: latest.url,
41
+ version: latest.version,
42
+ checksum: latest.checksum,
43
+ sessionKey: latest.sessionKey,
44
+ manifest: latest.manifest,
45
+ });
39
46
  export const useAutomaticUpdates = () => {
40
47
  const [otaStatus, setOtaStatus] = useState('idle');
41
48
  const [otaProgress, setOtaProgress] = useState(0);
@@ -100,10 +107,7 @@ export const useAutomaticUpdates = () => {
100
107
  });
101
108
  try {
102
109
  // download() resolves when complete and returns BundleInfo { id, version, ... }
103
- const bundle = await CapacitorUpdater.download({
104
- url: latest.url,
105
- version: latest.version,
106
- });
110
+ const bundle = await CapacitorUpdater.download(getDownloadOptions({ ...latest, url: latest.url }));
107
111
  progressHandle.remove();
108
112
  // Show "Update ready, restarting..." briefly before reload
109
113
  setOtaStatus('complete');
@@ -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,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EACL,SAAS,EACT,qBAAqB,GAEtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,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E,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 { CapacitorUpdater } 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 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 url: latest.url,\n version: latest.version,\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;AAY5C,MAAM,6BAA6B,GAAG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BACjD,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"]}
package/package.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "type": "git",
11
11
  "url": "git+ssh://git@github.com/linked-cm/capacitor.git"
12
12
  },
13
- "version": "0.3.6",
13
+ "version": "0.3.7",
14
14
  "linkedPackage": true,
15
15
  "type": "module",
16
16
  "main": "lib/esm/index.js",
@@ -0,0 +1,47 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { getDownloadOptions } from '../lib/esm/hooks/useAutomaticUpdates.js';
5
+
6
+ test('forwards integrity and delivery metadata from getLatest to download', () => {
7
+ const manifest = [
8
+ {
9
+ file_name: 'assets/index.js',
10
+ file_hash: 'file-checksum',
11
+ download_url: 'https://updates.example/assets/index.js',
12
+ },
13
+ ];
14
+
15
+ assert.deepEqual(
16
+ getDownloadOptions({
17
+ url: 'https://updates.example/bundle.zip',
18
+ version: '4.3.2',
19
+ checksum: 'bundle-checksum',
20
+ sessionKey: 'encrypted-session-key',
21
+ manifest,
22
+ }),
23
+ {
24
+ url: 'https://updates.example/bundle.zip',
25
+ version: '4.3.2',
26
+ checksum: 'bundle-checksum',
27
+ sessionKey: 'encrypted-session-key',
28
+ manifest,
29
+ }
30
+ );
31
+ });
32
+
33
+ test('keeps optional download metadata optional', () => {
34
+ assert.deepEqual(
35
+ getDownloadOptions({
36
+ url: 'https://updates.example/bundle.zip',
37
+ version: '4.3.2',
38
+ }),
39
+ {
40
+ url: 'https://updates.example/bundle.zip',
41
+ version: '4.3.2',
42
+ checksum: undefined,
43
+ sessionKey: undefined,
44
+ manifest: undefined,
45
+ }
46
+ );
47
+ });