native-update-capacitor 0.0.0-stage → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/AI-INTEGRATION-GUIDE.md +578 -0
  2. package/LICENSE +25 -0
  3. package/NativeUpdate.podspec +19 -0
  4. package/README.md +574 -2
  5. package/android/build.gradle +125 -0
  6. package/android/consumer-rules.pro +9 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  8. package/android/gradle.properties +17 -0
  9. package/android/manifest-additions.xml +28 -0
  10. package/android/proguard-rules.pro +26 -0
  11. package/android/settings.gradle +2 -0
  12. package/android/src/main/AndroidManifest.xml +13 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
  20. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
  21. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
  22. package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
  23. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
  24. package/android/variables.gradle +5 -0
  25. package/cli/commands/backend-create.js +623 -0
  26. package/cli/commands/bundle-create.js +145 -0
  27. package/cli/commands/bundle-sign.js +64 -0
  28. package/cli/commands/bundle-verify.js +58 -0
  29. package/cli/commands/init.js +146 -0
  30. package/cli/commands/keys-generate.js +58 -0
  31. package/cli/commands/monitor.js +89 -0
  32. package/cli/commands/remote-shared.js +262 -0
  33. package/cli/commands/remote.js +622 -0
  34. package/cli/commands/server-start.js +96 -0
  35. package/cli/index.js +605 -0
  36. package/cli/package.json +21 -0
  37. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  38. package/dist/esm/app-review/app-review-manager.js +194 -0
  39. package/dist/esm/app-review/index.d.ts +5 -0
  40. package/dist/esm/app-review/index.js +5 -0
  41. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  42. package/dist/esm/app-review/platform-review-handler.js +137 -0
  43. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  44. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  45. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  46. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  47. package/dist/esm/app-review/types.d.ts +41 -0
  48. package/dist/esm/app-review/types.js +1 -0
  49. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  50. package/dist/esm/app-update/app-update-checker.js +227 -0
  51. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  52. package/dist/esm/app-update/app-update-installer.js +134 -0
  53. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  54. package/dist/esm/app-update/app-update-manager.js +198 -0
  55. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  56. package/dist/esm/app-update/app-update-notifier.js +99 -0
  57. package/dist/esm/app-update/index.d.ts +6 -0
  58. package/dist/esm/app-update/index.js +6 -0
  59. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  60. package/dist/esm/app-update/platform-app-update.js +138 -0
  61. package/dist/esm/app-update/types.d.ts +58 -0
  62. package/dist/esm/app-update/types.js +11 -0
  63. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  64. package/dist/esm/background-update/background-scheduler.js +332 -0
  65. package/dist/esm/background-update/index.d.ts +3 -0
  66. package/dist/esm/background-update/index.js +2 -0
  67. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  68. package/dist/esm/background-update/notification-manager.js +88 -0
  69. package/dist/esm/config/support.d.ts +9 -0
  70. package/dist/esm/config/support.js +9 -0
  71. package/dist/esm/core/analytics.d.ts +83 -0
  72. package/dist/esm/core/analytics.js +151 -0
  73. package/dist/esm/core/cache-manager.d.ts +72 -0
  74. package/dist/esm/core/cache-manager.js +274 -0
  75. package/dist/esm/core/config.d.ts +69 -0
  76. package/dist/esm/core/config.js +107 -0
  77. package/dist/esm/core/errors.d.ts +56 -0
  78. package/dist/esm/core/errors.js +85 -0
  79. package/dist/esm/core/event-emitter.d.ts +30 -0
  80. package/dist/esm/core/event-emitter.js +80 -0
  81. package/dist/esm/core/logger.d.ts +21 -0
  82. package/dist/esm/core/logger.js +108 -0
  83. package/dist/esm/core/performance.d.ts +53 -0
  84. package/dist/esm/core/performance.js +153 -0
  85. package/dist/esm/core/plugin-manager.d.ts +88 -0
  86. package/dist/esm/core/plugin-manager.js +224 -0
  87. package/dist/esm/core/security.d.ts +123 -0
  88. package/dist/esm/core/security.js +361 -0
  89. package/dist/esm/core/update-check.d.ts +121 -0
  90. package/dist/esm/core/update-check.js +127 -0
  91. package/dist/esm/definitions.d.ts +872 -0
  92. package/dist/esm/definitions.js +104 -0
  93. package/dist/esm/index.d.ts +14 -0
  94. package/dist/esm/index.js +18 -0
  95. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  96. package/dist/esm/live-update/bundle-manager.js +344 -0
  97. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  98. package/dist/esm/live-update/certificate-pinning.js +77 -0
  99. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  100. package/dist/esm/live-update/delta-processor.js +257 -0
  101. package/dist/esm/live-update/download-manager.d.ts +106 -0
  102. package/dist/esm/live-update/download-manager.js +412 -0
  103. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  104. package/dist/esm/live-update/rollout-checker.js +304 -0
  105. package/dist/esm/live-update/update-manager.d.ts +63 -0
  106. package/dist/esm/live-update/update-manager.js +321 -0
  107. package/dist/esm/live-update/version-manager.d.ts +93 -0
  108. package/dist/esm/live-update/version-manager.js +390 -0
  109. package/dist/esm/plugin.d.ts +3 -0
  110. package/dist/esm/plugin.js +848 -0
  111. package/dist/esm/security/crypto.d.ts +88 -0
  112. package/dist/esm/security/crypto.js +228 -0
  113. package/dist/esm/security/validator.d.ts +60 -0
  114. package/dist/esm/security/validator.js +142 -0
  115. package/dist/esm/types/app-identity.d.ts +36 -0
  116. package/dist/esm/types/app-identity.js +1 -0
  117. package/dist/esm/types/rollout.d.ts +91 -0
  118. package/dist/esm/types/rollout.js +25 -0
  119. package/dist/esm/web.d.ts +130 -0
  120. package/dist/esm/web.js +981 -0
  121. package/dist/plugin.cjs +1 -0
  122. package/dist/plugin.esm.js +1 -0
  123. package/dist/plugin.js +2 -0
  124. package/docs/CHANGELOG.md +993 -0
  125. package/docs/KNOWN_LIMITATIONS.md +235 -0
  126. package/docs/MIGRATION.md +391 -0
  127. package/docs/protocol/CLIENT-PROTOCOL.md +178 -0
  128. package/docs/server-requirements.md +211 -0
  129. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  130. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  131. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  133. package/ios/Plugin/Info.plist +43 -0
  134. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  135. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  136. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  137. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  138. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  139. package/package.json +135 -4
@@ -0,0 +1,163 @@
1
+ import { Logger } from '../core/logger';
2
+ export class ReviewRateLimiter {
3
+ constructor(config) {
4
+ this.storageKey = 'cap_review_rate_limit';
5
+ // Platform-specific limits
6
+ this.IOS_MAX_PROMPTS_PER_YEAR = 3;
7
+ this.ANDROID_MIN_DAYS_BETWEEN = 30; // Recommended
8
+ this.DEFAULT_MIN_DAYS_BETWEEN = 90;
9
+ this.config = config;
10
+ this.logger = new Logger('ReviewRateLimiter');
11
+ }
12
+ async canRequestReview() {
13
+ const data = await this.getRateLimitData();
14
+ const platform = this.getPlatform();
15
+ // Check last request date
16
+ if (data.lastRequestDate) {
17
+ const daysSinceLastRequest = this.getDaysSince(data.lastRequestDate);
18
+ const minDays = this.getMinDaysBetweenPrompts(platform);
19
+ if (daysSinceLastRequest < minDays) {
20
+ return {
21
+ canRequest: false,
22
+ reason: `Only ${daysSinceLastRequest} days since last prompt, need ${minDays}`,
23
+ };
24
+ }
25
+ }
26
+ // iOS-specific: Check yearly limit
27
+ if (platform === 'ios') {
28
+ const currentYear = new Date().getFullYear().toString();
29
+ const requestsThisYear = data.requestsByYear[currentYear] || 0;
30
+ if (requestsThisYear >= this.IOS_MAX_PROMPTS_PER_YEAR) {
31
+ return {
32
+ canRequest: false,
33
+ reason: `iOS limit reached: ${requestsThisYear}/${this.IOS_MAX_PROMPTS_PER_YEAR} prompts this year`,
34
+ };
35
+ }
36
+ }
37
+ // Check version-specific limits
38
+ const currentVersion = await this.getCurrentVersion();
39
+ const requestsThisVersion = data.requestsByVersion[currentVersion] || 0;
40
+ const maxPerVersion = this.config.maxPromptsPerVersion || 1;
41
+ if (requestsThisVersion >= maxPerVersion) {
42
+ return {
43
+ canRequest: false,
44
+ reason: `Version limit reached: ${requestsThisVersion}/${maxPerVersion} prompts for v${currentVersion}`,
45
+ };
46
+ }
47
+ return {
48
+ canRequest: true,
49
+ };
50
+ }
51
+ async recordRequest(wasDisplayed = true) {
52
+ const data = await this.getRateLimitData();
53
+ const currentVersion = await this.getCurrentVersion();
54
+ const currentYear = new Date().getFullYear().toString();
55
+ // Update counters
56
+ data.totalRequests++;
57
+ data.lastRequestDate = Date.now();
58
+ if (wasDisplayed) {
59
+ data.successfulDisplays++;
60
+ }
61
+ // Update version-specific count
62
+ if (!data.requestsByVersion[currentVersion]) {
63
+ data.requestsByVersion[currentVersion] = 0;
64
+ }
65
+ data.requestsByVersion[currentVersion]++;
66
+ // Update year-specific count (for iOS)
67
+ if (!data.requestsByYear[currentYear]) {
68
+ data.requestsByYear[currentYear] = 0;
69
+ }
70
+ data.requestsByYear[currentYear]++;
71
+ await this.saveRateLimitData(data);
72
+ this.logger.log('Recorded review request', {
73
+ total: data.totalRequests,
74
+ version: currentVersion,
75
+ year: currentYear,
76
+ });
77
+ }
78
+ async reset() {
79
+ await this.saveRateLimitData({
80
+ totalRequests: 0,
81
+ successfulDisplays: 0,
82
+ requestsByVersion: {},
83
+ requestsByYear: {},
84
+ });
85
+ }
86
+ async getMetrics() {
87
+ const data = await this.getRateLimitData();
88
+ const installDate = await this.getInstallDate();
89
+ return {
90
+ totalRequests: data.totalRequests,
91
+ successfulDisplays: data.successfulDisplays,
92
+ lastRequestDate: data.lastRequestDate
93
+ ? new Date(data.lastRequestDate)
94
+ : undefined,
95
+ requestsByVersion: data.requestsByVersion,
96
+ significantEvents: [], // This would come from conditions checker
97
+ appLaunches: 0, // This would come from conditions checker
98
+ installDate: new Date(installDate),
99
+ };
100
+ }
101
+ async getRateLimitData() {
102
+ try {
103
+ const stored = localStorage.getItem(this.storageKey);
104
+ if (stored) {
105
+ return JSON.parse(stored);
106
+ }
107
+ }
108
+ catch (error) {
109
+ this.logger.error('Failed to read rate limit data', error);
110
+ }
111
+ return {
112
+ totalRequests: 0,
113
+ successfulDisplays: 0,
114
+ requestsByVersion: {},
115
+ requestsByYear: {},
116
+ };
117
+ }
118
+ async saveRateLimitData(data) {
119
+ try {
120
+ localStorage.setItem(this.storageKey, JSON.stringify(data));
121
+ }
122
+ catch (error) {
123
+ this.logger.error('Failed to save rate limit data', error);
124
+ }
125
+ }
126
+ getDaysSince(timestamp) {
127
+ const msPerDay = 24 * 60 * 60 * 1000;
128
+ return Math.floor((Date.now() - timestamp) / msPerDay);
129
+ }
130
+ getMinDaysBetweenPrompts(platform) {
131
+ if (platform === 'android') {
132
+ return (this.config.minimumDaysSinceLastPrompt || this.ANDROID_MIN_DAYS_BETWEEN);
133
+ }
134
+ return (this.config.minimumDaysSinceLastPrompt || this.DEFAULT_MIN_DAYS_BETWEEN);
135
+ }
136
+ getPlatform() {
137
+ if (typeof window !== 'undefined') {
138
+ const userAgent = window.navigator.userAgent;
139
+ if (/android/i.test(userAgent)) {
140
+ return 'android';
141
+ }
142
+ else if (/iPad|iPhone|iPod/.test(userAgent)) {
143
+ return 'ios';
144
+ }
145
+ }
146
+ return 'web';
147
+ }
148
+ async getCurrentVersion() {
149
+ // This would be provided by the platform
150
+ return '1.0.0';
151
+ }
152
+ async getInstallDate() {
153
+ // This would be stored on first app launch
154
+ const installKey = 'cap_app_install_date';
155
+ const stored = localStorage.getItem(installKey);
156
+ if (stored) {
157
+ return parseInt(stored, 10);
158
+ }
159
+ const now = Date.now();
160
+ localStorage.setItem(installKey, now.toString());
161
+ return now;
162
+ }
163
+ }
@@ -0,0 +1,41 @@
1
+ export interface ReviewRequestResult {
2
+ displayed: boolean;
3
+ reason?: string;
4
+ platform: string;
5
+ lastRequestDate?: number;
6
+ requestCount?: number;
7
+ }
8
+ export interface ReviewAvailability {
9
+ canRequest: boolean;
10
+ reason?: string;
11
+ lastRequestDate?: number;
12
+ requestCount?: number;
13
+ daysUntilNext?: number;
14
+ }
15
+ export interface ReviewConditions {
16
+ minimumDaysSinceInstall?: number;
17
+ minimumDaysSinceLastPrompt?: number;
18
+ minimumAppLaunches?: number;
19
+ minimumSignificantEvents?: number;
20
+ requirePositiveEvents?: boolean;
21
+ maxPromptsPerVersion?: number;
22
+ customConditions?: Record<string, unknown>;
23
+ }
24
+ export interface StoreReviewUrl {
25
+ url: string;
26
+ platform: 'ios' | 'android' | 'web';
27
+ }
28
+ export interface ReviewRequestOptions {
29
+ force?: boolean;
30
+ useCustomUI?: boolean;
31
+ customMessage?: string;
32
+ }
33
+ export interface ReviewMetrics {
34
+ totalRequests: number;
35
+ successfulDisplays: number;
36
+ lastRequestDate?: Date;
37
+ requestsByVersion: Record<string, number>;
38
+ significantEvents: string[];
39
+ appLaunches: number;
40
+ installDate: Date;
41
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,58 @@
1
+ import { PluginConfig } from '../core/config';
2
+ import { AppUpdateInfo, AppUpdateOptions } from './types';
3
+ interface CachedAppInfo {
4
+ version: string;
5
+ build: string;
6
+ name: string;
7
+ id: string;
8
+ timestamp: number;
9
+ }
10
+ export declare class AppUpdateChecker {
11
+ private config;
12
+ private logger;
13
+ private cachedAppInfo;
14
+ private readonly CACHE_DURATION;
15
+ constructor(config: PluginConfig);
16
+ /**
17
+ * Query an OPTIONAL custom app-version endpoint for a newer native
18
+ * app-store binary. This is a self-hoster extension point, independent
19
+ * of the Native Update (Laravel) OTA backend — configure it via
20
+ * `updateUrl`. When `updateUrl` is unset (the default) this is a no-op.
21
+ *
22
+ * Contract the custom server must implement:
23
+ * ```
24
+ * GET {updateUrl}/app-version?platform={ios|android|web}&current={ver}[&channel={ch}]
25
+ * X-App-Version: <installed version> X-App-Platform: <platform>
26
+ * → 200 {
27
+ * "version": "2.1.0", // latest store version
28
+ * "priority": 3, // optional update priority
29
+ * "releaseNotes": "…", // optional
30
+ * "size": 12345, // optional bytes
31
+ * "downloadUrl": "https://…" // optional store/deeplink URL
32
+ * }
33
+ * ```
34
+ */
35
+ checkServerVersion(_?: AppUpdateOptions): Promise<Partial<AppUpdateInfo>>;
36
+ compareVersions(version1: string, version2: string): number;
37
+ isUpdateRequired(currentVersion: string, availableVersion: string, minimumVersion?: string): boolean;
38
+ determineUpdatePriority(versionDiff: string, stalenessDays?: number): number;
39
+ /**
40
+ * Get current app version using @capacitor/app
41
+ * Falls back to config or default if native API unavailable
42
+ */
43
+ getCurrentVersion(): Promise<string>;
44
+ /**
45
+ * Get current app build number
46
+ */
47
+ getCurrentBuild(): Promise<string>;
48
+ /**
49
+ * Get full app info
50
+ */
51
+ getAppInfo(): Promise<CachedAppInfo>;
52
+ /**
53
+ * Clear the cached app info (useful after updates)
54
+ */
55
+ clearCache(): void;
56
+ private getPlatform;
57
+ }
58
+ export {};
@@ -0,0 +1,227 @@
1
+ import { Logger } from '../core/logger';
2
+ export class AppUpdateChecker {
3
+ constructor(config) {
4
+ this.cachedAppInfo = null;
5
+ this.CACHE_DURATION = 60 * 1000; // 1 minute cache
6
+ this.config = config;
7
+ this.logger = new Logger('AppUpdateChecker');
8
+ }
9
+ /**
10
+ * Query an OPTIONAL custom app-version endpoint for a newer native
11
+ * app-store binary. This is a self-hoster extension point, independent
12
+ * of the Native Update (Laravel) OTA backend — configure it via
13
+ * `updateUrl`. When `updateUrl` is unset (the default) this is a no-op.
14
+ *
15
+ * Contract the custom server must implement:
16
+ * ```
17
+ * GET {updateUrl}/app-version?platform={ios|android|web}&current={ver}[&channel={ch}]
18
+ * X-App-Version: <installed version> X-App-Platform: <platform>
19
+ * → 200 {
20
+ * "version": "2.1.0", // latest store version
21
+ * "priority": 3, // optional update priority
22
+ * "releaseNotes": "…", // optional
23
+ * "size": 12345, // optional bytes
24
+ * "downloadUrl": "https://…" // optional store/deeplink URL
25
+ * }
26
+ * ```
27
+ */
28
+ async checkServerVersion(_) {
29
+ if (!this.config.updateUrl) {
30
+ return {};
31
+ }
32
+ try {
33
+ const currentVersion = await this.getCurrentVersion();
34
+ const url = new URL(`${this.config.updateUrl}/app-version`);
35
+ url.searchParams.append('platform', this.getPlatform());
36
+ url.searchParams.append('current', currentVersion);
37
+ if (this.config.channel) {
38
+ url.searchParams.append('channel', this.config.channel);
39
+ }
40
+ const response = await fetch(url.toString(), {
41
+ method: 'GET',
42
+ headers: {
43
+ Accept: 'application/json',
44
+ 'X-App-Version': currentVersion,
45
+ 'X-App-Platform': this.getPlatform(),
46
+ },
47
+ });
48
+ if (!response.ok) {
49
+ throw new Error(`Server returned ${response.status}`);
50
+ }
51
+ const data = await response.json();
52
+ return {
53
+ availableVersion: data.version,
54
+ updatePriority: data.priority,
55
+ releaseNotes: data.releaseNotes,
56
+ updateSize: data.size,
57
+ updateURL: data.downloadUrl,
58
+ };
59
+ }
60
+ catch (error) {
61
+ this.logger.error('Failed to check server version', error);
62
+ return {};
63
+ }
64
+ }
65
+ compareVersions(version1, version2) {
66
+ const v1Parts = version1.split('.').map(Number);
67
+ const v2Parts = version2.split('.').map(Number);
68
+ for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
69
+ const v1Part = v1Parts[i] || 0;
70
+ const v2Part = v2Parts[i] || 0;
71
+ if (v1Part > v2Part)
72
+ return 1;
73
+ if (v1Part < v2Part)
74
+ return -1;
75
+ }
76
+ return 0;
77
+ }
78
+ isUpdateRequired(currentVersion, availableVersion, minimumVersion) {
79
+ // Check if current version is less than available
80
+ if (this.compareVersions(currentVersion, availableVersion) < 0) {
81
+ return true;
82
+ }
83
+ // Check if current version meets minimum requirement
84
+ if (minimumVersion &&
85
+ this.compareVersions(currentVersion, minimumVersion) < 0) {
86
+ return true;
87
+ }
88
+ return false;
89
+ }
90
+ determineUpdatePriority(versionDiff, stalenessDays) {
91
+ // Parse version difference
92
+ const [major, minor] = versionDiff.split('.').map(Number);
93
+ // Major version change = IMMEDIATE (priority 5)
94
+ if (major > 0) {
95
+ return 5;
96
+ }
97
+ // Minor version with high staleness = HIGH (priority 4)
98
+ if (minor > 0 && stalenessDays && stalenessDays > 30) {
99
+ return 4;
100
+ }
101
+ // Minor version = MEDIUM (priority 3)
102
+ if (minor > 0) {
103
+ return 3;
104
+ }
105
+ // Patch version = LOW (priority 1)
106
+ return 1;
107
+ }
108
+ /**
109
+ * Get current app version using @capacitor/app
110
+ * Falls back to config or default if native API unavailable
111
+ */
112
+ async getCurrentVersion() {
113
+ // Check cache first
114
+ if (this.cachedAppInfo && Date.now() - this.cachedAppInfo.timestamp < this.CACHE_DURATION) {
115
+ return this.cachedAppInfo.version;
116
+ }
117
+ try {
118
+ // Try to use @capacitor/app for real version info
119
+ const { App } = await import('@capacitor/app');
120
+ const info = await App.getInfo();
121
+ // Cache the result
122
+ this.cachedAppInfo = {
123
+ version: info.version,
124
+ build: info.build,
125
+ name: info.name,
126
+ id: info.id,
127
+ timestamp: Date.now(),
128
+ };
129
+ this.logger.debug('Got app info from Capacitor', {
130
+ version: info.version,
131
+ build: info.build,
132
+ });
133
+ return info.version;
134
+ }
135
+ catch (error) {
136
+ this.logger.debug('Failed to get app info from Capacitor, using fallback', error);
137
+ // Fallback to config value or environment
138
+ const configAppVersion = this.config.appVersion;
139
+ if (typeof configAppVersion === 'string') {
140
+ return configAppVersion;
141
+ }
142
+ // Try to get from environment/window
143
+ if (typeof window !== 'undefined') {
144
+ const windowWithVersion = window;
145
+ if (typeof windowWithVersion.APP_VERSION === 'string') {
146
+ return windowWithVersion.APP_VERSION;
147
+ }
148
+ }
149
+ // Last resort fallback
150
+ return '1.0.0';
151
+ }
152
+ }
153
+ /**
154
+ * Get current app build number
155
+ */
156
+ async getCurrentBuild() {
157
+ // Check cache first
158
+ if (this.cachedAppInfo && Date.now() - this.cachedAppInfo.timestamp < this.CACHE_DURATION) {
159
+ return this.cachedAppInfo.build;
160
+ }
161
+ try {
162
+ const { App } = await import('@capacitor/app');
163
+ const info = await App.getInfo();
164
+ // Cache the result
165
+ this.cachedAppInfo = {
166
+ version: info.version,
167
+ build: info.build,
168
+ name: info.name,
169
+ id: info.id,
170
+ timestamp: Date.now(),
171
+ };
172
+ return info.build;
173
+ }
174
+ catch (_a) {
175
+ return '1';
176
+ }
177
+ }
178
+ /**
179
+ * Get full app info
180
+ */
181
+ async getAppInfo() {
182
+ // Check cache first
183
+ if (this.cachedAppInfo && Date.now() - this.cachedAppInfo.timestamp < this.CACHE_DURATION) {
184
+ return this.cachedAppInfo;
185
+ }
186
+ try {
187
+ const { App } = await import('@capacitor/app');
188
+ const info = await App.getInfo();
189
+ this.cachedAppInfo = {
190
+ version: info.version,
191
+ build: info.build,
192
+ name: info.name,
193
+ id: info.id,
194
+ timestamp: Date.now(),
195
+ };
196
+ return this.cachedAppInfo;
197
+ }
198
+ catch (_a) {
199
+ return {
200
+ version: '1.0.0',
201
+ build: '1',
202
+ name: 'App',
203
+ id: 'com.app',
204
+ timestamp: Date.now(),
205
+ };
206
+ }
207
+ }
208
+ /**
209
+ * Clear the cached app info (useful after updates)
210
+ */
211
+ clearCache() {
212
+ this.cachedAppInfo = null;
213
+ }
214
+ getPlatform() {
215
+ // Detect platform
216
+ if (typeof window !== 'undefined') {
217
+ const userAgent = window.navigator.userAgent;
218
+ if (/android/i.test(userAgent)) {
219
+ return 'android';
220
+ }
221
+ else if (/iPad|iPhone|iPod/.test(userAgent)) {
222
+ return 'ios';
223
+ }
224
+ }
225
+ return 'web';
226
+ }
227
+ }
@@ -0,0 +1,20 @@
1
+ import { PluginConfig } from '../core/config';
2
+ import { AppUpdateProgress, AppUpdateState } from './types';
3
+ export declare class AppUpdateInstaller {
4
+ private logger;
5
+ private progressCallback?;
6
+ private currentState;
7
+ private flexibleUpdateInterval;
8
+ constructor(_: PluginConfig);
9
+ startImmediateUpdate(): Promise<void>;
10
+ startFlexibleUpdate(): Promise<void>;
11
+ completeFlexibleUpdate(): Promise<void>;
12
+ cancelUpdate(): Promise<void>;
13
+ getInstallState(): Promise<AppUpdateState>;
14
+ onProgress(callback: (progress: AppUpdateProgress) => void): void;
15
+ private updateState;
16
+ private simulateFlexibleUpdate;
17
+ private isAndroid;
18
+ private isIOS;
19
+ private isWeb;
20
+ }
@@ -0,0 +1,134 @@
1
+ import { Logger } from '../core/logger';
2
+ import { AppUpdateInstallStatus, } from './types';
3
+ export class AppUpdateInstaller {
4
+ constructor(_) {
5
+ this.flexibleUpdateInterval = null;
6
+ this.logger = new Logger('AppUpdateInstaller');
7
+ this.currentState = {
8
+ installStatus: AppUpdateInstallStatus.UNKNOWN,
9
+ packageName: '',
10
+ availableVersion: '',
11
+ };
12
+ }
13
+ async startImmediateUpdate() {
14
+ this.logger.log('Starting immediate update installation');
15
+ // Update state
16
+ this.updateState(AppUpdateInstallStatus.PENDING);
17
+ // On Android, this would trigger Play Core immediate update
18
+ // On iOS, this would open App Store
19
+ if (this.isAndroid()) {
20
+ // Android implementation would use Play Core Library
21
+ this.logger.log('Triggering Android immediate update');
22
+ }
23
+ else if (this.isIOS()) {
24
+ // iOS implementation would open App Store
25
+ this.logger.log('Opening iOS App Store for update');
26
+ }
27
+ else {
28
+ // Web fallback
29
+ throw new Error('Immediate updates not supported on web platform');
30
+ }
31
+ }
32
+ async startFlexibleUpdate() {
33
+ this.logger.log('Starting flexible update download');
34
+ // Update state
35
+ this.updateState(AppUpdateInstallStatus.DOWNLOADING);
36
+ // Start download simulation for web
37
+ if (this.isWeb()) {
38
+ this.simulateFlexibleUpdate();
39
+ }
40
+ else if (this.isAndroid()) {
41
+ // Android implementation would use Play Core Library
42
+ this.logger.log('Starting Android flexible update');
43
+ }
44
+ else {
45
+ // iOS doesn't support flexible updates
46
+ throw new Error('Flexible updates not supported on iOS');
47
+ }
48
+ }
49
+ async completeFlexibleUpdate() {
50
+ this.logger.log('Completing flexible update installation');
51
+ if (this.currentState.installStatus !== AppUpdateInstallStatus.DOWNLOADED) {
52
+ throw new Error('Update not ready for installation');
53
+ }
54
+ // Update state
55
+ this.updateState(AppUpdateInstallStatus.INSTALLING);
56
+ // Trigger installation
57
+ if (this.isAndroid()) {
58
+ // Android implementation would complete the update
59
+ this.logger.log('Completing Android update installation');
60
+ }
61
+ else {
62
+ // Simulate completion
63
+ setTimeout(() => {
64
+ this.updateState(AppUpdateInstallStatus.INSTALLED);
65
+ }, 1000);
66
+ }
67
+ }
68
+ async cancelUpdate() {
69
+ this.logger.log('Cancelling update');
70
+ // Stop the simulated download interval. Without this, the interval
71
+ // runs forever even after cancel because the only previous exit was
72
+ // a "download finished" branch.
73
+ if (this.flexibleUpdateInterval) {
74
+ clearInterval(this.flexibleUpdateInterval);
75
+ this.flexibleUpdateInterval = null;
76
+ }
77
+ if (this.currentState.installStatus === AppUpdateInstallStatus.DOWNLOADING) {
78
+ this.updateState(AppUpdateInstallStatus.CANCELED);
79
+ }
80
+ }
81
+ async getInstallState() {
82
+ return Object.assign({}, this.currentState);
83
+ }
84
+ onProgress(callback) {
85
+ this.progressCallback = callback;
86
+ }
87
+ updateState(status, errorCode) {
88
+ this.currentState.installStatus = status;
89
+ if (errorCode !== undefined) {
90
+ this.currentState.installErrorCode = errorCode;
91
+ }
92
+ this.logger.log('Update state changed', this.currentState);
93
+ }
94
+ simulateFlexibleUpdate() {
95
+ let downloaded = 0;
96
+ const totalSize = 50 * 1024 * 1024;
97
+ const chunkSize = 1024 * 1024;
98
+ if (this.flexibleUpdateInterval) {
99
+ clearInterval(this.flexibleUpdateInterval);
100
+ }
101
+ this.flexibleUpdateInterval = setInterval(() => {
102
+ downloaded += chunkSize;
103
+ if (downloaded >= totalSize) {
104
+ downloaded = totalSize;
105
+ if (this.flexibleUpdateInterval) {
106
+ clearInterval(this.flexibleUpdateInterval);
107
+ this.flexibleUpdateInterval = null;
108
+ }
109
+ this.updateState(AppUpdateInstallStatus.DOWNLOADED);
110
+ }
111
+ const progress = {
112
+ bytesDownloaded: downloaded,
113
+ totalBytesToDownload: totalSize,
114
+ percentComplete: Math.round((downloaded / totalSize) * 100),
115
+ downloadSpeed: chunkSize,
116
+ estimatedTime: Math.ceil((totalSize - downloaded) / chunkSize),
117
+ };
118
+ if (this.progressCallback) {
119
+ this.progressCallback(progress);
120
+ }
121
+ }, 1000);
122
+ }
123
+ isAndroid() {
124
+ return (typeof window !== 'undefined' &&
125
+ /android/i.test(window.navigator.userAgent));
126
+ }
127
+ isIOS() {
128
+ return (typeof window !== 'undefined' &&
129
+ /iPad|iPhone|iPod/.test(window.navigator.userAgent));
130
+ }
131
+ isWeb() {
132
+ return !this.isAndroid() && !this.isIOS();
133
+ }
134
+ }
@@ -0,0 +1,28 @@
1
+ import { PluginConfig } from '../core/config';
2
+ import { AppUpdateInfo, AppUpdateOptions, VersionInfo, MinimumVersionCheck, AppUpdateState } from './types';
3
+ import { AppUpdatePlugin } from '../definitions';
4
+ import { PluginListenerHandle } from '@capacitor/core';
5
+ export declare class AppUpdateManager implements AppUpdatePlugin {
6
+ private config;
7
+ private logger;
8
+ private checker;
9
+ private installer;
10
+ private platformUpdate;
11
+ private listeners;
12
+ constructor(config: PluginConfig);
13
+ checkAppUpdate(options?: AppUpdateOptions): Promise<AppUpdateInfo>;
14
+ startImmediateUpdate(): Promise<void>;
15
+ startFlexibleUpdate(): Promise<void>;
16
+ completeFlexibleUpdate(): Promise<void>;
17
+ getVersionInfo(): Promise<VersionInfo>;
18
+ isMinimumVersionMet(): Promise<MinimumVersionCheck>;
19
+ getAppUpdateInfo(): Promise<AppUpdateInfo>;
20
+ performImmediateUpdate(): Promise<void>;
21
+ openAppStore(_options?: import('../definitions').OpenAppStoreOptions): Promise<void>;
22
+ private getAppStoreUrl;
23
+ getUpdateInstallState(): Promise<AppUpdateState>;
24
+ addListener(eventName: string, listenerFunc: (data: unknown) => void): PluginListenerHandle;
25
+ removeAllListeners(eventName?: string): Promise<void>;
26
+ private emit;
27
+ private mergeUpdateInfo;
28
+ }