From f791a378f51958110fd0e4e110b6dee6f59576cf Mon Sep 17 00:00:00 2001 From: iletai Date: Sat, 3 Oct 2026 21:17:17 +0700 Subject: [PATCH] feat: headless-first architecture, pluggable evaluator, vector banner, and trilingual docs --- README.ja.md | 181 ++++++++++ README.md | 337 +++++------------- README.vi.md | 181 ++++++++++ .../AppUpdateKit/Core/AppUpdateAction.swift | 84 ++++- .../AppUpdateKit/Core/AppUpdateChecker.swift | 53 +-- .../AppUpdateKit/Core/AppUpdateConfig.swift | 36 +- .../Core/AppUpdateEvaluator.swift | 67 ++++ .../AppUpdateKit/Core/AppUpdateEvent.swift | 20 +- .../AppUpdateKit/Core/AppUpdateManager.swift | 138 +++++-- Sources/AppUpdateKit/Core/AppVersion.swift | 84 +++-- .../UI/AppUpdateAlertModifier.swift | 40 ++- .../AppUpdateKit/UI/AppUpdateCardView.swift | 6 +- .../AppUpdateKit/UI/AppUpdatePresenter.swift | 23 +- .../AppUpdateCheckerTests.swift | 22 +- .../AppUpdateEventTests.swift | 88 +++-- .../AppUpdateManagerTests.swift | 18 +- art/banner.svg | 95 +++++ 17 files changed, 1035 insertions(+), 438 deletions(-) create mode 100644 README.ja.md create mode 100644 README.vi.md create mode 100644 Sources/AppUpdateKit/Core/AppUpdateEvaluator.swift create mode 100644 art/banner.svg diff --git a/README.ja.md b/README.ja.md new file mode 100644 index 0000000..07ce35e --- /dev/null +++ b/README.ja.md @@ -0,0 +1,181 @@ +

+ AppUpdateKit Banner +

+ +

+ CI Status + Swift バージョン + 対応プラットフォーム + 外部依存関係ゼロ + ライセンス +

+ +

+ 🌐 Language Selection / Chọn ngôn ngữ / 言語選択:
+ 🇬🇧 English  |  + 🇻🇳 Tiếng Việt  |  + 🇯🇵 日本語 +

+ +--- + +# AppUpdateKit + +**AppUpdateKit** は、完全な **Headless-First** 設計を採用した超軽量・依存関係ゼロ(Zero Dependency)の Swift Package です。**microCMS** や **Raw JSON (GitHub Raw, S3, Cloudflare Workers)** などを介して、アプリの強制アップデート(Force Update)、任意アップデート(Optional Update・更新履歴付き)、およびメンテナンスモード(Maintenance Mode)をリモートで制御します。 + +### 🌟 主な特徴 & 設計思想 +- **完全な Headless 設計(UI の強制なし):** 純粋なビジネスロジックエンジン (`AppUpdateChecker`, `AppUpdateEvaluator`, `AppVersion`, `AppUpdateConfig`) を提供します。標準 UI の使用は強制されません。生のモデル、メタデータ、バージョンオブジェクト、イベントストリームがすべて公開されているため、独自のカスタム UI、モーダル、または React Native / Flutter ブリッジを自由に構築できます。 +- **外部依存性ゼロ:** Apple 標準フレームワーク (`Foundation`, `SwiftUI`, `Combine`, `UIKit`) のみで動作。 +- **O(N) SemVer 比較エンジン:** バージョン文字列の正規化 (`"1.2"` == `"1.2.0"` == `"1.2.0.0"`, `"1.10.0"` > `"1.2.0"`) およびプレリリースタグ・ビルドメタデータの自動除去に対応。 +- **フェイルセーフ設計:** ネットワークエラー、タイムアウト、または不正な JSON が発生した場合でも、クラッシュせずに `.none` へ安全にフォールバック。 +- **詳細なイベント&アナリティクス対応:** `checkStarted`, `configFetched`, `evaluated`, `presented`, `userAction`, `checkFailed` を出力し、Firebase や Mixpanel と連携可能。 +- **Swift 6 & Sendable 完全対応:** `@MainActor` の安全性と Task 重複排除を備えた完全なスレッドセーフ設計。 + +--- + +## 📱 UI プレビュー + +``` +┌────────────────────────────────────────┐ ┌────────────────────────────────────────┐ +│ Update Available │ │ ╭────────────╮ │ +│ │ │ │ 🔄 │ │ +│ A new version (2.1.0) is available on │ │ ╰────────────╯ │ +│ the App Store. Would you like to get │ │ Bản Cập Nhật Mới 2.1.0 │ +│ the latest features? │ │ Trải nghiệm giao diện mới và sửa lỗi. │ +│ │ │ │ +│ │ │ ┌── Có gì mới: ────────────────────┐ │ +│ │ │ │ • ✨ Giao diện Liquid Glass │ │ +│ │ │ │ • ⚡️ Tối ưu tốc độ tải 40% │ │ +│ ┌──────────────────┐┌───────────────┐ │ │ │ • 🐛 Sửa lỗi offline sync │ │ +│ │ Để sau (Later)││Cập nhật(Update│ │ │ └──────────────────────────────────┘ │ +│ └──────────────────┘└───────────────┘ │ │ ┌──────────────────────────────────┐ │ +│ │ │ │ Cập nhật ngay (Update) │ │ +│ │ │ └──────────────────────────────────┘ │ +│ │ │ Để sau │ +└────────────────────────────────────────┘ └────────────────────────────────────────┘ + [ SwiftUI / UIKit Alert ] [ Custom SwiftUI Card Sheet ] +``` + +--- + +## 🚀 クイックスタート (100% Headless / カスタム UI) + +UI コードを使用せず、純粋な判定ロジックのみを使用する例: + +```swift +import AppUpdateKit + +let fetcher = AppUpdateFetcher.microCMS( + endpoint: URL(string: "https://your-service.microcms.io/api/v1/app-update")!, + apiKey: "YOUR_API_KEY" +) + +// 非同期でアップデート状態をチェック(フェイルセーフ対応) +let action: AppUpdateAction = await AppUpdateChecker.check( + onEvent: { event in + Analytics.logEvent("app_update_lifecycle", parameters: ["event": "\(event)"]) + }, + fetcher: fetcher +) + +// 独自の View、モーダル、または Coordinator でアクションを処理 +switch action { +case .none: + print("アプリは最新バージョンです") +case .optionalUpdate(let title, let message, let storeURL, let version, let releaseNotes, let metadata): + MyCustomDialogPresenter.showOptionalUpdate(title: title, version: version?.description, url: storeURL) +case .forceUpdate(let title, let message, let storeURL, let version, let releaseNotes, let metadata): + MyCustomDialogPresenter.showBlockingUpdate(title: title, url: storeURL) +case .maintenance(let title, let message, let metadata): + MyCustomDialogPresenter.showMaintenanceScreen(message: message) +case .custom(let id, let title, let message, let storeURL, _, _, _): + MyCustomDialogPresenter.handleCustomAction(id: id) +} +``` + +--- + +## 🎨 組み込み UI モディファイア(任意) + +### 1. SwiftUI 標準アラート +```swift +ContentView() + .appUpdateAlert( + action: $updateAction, + configuration: AppUpdateUIConfiguration( + updateButtonTitle: "今すぐ更新", + laterButtonTitle: "後で", + dismissButtonTitle: "OK" + ), + onEvent: { event in + print("[AppUpdateKit] Event: \(event)") + } + ) +``` + +### 2. SwiftUI カスタムカードシート +```swift +ContentView() + .appUpdateSheet( + action: $updateAction, + accentColor: .indigo, + onEvent: { event in + if case .userAction(let action, let choice) = event { + print("User tapped \(choice) for \(action.title ?? "")") + } + } + ) +``` + +### 3. UIKit との連携 (`UIViewController`) +```swift +class ViewController: UIViewController { + func checkVersion() { + Task { [weak self] in + let action = await AppUpdateChecker.check(fetcher: fetcher) + self?.presentAppUpdate(action: action) + } + } +} +``` + +--- + +## 📊 Semantic Versioning 判定マトリクス + +| 現在のバージョン | リモート最小必須 | リモート最新 | 判定アクション | アプリの挙動 | +| :--- | :--- | :--- | :--- | :--- | +| `1.0.0` | `2.0.0` | `2.5.0` | `.forceUpdate` | 🚨 強制アップデートダイアログ(操作ブロック) | +| `2.0.0` | `1.5.0` | `2.1.0` | `.optionalUpdate` | 💡 任意アップデートダイアログ(「後で」ボタンあり) | +| `2.1.0` | `1.5.0` | `2.1.0` | `.none` | ✅ アプリは最新 | +| `2.1.0.0` | `1.5.0` | `2.1` | `.none` | ✅ 正規化による一致判定 | +| `任意` | `任意` | `任意` (`is_maintenance: true`) | `.maintenance` | 🛠️ アプリをロック、メンテナンス画面を表示 | +| `1.0.0` | 通信エラー (404/500/Timeout) | N/A | `.none` | 🛡️ フェイルセーフ: 通常通り起動 | + +--- + +## 🛠️ microCMS API スキーマ設定 + +| フィールド ID | 表示名 | 種類 | 説明 | +| :--- | :--- | :--- | :--- | +| `minimum_version` | 最低必須バージョン | テキスト | これ未満のバージョンで強制アップデートを発火 | +| `latest_version` | 最新バージョン | テキスト | App Store で公開中の最新バージョン | +| `store_url` | ストア URL | テキスト | App Store または TestFlight のリンク | +| `is_maintenance` | メンテナンス中 | 真偽値 | メンテナンスモードの切り替えフラグ | +| `title` | ダイアログタイトル | テキスト (任意) | カスタムタイトル | +| `message` | ダイアログ本文 | 複数行テキスト (任意) | カスタム説明文 | +| `release_notes` | 更新内容 | 複数行テキスト / リスト | 箇条書きのリリースノート | + +--- + +## 📦 インストール方法 (SPM) + +```swift +dependencies: [ + .package(url: "https://github.com/iletai/AppUpdateKit.git", from: "1.1.0") +] +``` + +## 📄 ライセンス + +AppUpdateKit は **MIT ライセンス** の下で公開されています。Copyright (c) 2026 iletai. diff --git a/README.md b/README.md index 9a7659f..25ef636 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,39 @@ -# AppUpdateKit -

- AppUpdateKit Banner + AppUpdateKit Banner

CI Status Swift Version - Platforms + Platforms Zero Dependencies License

-**AppUpdateKit** is an ultra-lightweight, zero-dependency Swift Package for evaluating app versions, enforcing **Force Updates**, presenting **Optional Updates** (with release notes), and activating **Maintenance Mode** remotely via **microCMS**, **Raw JSON (GitHub Raw, S3, Cloudflare Workers)**, or any backend endpoint. +

+ 🌐 Language Selection / Chọn ngôn ngữ / 言語選択:
+ 🇬🇧 English  |  + 🇻🇳 Tiếng Việt  |  + 🇯🇵 日本語 +

--- -## 📱 Visual UI Preview +# AppUpdateKit -### 1. Native Alert vs. Custom Card Sheet +**AppUpdateKit** is an ultra-lightweight, zero-dependency, **headless-first** Swift Package for evaluating app versions, enforcing **Force Updates**, presenting **Optional Updates** (with release notes), and activating **Maintenance Mode** remotely via **microCMS**, **Raw JSON (GitHub Raw, S3, Cloudflare Workers)**, or any backend endpoint. + +### 🛡️ Core Values & Design Principles +- **100% Headless-First (UI is strictly optional):** AppUpdateKit is built as a pure business logic engine (`AppUpdateChecker`, `AppUpdateEvaluator`, `AppVersion`, `AppUpdateConfig`). You are **never forced to use our UI**. All raw models, metadata, version objects, and event streams are exposed so you can render your own custom dialogs, sheets, or bridges (React Native, Flutter). +- **Zero Third-Party Dependencies:** Pure Swift Standard Library (`Foundation`, `SwiftUI`, `Combine`, `UIKit`). +- **O(N) SemVer Normalizer:** Vector integer comparator (`"1.2"` == `"1.2.0"` == `"1.2.0.0"`, `"1.10.0"` > `"1.2.0"`), stripping prerelease tags and build metadata. +- **Fail-Safe by Default:** Network errors, timeouts, or corrupt JSON gracefully fallback to `.none` without crashing or blocking users. +- **Full Lifecycle Events & Analytics:** Emits granular events (`checkStarted`, `configFetched`, `evaluated`, `presented`, `userAction`, `checkFailed`) for Firebase, Mixpanel, and custom logging. +- **Swift 6 & Sendable Compliant:** Fully concurrency-safe with `@MainActor` safety and Task deduplication. + +--- + +## 📱 Visual UI Preview ``` ┌────────────────────────────────────────┐ ┌────────────────────────────────────────┐ @@ -41,214 +56,84 @@ [ SwiftUI / UIKit Alert ] [ Custom SwiftUI Card Sheet ] ``` -### 2. Force Update (Mandatory) vs. Maintenance Mode - -``` -┌────────────────────────────────────────┐ ┌────────────────────────────────────────┐ -│ Update Required │ │ Hệ Thống Bảo Trì │ -│ ⚠️ │ │ 🛠️ │ -│ This version is deprecated. Please │ │ Hệ thống đang bảo trì định kỳ để │ -│ update to continue using the service. │ │ nâng cấp server. Vui lòng quay lại │ -│ │ │ sau ít phút. │ -│ │ │ │ -│ ┌──────────────────────────────────┐ │ │ ┌──────────────────────────────────┐ │ -│ │ Cập nhật ngay │ │ │ │ Đã hiểu │ │ -│ └──────────────────────────────────┘ │ │ └──────────────────────────────────┘ │ -└────────────────────────────────────────┘ └────────────────────────────────────────┘ - [ Non-dismissable Modal ] [ Server Maintenance Modal ] -``` - --- -## 🌟 Highlights & Architecture - -- **Zero Third-Party Dependencies:** 100% Apple Native (`Foundation`, `SwiftUI`, `Combine`, `UIKit`). -- **O(N) SemVer Normalizer:** Integer vector comparison (`"1.2"` == `"1.2.0"` == `"1.2.0.0"`, `"1.10.0"` > `"1.2.0"`), safely stripping prerelease tags and build metadata. -- **Fail-Safe by Default:** Network errors, timeouts, or corrupt JSON gracefully fallback to `.none` without crashing or blocking users. -- **Decoupled Architecture:** Pure logic engine (`AppUpdateChecker.evaluate`) is fully separated from I/O fetchers and UI presentation. -- **Full Lifecycle Events & Analytics:** Emits granular events (`checkStarted`, `configFetched`, `evaluated`, `presented`, `userAction`, `checkFailed`) for Firebase, Mixpanel, and Telemetry tracking. -- **Swift 6 & Sendable Compliant:** Zero data races, `@MainActor` UI safety. +## 🚀 Quick Start (100% Headless / Custom UI) -``` - ┌──────────────────────┐ ┌──────────────────────┐ - │ microCMS / JSON │───────▶│ AppUpdateFetcher │ - └──────────────────────┘ └──────────┬───────────┘ - │ async throws -> AppUpdateConfig - ▼ - ┌──────────────────────┐ ┌──────────────────────┐ - │ AppVersion │───────▶│ AppUpdateChecker │ - └──────────────────────┘ └──────────┬───────────┘ - │ AppUpdateAction - ▼ - ┌──────────────────────────────────────────────────────────────┐ - │ AppUpdateAction Types │ - │ • .none │ - │ • .optionalUpdate(title, message, storeURL, releaseNotes) │ - │ • .forceUpdate(title, message, storeURL, releaseNotes) │ - │ • .maintenance(title, message) │ - └──────────────────────────────┬───────────────────────────────┘ - │ - ┌─────────────────────┴─────────────────────┐ - ▼ ▼ -┌──────────────────┐ ┌──────────────────┐ -│ SwiftUI View │ │ UIKit Helper │ -│ .appUpdateAlert │ │ presentAppUpdate │ -│ .appUpdateSheet │ │ (Controllers) │ -└──────────────────┘ └──────────────────┘ -``` - ---- - -## 📦 Installation - -### Swift Package Manager (SPM) - -In Xcode, select **File > Add Package Dependencies...** and enter: - -``` -https://github.com/iletai/AppUpdateKit.git -``` - -Or add directly to `Package.swift`: +Use pure evaluation logic without touching any UI code: ```swift -dependencies: [ - .package(url: "https://github.com/iletai/AppUpdateKit.git", from: "1.0.0") -] -``` +import AppUpdateKit ---- +let fetcher = AppUpdateFetcher.microCMS( + endpoint: URL(string: "https://your-service.microcms.io/api/v1/app-update")!, + apiKey: "YOUR_API_KEY" +) + +// Check update status asynchronously (fail-safe) +let action: AppUpdateAction = await AppUpdateChecker.check( + onEvent: { event in + Analytics.logEvent("app_update_lifecycle", parameters: ["event": "\(event)"]) + }, + fetcher: fetcher +) -## 🛠️ Remote Backend Configuration - -`AppUpdateKit` supports both `snake_case` and `camelCase` response payloads. - -### JSON Payload Schema - -```json -{ - "minimum_version": "1.0.0", - "latest_version": "2.1.0", - "store_url": "https://apps.apple.com/app/id123456789", - "is_maintenance": false, - "title": "Bản cập nhật mới 2.1.0", - "message": "Nhiều tính năng mới hấp dẫn và sửa lỗi hiệu năng.", - "release_notes": [ - "✨ Hỗ trợ giao diện Liquid Glass & Dark Mode", - "⚡️ Tối ưu hóa hiệu năng khởi động nhanh hơn 40%", - "🐛 Sửa lỗi đồng bộ dữ liệu" - ] +// Handle action in your own custom View, Modal, or Coordinator +switch action { +case .none: + print("App is up-to-date") +case .optionalUpdate(let title, let message, let storeURL, let version, let releaseNotes, let metadata): + MyCustomDialogPresenter.showOptionalUpdate(title: title, version: version?.description, url: storeURL) +case .forceUpdate(let title, let message, let storeURL, let version, let releaseNotes, let metadata): + MyCustomDialogPresenter.showBlockingUpdate(title: title, url: storeURL) +case .maintenance(let title, let message, let metadata): + MyCustomDialogPresenter.showMaintenanceScreen(message: message) +case .custom(let id, let title, let message, let storeURL, _, _, _): + MyCustomDialogPresenter.handleCustomAction(id: id) } ``` -### microCMS Setup Schema - -| Field ID | Field Name | Type | Description | -| :--- | :--- | :--- | :--- | -| `minimum_version` | Minimum Required Version | Text | Versions below this trigger mandatory Force Update (e.g. `1.0.0`) | -| `latest_version` | Latest Version | Text | Latest version available on App Store (e.g. `2.1.0`) | -| `store_url` | App Store URL | Text | Link to App Store or TestFlight | -| `is_maintenance` | Maintenance Mode | Boolean | Toggle maintenance state | -| `title` | Dialog Title | Text (Optional) | Custom title | -| `message` | Dialog Message | TextArea (Optional) | Custom description | -| `release_notes` | Release Notes | TextArea / List (Optional) | Bullet points or newline-separated notes | - --- -## 🚀 Usage Guide +## 🎨 Optional Pre-built UI Modifiers ### 1. SwiftUI Native Alert - ```swift -import SwiftUI -import AppUpdateKit - -@main -struct MyApp: App { - @State private var updateAction: AppUpdateAction = .none - - var body: some Scene { - WindowGroup { - ContentView() - .appUpdateAlert( - action: $updateAction, - configuration: AppUpdateUIConfiguration( - updateButtonTitle: "Cập nhật", - laterButtonTitle: "Để sau", - dismissButtonTitle: "Đã hiểu" - ), - onEvent: { event in - print("AppUpdate Event: \(event)") - } - ) - .task { - let fetcher = AppUpdateFetcher.microCMS( - endpoint: URL(string: "https://your-service.microcms.io/api/v1/app-update")!, - apiKey: "YOUR_MICROCMS_API_KEY" - ) - updateAction = await AppUpdateChecker.check(fetcher: fetcher) - } +ContentView() + .appUpdateAlert( + action: $updateAction, + configuration: AppUpdateUIConfiguration( + updateButtonTitle: "Update Now", + laterButtonTitle: "Later", + dismissButtonTitle: "OK" + ), + onEvent: { event in + print("[AppUpdateKit] Event: \(event)") } - } -} + ) ``` ---- - -### 2. SwiftUI Custom Sheet with Release Notes - +### 2. SwiftUI Custom Card Sheet ```swift ContentView() .appUpdateSheet( action: $updateAction, accentColor: .indigo, onEvent: { event in - // Handle Analytics if case .userAction(let action, let choice) = event { - Analytics.logEvent("update_prompt_interaction", parameters: [ - "choice": "\(choice)", - "action_title": action.title ?? "" - ]) + print("User tapped \(choice) for \(action.title ?? "")") } } ) ``` ---- - ### 3. UIKit Integration (`UIViewController`) - ```swift -import UIKit -import AppUpdateKit - -class MainViewController: UIViewController { - override func viewDidAppear(_ animated: Bool) { - super.viewDidAppear(animated) - checkForUpdates() - } - - private func checkForUpdates() { +class ViewController: UIViewController { + func checkVersion() { Task { [weak self] in - guard let self = self else { return } - - let fetcher = AppUpdateFetcher.json( - url: URL(string: "https://your-domain.com/app-update.json")! - ) - let action = await AppUpdateChecker.check(fetcher: fetcher) - - self.presentAppUpdate( - action: action, - configuration: AppUpdateUIConfiguration( - updateButtonTitle: "Cập nhật ngay", - laterButtonTitle: "Bỏ qua", - dismissButtonTitle: "Đóng" - ), - onEvent: { event in - print("[AppUpdateKit] \(event)") - } - ) + self?.presentAppUpdate(action: action) } } } @@ -256,81 +141,41 @@ class MainViewController: UIViewController { --- -### 4. Stateful Manager & Throttling Policy (`AppUpdateManager`) +## 📊 Semantic Versioning Comparison Matrix -Use `AppUpdateManager` to prevent hammering servers on every app active: +| Current Version | Remote Minimum | Remote Latest | Evaluated Action | Application Behavior | +| :--- | :--- | :--- | :--- | :--- | +| `1.0.0` | `2.0.0` | `2.5.0` | `.forceUpdate` | 🚨 Blocking update required to proceed | +| `2.0.0` | `1.5.0` | `2.1.0` | `.optionalUpdate` | 💡 Show update prompt (with "Later" button) | +| `2.1.0` | `1.5.0` | `2.1.0` | `.none` | ✅ App is on latest version | +| `2.1.0.0` | `1.5.0` | `2.1` | `.none` | ✅ Vector-normalized match | +| `any` | `any` | `any` (`is_maintenance: true`) | `.maintenance` | 🛠️ Lock app, show maintenance screen | +| `1.0.0` | Network Error (404/500/Timeout) | N/A | `.none` | 🛡️ Fail-safe: app functions normally | -```swift -let manager = AppUpdateManager.shared +--- -// Check once per session -await manager.check( - policy: .oncePerSession, - fetcher: fetcher -) +## 🛠️ microCMS API Schema -// Or check at most once every 24 hours -await manager.check( - policy: .interval(24 * 3600), - fetcher: fetcher -) -``` +| Field ID | Display Name | Type | Description | +| :--- | :--- | :--- | :--- | +| `minimum_version` | Minimum Version | Text | Versions below this trigger force update | +| `latest_version` | Latest Version | Text | Current latest version on App Store | +| `store_url` | Store URL | Text | App Store or TestFlight link | +| `is_maintenance` | Is Maintenance | Boolean | System maintenance toggle flag | +| `title` | Title | Text (Optional) | Custom dialog title | +| `message` | Message | Multi-line Text (Optional) | Custom explanation message | +| `release_notes` | Release Notes | Multi-line Text / Array | Bullet list of release notes | --- -### 5. Unit Testing with Pure Logic Engine - -You can test version evaluation deterministically without mocking network calls: +## 📦 Installation (SPM) ```swift -import XCTest -import AppUpdateKit - -final class AppVersionPolicyTests: XCTestCase { - func testForceUpdateTriggered() { - let config = AppUpdateConfig( - minimumVersion: "2.0.0", - latestVersion: "2.5.0", - storeURL: URL(string: "https://apps.apple.com/app/id123")! - ) - - let action = AppUpdateChecker.evaluate( - currentVersion: AppVersion("1.9.9"), - config: config - ) - - XCTAssertTrue(action.isRequired) - XCTAssertTrue(action.isBlocking) - XCTAssertEqual(action.storeURL, config.storeURL) - } -} +dependencies: [ + .package(url: "https://github.com/iletai/AppUpdateKit.git", from: "1.1.0") +] ``` ---- - -## 📊 Semantic Versioning Matrix - -| Current Version | Remote Minimum | Remote Latest | Evaluated Action | Behavior | -| :--- | :--- | :--- | :--- | :--- | -| `1.0.0` | `2.0.0` | `2.5.0` | `.forceUpdate` | 🚨 User must update to continue | -| `2.0.0` | `1.5.0` | `2.1.0` | `.optionalUpdate` | 💡 Update prompt with "Later" option | -| `2.1.0` | `1.5.0` | `2.1.0` | `.none` | ✅ App is up-to-date | -| `2.1.0.0` | `1.5.0` | `2.1` | `.none` | ✅ Normalized version match | -| `any` | `any` | `any` (`isMaintenance: true`) | `.maintenance` | 🛠️ Full blocking maintenance mode | -| `1.0.0` | Network Error (404/500/Timeout) | N/A | `.none` | 🛡️ Fail-safe: app opens normally | - ---- - -## 📋 Example Project - -Check out the interactive demo in the [`Examples/`](Examples/) folder: -- **`Examples/SwiftUI/AppUpdateDemoView.swift`**: Full SwiftUI simulator. -- **`Examples/UIKit/ViewController.swift`**: UIKit implementation. -- **`Examples/microcms-schema.json`**: Ready-to-import microCMS schema. -- **`Examples/config.json`**: Sample JSON config payload. - ---- - ## 📄 License -AppUpdateKit is released under the **MIT License**. See [LICENSE](LICENSE) for details. +AppUpdateKit is released under the **MIT License**. Copyright (c) 2026 iletai. diff --git a/README.vi.md b/README.vi.md new file mode 100644 index 0000000..a5f504f --- /dev/null +++ b/README.vi.md @@ -0,0 +1,181 @@ +

+ AppUpdateKit Banner +

+ +

+ CI Status + Phiên bản Swift + Nền tảng + Không phụ thuộc + Giấy phép +

+ +

+ 🌐 Language Selection / Chọn ngôn ngữ / 言語選択:
+ 🇬🇧 English  |  + 🇻🇳 Tiếng Việt  |  + 🇯🇵 日本語 +

+ +--- + +# AppUpdateKit + +**AppUpdateKit** là thư viện Swift Package Manager (SPM) siêu nhẹ, zero-dependency, thiết kế theo triết lý **Headless-First (Không ép buộc dùng UI có sẵn)**. Hỗ trợ kiểm tra phiên bản ứng dụng, kích hoạt **Force Update (Cập nhật bắt buộc)**, **Optional Update (Cập nhật tùy chọn kèm Release Notes)**, và **Maintenance Mode (Bảo trì hệ thống)** từ xa qua **microCMS**, **Raw JSON (GitHub Raw, S3, Cloudflare Workers)**, hoặc bất kỳ API backend nào. + +### 🌟 Điểm nổi bật & Triết lý thiết kế +- **Headless-First 100% (UI hoàn toàn tùy chọn):** AppUpdateKit được xây dựng như một Pure Business Logic Engine (`AppUpdateChecker`, `AppUpdateEvaluator`, `AppVersion`, `AppUpdateConfig`). Bạn **không bao giờ bị ép buộc dùng UI mặc định**. Toàn bộ raw models, metadata, version object và event stream được mở hoàn toàn để bạn tự render giao diện custom, modal, hoặc bridge qua React Native / Flutter. +- **0 Dependency bên ngoài:** Thuần Swift Standard Library (`Foundation`, `SwiftUI`, `Combine`, `UIKit`). +- **Bộ so sánh SemVer O(N):** Chuẩn hóa so sánh vector số nguyên (`"1.2"` == `"1.2.0"` == `"1.2.0.0"`, `"1.10.0"` > `"1.2.0"`), tự động loại bỏ tag prerelease và build metadata. +- **An toàn tuyệt đối (Fail-Safe):** Khi mất mạng, server timeout hoặc JSON hỏng, app tự fallback về `.none`, không làm crash hoặc block user khởi động app. +- **Vòng đời Event & Analytics chi tiết:** Bắn đầy đủ sự kiện (`checkStarted`, `configFetched`, `evaluated`, `presented`, `userAction`, `checkFailed`) cho Firebase Analytics, Mixpanel, TelemetryDeck. +- **Tương thích Swift 6 & Sendable:** An toàn tuyệt đối với `@MainActor` và Task deduplication. + +--- + +## 📱 Minh họa Giao diện (Visual UI Preview) + +``` +┌────────────────────────────────────────┐ ┌────────────────────────────────────────┐ +│ Update Available │ │ ╭────────────╮ │ +│ │ │ │ 🔄 │ │ +│ A new version (2.1.0) is available on │ │ ╰────────────╯ │ +│ the App Store. Would you like to get │ │ Bản Cập Nhật Mới 2.1.0 │ +│ the latest features? │ │ Trải nghiệm giao diện mới và sửa lỗi. │ +│ │ │ │ +│ │ │ ┌── Có gì mới: ────────────────────┐ │ +│ │ │ │ • ✨ Giao diện Liquid Glass │ │ +│ │ │ │ • ⚡️ Tối ưu tốc độ tải 40% │ │ +│ ┌──────────────────┐┌───────────────┐ │ │ │ • 🐛 Sửa lỗi offline sync │ │ +│ │ Để sau (Later)││Cập nhật(Update│ │ │ └──────────────────────────────────┘ │ +│ └──────────────────┘└───────────────┘ │ │ ┌──────────────────────────────────┐ │ +│ │ │ │ Cập nhật ngay (Update) │ │ +│ │ │ └──────────────────────────────────┘ │ +│ │ │ Để sau │ +└────────────────────────────────────────┘ └────────────────────────────────────────┘ + [ SwiftUI / UIKit Alert ] [ Custom SwiftUI Card Sheet ] +``` + +--- + +## 🚀 Quick Start (100% Headless / Custom UI) + +Sử dụng logic kiểm tra thuần túy mà không đụng đến code UI: + +```swift +import AppUpdateKit + +let fetcher = AppUpdateFetcher.microCMS( + endpoint: URL(string: "https://your-service.microcms.io/api/v1/app-update")!, + apiKey: "YOUR_API_KEY" +) + +// Kiểm tra trạng thái cập nhật bất đồng bộ (fail-safe) +let action: AppUpdateAction = await AppUpdateChecker.check( + onEvent: { event in + Analytics.logEvent("app_update_lifecycle", parameters: ["event": "\(event)"]) + }, + fetcher: fetcher +) + +// Xử lý action trong View, Modal hoặc Coordinator riêng của bạn +switch action { +case .none: + print("Ứng dụng đang ở bản mới nhất") +case .optionalUpdate(let title, let message, let storeURL, let version, let releaseNotes, let metadata): + MyCustomDialogPresenter.showOptionalUpdate(title: title, version: version?.description, url: storeURL) +case .forceUpdate(let title, let message, let storeURL, let version, let releaseNotes, let metadata): + MyCustomDialogPresenter.showBlockingUpdate(title: title, url: storeURL) +case .maintenance(let title, let message, let metadata): + MyCustomDialogPresenter.showMaintenanceScreen(message: message) +case .custom(let id, let title, let message, let storeURL, _, _, _): + MyCustomDialogPresenter.handleCustomAction(id: id) +} +``` + +--- + +## 🎨 UI Modifiers Có Sẵn (Tùy chọn) + +### 1. SwiftUI Native Alert +```swift +ContentView() + .appUpdateAlert( + action: $updateAction, + configuration: AppUpdateUIConfiguration( + updateButtonTitle: "Cập nhật ngay", + laterButtonTitle: "Để sau", + dismissButtonTitle: "Đồng ý" + ), + onEvent: { event in + print("[AppUpdateKit] Event: \(event)") + } + ) +``` + +### 2. SwiftUI Custom Card Sheet +```swift +ContentView() + .appUpdateSheet( + action: $updateAction, + accentColor: .indigo, + onEvent: { event in + if case .userAction(let action, let choice) = event { + print("User tapped \(choice) for \(action.title ?? "")") + } + } + ) +``` + +### 3. Tích hợp UIKit (`UIViewController`) +```swift +class ViewController: UIViewController { + func checkVersion() { + Task { [weak self] in + let action = await AppUpdateChecker.check(fetcher: fetcher) + self?.presentAppUpdate(action: action) + } + } +} +``` + +--- + +## 📊 Bảng so sánh Semantic Versioning + +| Version hiện tại | Remote Minimum | Remote Latest | Action trả về | Hành vi ứng dụng | +| :--- | :--- | :--- | :--- | :--- | +| `1.0.0` | `2.0.0` | `2.5.0` | `.forceUpdate` | 🚨 Bắt buộc cập nhật để tiếp tục | +| `2.0.0` | `1.5.0` | `2.1.0` | `.optionalUpdate` | 💡 Hiện thông báo cập nhật (có nút "Để sau") | +| `2.1.0` | `1.5.0` | `2.1.0` | `.none` | ✅ App đã ở bản mới nhất | +| `2.1.0.0` | `1.5.0` | `2.1` | `.none` | ✅ Chuẩn hóa chuỗi version trùng khớp | +| `bất kỳ` | `bất kỳ` | `bất kỳ` (`is_maintenance: true`) | `.maintenance` | 🛠️ Khóa ứng dụng, hiện màn hình bảo trì | +| `1.0.0` | Lỗi mạng (404/500/Timeout) | N/A | `.none` | 🛡️ Fail-safe: app hoạt động bình thường | + +--- + +## 🛠️ Cấu hình API Schema microCMS + +| Field ID | Tên hiển thị | Loại dữ liệu | Mô tả | +| :--- | :--- | :--- | :--- | +| `minimum_version` | Phiên bản tối thiểu | Text | Nhỏ hơn bản này sẽ kích hoạt cập nhật bắt buộc | +| `latest_version` | Phiên bản mới nhất | Text | Phiên bản mới nhất đang có trên App Store | +| `store_url` | Đường dẫn App Store | Text | Link đến App Store hoặc TestFlight | +| `is_maintenance` | Đang bảo trì | Boolean | Cờ bật/tắt chế độ bảo trì | +| `title` | Tiêu đề | Text (Tùy chọn) | Tiêu đề thông báo custom | +| `message` | Nội dung | Multi-line Text (Tùy chọn) | Mô tả chi tiết custom | +| `release_notes` | Nội dung cập nhật | Multi-line Text / Array | Danh sách các thay đổi mới | + +--- + +## 📦 Cài đặt (SPM) + +```swift +dependencies: [ + .package(url: "https://github.com/iletai/AppUpdateKit.git", from: "1.1.0") +] +``` + +## 📄 Giấy phép (License) + +AppUpdateKit được phát hành theo **Giấy phép MIT**. Bản quyền (c) 2026 iletai. diff --git a/Sources/AppUpdateKit/Core/AppUpdateAction.swift b/Sources/AppUpdateKit/Core/AppUpdateAction.swift index c75fb31..c31f8a6 100644 --- a/Sources/AppUpdateKit/Core/AppUpdateAction.swift +++ b/Sources/AppUpdateKit/Core/AppUpdateAction.swift @@ -1,25 +1,27 @@ import Foundation /// User choices during update prompts. -public enum AppUpdateUserChoice: Sendable, Equatable { +public enum AppUpdateUserChoice: Sendable, Equatable, Codable { case update(url: URL) case remindLater case dismiss + case custom(id: String) } /// Action to take based on app update evaluation. -public enum AppUpdateAction: Sendable, Equatable { +public enum AppUpdateAction: Sendable, Equatable, Codable { case `none` - case optionalUpdate(title: String, message: String, storeURL: URL, releaseNotes: [String]? = nil) - case forceUpdate(title: String, message: String, storeURL: URL, releaseNotes: [String]? = nil) - case maintenance(title: String, message: String) + case optionalUpdate(title: String, message: String, storeURL: URL, version: AppVersion? = nil, releaseNotes: [String]? = nil, metadata: [String: String]? = nil) + case forceUpdate(title: String, message: String, storeURL: URL, version: AppVersion? = nil, releaseNotes: [String]? = nil, metadata: [String: String]? = nil) + case maintenance(title: String, message: String, metadata: [String: String]? = nil) + case custom(id: String, title: String? = nil, message: String? = nil, storeURL: URL? = nil, version: AppVersion? = nil, releaseNotes: [String]? = nil, metadata: [String: String]? = nil) /// Returns `true` if the update requires blocking user interaction (force update or maintenance). public var isBlocking: Bool { switch self { case .forceUpdate, .maintenance: return true - case .none, .optionalUpdate: + case .none, .optionalUpdate, .custom: return false } } @@ -29,7 +31,7 @@ public enum AppUpdateAction: Sendable, Equatable { switch self { case .optionalUpdate, .forceUpdate: return true - case .none, .maintenance: + case .none, .maintenance, .custom: return false } } @@ -39,7 +41,7 @@ public enum AppUpdateAction: Sendable, Equatable { switch self { case .forceUpdate: return true - case .none, .optionalUpdate, .maintenance: + case .none, .optionalUpdate, .maintenance, .custom: return false } } @@ -49,19 +51,33 @@ public enum AppUpdateAction: Sendable, Equatable { switch self { case .maintenance: return true - case .none, .optionalUpdate, .forceUpdate: + case .none, .optionalUpdate, .forceUpdate, .custom: return false } } + /// Returns `true` if this is a custom action. + public var isCustom: Bool { + if case .custom = self { return true } + return false + } + + /// Custom action ID if applicable. + public var customID: String? { + if case .custom(let id, _, _, _, _, _, _) = self { return id } + return nil + } + /// Extracted title of the action if applicable. public var title: String? { switch self { case .none: return nil - case .optionalUpdate(let title, _, _, _), - .forceUpdate(let title, _, _, _), - .maintenance(let title, _): + case .optionalUpdate(let title, _, _, _, _, _), + .forceUpdate(let title, _, _, _, _, _), + .maintenance(let title, _, _): + return title + case .custom(_, let title, _, _, _, _, _): return title } } @@ -71,9 +87,11 @@ public enum AppUpdateAction: Sendable, Equatable { switch self { case .none: return nil - case .optionalUpdate(_, let message, _, _), - .forceUpdate(_, let message, _, _), - .maintenance(_, let message): + case .optionalUpdate(_, let message, _, _, _, _), + .forceUpdate(_, let message, _, _, _, _), + .maintenance(_, let message, _): + return message + case .custom(_, _, let message, _, _, _, _): return message } } @@ -81,22 +99,50 @@ public enum AppUpdateAction: Sendable, Equatable { /// Target App Store or download URL if applicable. public var storeURL: URL? { switch self { - case .optionalUpdate(_, _, let url, _), - .forceUpdate(_, _, let url, _): + case .optionalUpdate(_, _, let url, _, _, _), + .forceUpdate(_, _, let url, _, _, _): + return url + case .custom(_, _, _, let url, _, _, _): return url case .none, .maintenance: return nil } } + /// Target new version if provided by configuration. + public var version: AppVersion? { + switch self { + case .optionalUpdate(_, _, _, let ver, _, _), + .forceUpdate(_, _, _, let ver, _, _), + .custom(_, _, _, _, let ver, _, _): + return ver + case .none, .maintenance: + return nil + } + } + /// Optional changelog or release notes bullet points. public var releaseNotes: [String]? { switch self { - case .optionalUpdate(_, _, _, let notes), - .forceUpdate(_, _, _, let notes): + case .optionalUpdate(_, _, _, _, let notes, _), + .forceUpdate(_, _, _, _, let notes, _), + .custom(_, _, _, _, _, let notes, _): return notes case .none, .maintenance: return nil } } + + /// Extra custom metadata dictionary from backend payload. + public var metadata: [String: String]? { + switch self { + case .optionalUpdate(_, _, _, _, _, let meta), + .forceUpdate(_, _, _, _, _, let meta), + .maintenance(_, _, let meta), + .custom(_, _, _, _, _, _, let meta): + return meta + case .none: + return nil + } + } } diff --git a/Sources/AppUpdateKit/Core/AppUpdateChecker.swift b/Sources/AppUpdateKit/Core/AppUpdateChecker.swift index 54b0dc2..c9ac599 100644 --- a/Sources/AppUpdateKit/Core/AppUpdateChecker.swift +++ b/Sources/AppUpdateKit/Core/AppUpdateChecker.swift @@ -8,51 +8,18 @@ public enum AppUpdateChecker { return AppVersion(version) } - /// Evaluates pure business logic to determine update action. + /// Evaluates pure business logic using standard or custom evaluator. public static func evaluate( currentVersion: AppVersion, config: AppUpdateConfig, - defaultStoreURL: URL? = nil + defaultStoreURL: URL? = nil, + evaluator: AppUpdateEvaluator = DefaultAppUpdateEvaluator() ) -> AppUpdateAction { - let title = config.title?.trimmingCharacters(in: .whitespacesAndNewlines) - let message = config.message?.trimmingCharacters(in: .whitespacesAndNewlines) - - if config.isMaintenance { - return .maintenance( - title: (title?.isEmpty == false) ? title! : "Maintenance", - message: (message?.isEmpty == false) ? message! : "The service is currently undergoing maintenance. Please try again later." - ) - } - - let storeURL = config.storeURL ?? defaultStoreURL - - if let minVerStr = config.minimumVersion, - !minVerStr.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - let minVersion = AppVersion(minVerStr) - if currentVersion < minVersion, let storeURL = storeURL { - return .forceUpdate( - title: (title?.isEmpty == false) ? title! : "Update Required", - message: (message?.isEmpty == false) ? message! : "A new version of the app is available. Please update to continue.", - storeURL: storeURL, - releaseNotes: config.releaseNotes - ) - } - } - - if let latestVerStr = config.latestVersion, - !latestVerStr.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - let latestVersion = AppVersion(latestVerStr) - if currentVersion < latestVersion, let storeURL = storeURL { - return .optionalUpdate( - title: (title?.isEmpty == false) ? title! : "Update Available", - message: (message?.isEmpty == false) ? message! : "A new version of the app is available. Would you like to update now?", - storeURL: storeURL, - releaseNotes: config.releaseNotes - ) - } - } - - return .none + return evaluator.evaluate( + currentVersion: currentVersion, + config: config, + defaultStoreURL: defaultStoreURL + ) } /// Asynchronously fetches update configuration and returns update action. @@ -60,6 +27,7 @@ public enum AppUpdateChecker { public static func check( currentVersion: AppVersion = currentInstalledVersion(), defaultStoreURL: URL? = nil, + evaluator: AppUpdateEvaluator = DefaultAppUpdateEvaluator(), onEvent: (@Sendable (AppUpdateEvent) -> Void)? = nil, fetcher: () async throws -> AppUpdateConfig ) async -> AppUpdateAction { @@ -71,7 +39,8 @@ public enum AppUpdateChecker { let action = evaluate( currentVersion: currentVersion, config: config, - defaultStoreURL: defaultStoreURL + defaultStoreURL: defaultStoreURL, + evaluator: evaluator ) onEvent?(.evaluated(action: action)) return action diff --git a/Sources/AppUpdateKit/Core/AppUpdateConfig.swift b/Sources/AppUpdateKit/Core/AppUpdateConfig.swift index 76d1d53..df688ea 100644 --- a/Sources/AppUpdateKit/Core/AppUpdateConfig.swift +++ b/Sources/AppUpdateKit/Core/AppUpdateConfig.swift @@ -1,6 +1,6 @@ import Foundation -/// Configuration model representing app update policies and remote settings. +/// Configuration model representing app update policies, remote settings, and custom metadata. public struct AppUpdateConfig: Codable, Sendable, Equatable { public let minimumVersion: String? public let latestVersion: String? @@ -9,6 +9,15 @@ public struct AppUpdateConfig: Codable, Sendable, Equatable { public let title: String? public let message: String? public let releaseNotes: [String]? + public let metadata: [String: String]? + + public var latestAppVersion: AppVersion? { + latestVersion.map { AppVersion($0) } + } + + public var minimumAppVersion: AppVersion? { + minimumVersion.map { AppVersion($0) } + } public init( minimumVersion: String? = nil, @@ -17,7 +26,8 @@ public struct AppUpdateConfig: Codable, Sendable, Equatable { isMaintenance: Bool = false, title: String? = nil, message: String? = nil, - releaseNotes: [String]? = nil + releaseNotes: [String]? = nil, + metadata: [String: String]? = nil ) { self.minimumVersion = minimumVersion self.latestVersion = latestVersion @@ -26,6 +36,7 @@ public struct AppUpdateConfig: Codable, Sendable, Equatable { self.title = title self.message = message self.releaseNotes = releaseNotes + self.metadata = metadata } private enum CodingKeys: String, CodingKey { @@ -43,6 +54,8 @@ public struct AppUpdateConfig: Codable, Sendable, Equatable { case releaseNotes case releaseNotesSnake = "release_notes" case changelog + case metadata + case customPayload = "custom_payload" } public init(from decoder: Decoder) throws { @@ -66,9 +79,18 @@ public struct AppUpdateConfig: Codable, Sendable, Equatable { self.storeURL = nil } - self.isMaintenance = (try? container.decodeIfPresent(Bool.self, forKey: .isMaintenance)) - ?? (try? container.decodeIfPresent(Bool.self, forKey: .isMaintenanceSnake)) - ?? false + // Support bool or string-boolean ("true" / "1") + if let boolVal = try? container.decodeIfPresent(Bool.self, forKey: .isMaintenance) { + self.isMaintenance = boolVal + } else if let boolValSnake = try? container.decodeIfPresent(Bool.self, forKey: .isMaintenanceSnake) { + self.isMaintenance = boolValSnake + } else if let strVal = try? container.decodeIfPresent(String.self, forKey: .isMaintenance) { + self.isMaintenance = (strVal.lowercased() == "true" || strVal == "1") + } else if let strValSnake = try? container.decodeIfPresent(String.self, forKey: .isMaintenanceSnake) { + self.isMaintenance = (strValSnake.lowercased() == "true" || strValSnake == "1") + } else { + self.isMaintenance = false + } self.title = try container.decodeIfPresent(String.self, forKey: .title) self.message = try container.decodeIfPresent(String.self, forKey: .message) @@ -89,6 +111,9 @@ public struct AppUpdateConfig: Codable, Sendable, Equatable { } else { self.releaseNotes = nil } + + self.metadata = (try? container.decodeIfPresent([String: String].self, forKey: .metadata)) + ?? (try? container.decodeIfPresent([String: String].self, forKey: .customPayload)) } public func encode(to encoder: Encoder) throws { @@ -100,5 +125,6 @@ public struct AppUpdateConfig: Codable, Sendable, Equatable { try container.encodeIfPresent(title, forKey: .title) try container.encodeIfPresent(message, forKey: .message) try container.encodeIfPresent(releaseNotes, forKey: .releaseNotes) + try container.encodeIfPresent(metadata, forKey: .metadata) } } diff --git a/Sources/AppUpdateKit/Core/AppUpdateEvaluator.swift b/Sources/AppUpdateKit/Core/AppUpdateEvaluator.swift new file mode 100644 index 0000000..86f453a --- /dev/null +++ b/Sources/AppUpdateKit/Core/AppUpdateEvaluator.swift @@ -0,0 +1,67 @@ +import Foundation + +/// Protocol for custom version evaluation strategies. +public protocol AppUpdateEvaluator: Sendable { + /// Evaluates version policy and returns corresponding update action. + func evaluate( + currentVersion: AppVersion, + config: AppUpdateConfig, + defaultStoreURL: URL? + ) -> AppUpdateAction +} + +/// Default standard evaluation engine. +public struct DefaultAppUpdateEvaluator: AppUpdateEvaluator { + public init() {} + + public func evaluate( + currentVersion: AppVersion, + config: AppUpdateConfig, + defaultStoreURL: URL? = nil + ) -> AppUpdateAction { + let title = config.title?.trimmingCharacters(in: .whitespacesAndNewlines) + let message = config.message?.trimmingCharacters(in: .whitespacesAndNewlines) + + if config.isMaintenance { + return .maintenance( + title: (title?.isEmpty == false) ? title! : "Maintenance", + message: (message?.isEmpty == false) ? message! : "The service is currently undergoing maintenance. Please try again later.", + metadata: config.metadata + ) + } + + let storeURL = config.storeURL ?? defaultStoreURL + + if let minVerStr = config.minimumVersion, + !minVerStr.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + let minVersion = AppVersion(minVerStr) + if currentVersion < minVersion, let storeURL = storeURL { + return .forceUpdate( + title: (title?.isEmpty == false) ? title! : "Update Required", + message: (message?.isEmpty == false) ? message! : "A new version of the app is available. Please update to continue.", + storeURL: storeURL, + version: config.latestAppVersion ?? minVersion, + releaseNotes: config.releaseNotes, + metadata: config.metadata + ) + } + } + + if let latestVerStr = config.latestVersion, + !latestVerStr.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + let latestVersion = AppVersion(latestVerStr) + if currentVersion < latestVersion, let storeURL = storeURL { + return .optionalUpdate( + title: (title?.isEmpty == false) ? title! : "Update Available", + message: (message?.isEmpty == false) ? message! : "A new version of the app is available. Would you like to update now?", + storeURL: storeURL, + version: latestVersion, + releaseNotes: config.releaseNotes, + metadata: config.metadata + ) + } + } + + return .none + } +} diff --git a/Sources/AppUpdateKit/Core/AppUpdateEvent.swift b/Sources/AppUpdateKit/Core/AppUpdateEvent.swift index a3265c9..e5aae78 100644 --- a/Sources/AppUpdateKit/Core/AppUpdateEvent.swift +++ b/Sources/AppUpdateKit/Core/AppUpdateEvent.swift @@ -20,22 +20,6 @@ public enum AppUpdateEvent: Sendable, Equatable { /// An error occurred during check or network fetch. case checkFailed(reason: String) - public static func == (lhs: AppUpdateEvent, rhs: AppUpdateEvent) -> Bool { - switch (lhs, rhs) { - case (.checkStarted, .checkStarted): - return true - case (.configFetched(let c1), .configFetched(let c2)): - return c1 == c2 - case (.evaluated(let a1), .evaluated(let a2)): - return a1 == a2 - case (.presented(let a1), .presented(let a2)): - return a1 == a2 - case (.userAction(let a1, let c1), .userAction(let a2, let c2)): - return a1 == a2 && c1 == c2 - case (.checkFailed(let r1), .checkFailed(let r2)): - return r1 == r2 - default: - return false - } - } + /// Custom lifecycle or developer-defined tracking event. + case custom(name: String, payload: [String: String]? = nil) } diff --git a/Sources/AppUpdateKit/Core/AppUpdateManager.swift b/Sources/AppUpdateKit/Core/AppUpdateManager.swift index 171e362..d0fccf3 100644 --- a/Sources/AppUpdateKit/Core/AppUpdateManager.swift +++ b/Sources/AppUpdateKit/Core/AppUpdateManager.swift @@ -20,9 +20,11 @@ public final class AppUpdateManager: ObservableObject { public static let shared = AppUpdateManager() @Published public private(set) var currentAction: AppUpdateAction = .none + @Published public private(set) var latestConfig: AppUpdateConfig? = nil @Published public private(set) var isChecking: Bool = false @Published public private(set) var lastCheckDate: Date? = nil + private var activeTask: Task? private var hasCheckedThisSession = false private let userDefaults: UserDefaults @@ -33,14 +35,15 @@ public final class AppUpdateManager: ObservableObject { } } - /// Performs update check according to the given policy and fetcher. + /// Performs update check according to the given policy, evaluator, and fetcher. @discardableResult public func check( policy: AppUpdateCheckPolicy = .always, currentVersion: AppVersion = AppUpdateChecker.currentInstalledVersion(), defaultStoreURL: URL? = nil, + evaluator: AppUpdateEvaluator = DefaultAppUpdateEvaluator(), onEvent: (@Sendable (AppUpdateEvent) -> Void)? = nil, - fetcher: @escaping () async throws -> AppUpdateConfig + fetcher: @Sendable @escaping () async throws -> AppUpdateConfig ) async -> AppUpdateAction { switch policy { case .oncePerSession: @@ -53,26 +56,51 @@ public final class AppUpdateManager: ObservableObject { break } + if let activeTask = activeTask { + return await activeTask.value + } + isChecking = true - defer { isChecking = false } - - let action = await AppUpdateChecker.check( - currentVersion: currentVersion, - defaultStoreURL: defaultStoreURL, - onEvent: onEvent, - fetcher: fetcher - ) - - self.currentAction = action - self.hasCheckedThisSession = true - let now = Date() - self.lastCheckDate = now - userDefaults.set(now, forKey: "AppUpdateKit.lastCheckDate") - - return action + + final class ConfigBox: @unchecked Sendable { + var config: AppUpdateConfig? + } + let box = ConfigBox() + + let task = Task { @MainActor [weak self] in + defer { + self?.activeTask = nil + self?.isChecking = false + } + + let action = await AppUpdateChecker.check( + currentVersion: currentVersion, + defaultStoreURL: defaultStoreURL, + evaluator: evaluator, + onEvent: { event in + if case .configFetched(let config) = event { + box.config = config + } + onEvent?(event) + }, + fetcher: fetcher + ) + + self?.latestConfig = box.config + self?.currentAction = action + self?.hasCheckedThisSession = true + let now = Date() + self?.lastCheckDate = now + self?.userDefaults.set(now, forKey: "AppUpdateKit.lastCheckDate") + + return action + } + + self.activeTask = task + return await task.value } - /// Handles user choice (update, remind later, dismiss) and updates state. + /// Handles user choice (update, remind later, dismiss, custom) and updates state. public func handleUserChoice(_ choice: AppUpdateUserChoice, onEvent: (@Sendable (AppUpdateEvent) -> Void)? = nil) { let action = currentAction onEvent?(.userAction(action: action, choice: choice)) @@ -86,12 +114,15 @@ public final class AppUpdateManager: ObservableObject { if !action.isRequired { currentAction = .none } + case .custom: + currentAction = .none } } /// Resets the cached check status. public func reset() { currentAction = .none + latestConfig = nil hasCheckedThisSession = false lastCheckDate = nil userDefaults.removeObject(forKey: "AppUpdateKit.lastCheckDate") @@ -104,9 +135,11 @@ public final class AppUpdateManager { public static let shared = AppUpdateManager() public private(set) var currentAction: AppUpdateAction = .none + public private(set) var latestConfig: AppUpdateConfig? = nil public private(set) var isChecking: Bool = false public private(set) var lastCheckDate: Date? = nil + private var activeTask: Task? private var hasCheckedThisSession = false private let userDefaults: UserDefaults @@ -117,14 +150,15 @@ public final class AppUpdateManager { } } - /// Performs update check according to the given policy and fetcher. + /// Performs update check according to the given policy, evaluator, and fetcher. @discardableResult public func check( policy: AppUpdateCheckPolicy = .always, currentVersion: AppVersion = AppUpdateChecker.currentInstalledVersion(), defaultStoreURL: URL? = nil, + evaluator: AppUpdateEvaluator = DefaultAppUpdateEvaluator(), onEvent: (@Sendable (AppUpdateEvent) -> Void)? = nil, - fetcher: @escaping () async throws -> AppUpdateConfig + fetcher: @Sendable @escaping () async throws -> AppUpdateConfig ) async -> AppUpdateAction { switch policy { case .oncePerSession: @@ -137,26 +171,51 @@ public final class AppUpdateManager { break } + if let activeTask = activeTask { + return await activeTask.value + } + isChecking = true - defer { isChecking = false } - - let action = await AppUpdateChecker.check( - currentVersion: currentVersion, - defaultStoreURL: defaultStoreURL, - onEvent: onEvent, - fetcher: fetcher - ) - - self.currentAction = action - self.hasCheckedThisSession = true - let now = Date() - self.lastCheckDate = now - userDefaults.set(now, forKey: "AppUpdateKit.lastCheckDate") - - return action + + final class ConfigBox: @unchecked Sendable { + var config: AppUpdateConfig? + } + let box = ConfigBox() + + let task = Task { @MainActor [weak self] in + defer { + self?.activeTask = nil + self?.isChecking = false + } + + let action = await AppUpdateChecker.check( + currentVersion: currentVersion, + defaultStoreURL: defaultStoreURL, + evaluator: evaluator, + onEvent: { event in + if case .configFetched(let config) = event { + box.config = config + } + onEvent?(event) + }, + fetcher: fetcher + ) + + self?.latestConfig = box.config + self?.currentAction = action + self?.hasCheckedThisSession = true + let now = Date() + self?.lastCheckDate = now + self?.userDefaults.set(now, forKey: "AppUpdateKit.lastCheckDate") + + return action + } + + self.activeTask = task + return await task.value } - /// Handles user choice (update, remind later, dismiss) and updates state. + /// Handles user choice (update, remind later, dismiss, custom) and updates state. public func handleUserChoice(_ choice: AppUpdateUserChoice, onEvent: (@Sendable (AppUpdateEvent) -> Void)? = nil) { let action = currentAction onEvent?(.userAction(action: action, choice: choice)) @@ -170,12 +229,15 @@ public final class AppUpdateManager { if !action.isRequired { currentAction = .none } + case .custom: + currentAction = .none } } /// Resets the cached check status. public func reset() { currentAction = .none + latestConfig = nil hasCheckedThisSession = false lastCheckDate = nil userDefaults.removeObject(forKey: "AppUpdateKit.lastCheckDate") diff --git a/Sources/AppUpdateKit/Core/AppVersion.swift b/Sources/AppUpdateKit/Core/AppVersion.swift index 15f64a2..61bacb3 100644 --- a/Sources/AppUpdateKit/Core/AppVersion.swift +++ b/Sources/AppUpdateKit/Core/AppVersion.swift @@ -1,27 +1,25 @@ import Foundation -/// Represents a semantic version with integer component normalization. -public struct AppVersion: Comparable, Sendable, Equatable, Hashable, CustomStringConvertible, ExpressibleByStringLiteral { - public let rawValue: String +/// Semantic version model with integer component normalization and metadata stripping. +public struct AppVersion: Comparable, Hashable, Sendable, CustomStringConvertible, ExpressibleByStringLiteral, RawRepresentable, Codable { + public let raw: String public let components: [Int] - public init(_ rawValue: String) { - self.rawValue = rawValue - // Strip prerelease (-...) and build metadata (+...) - let base = rawValue - .components(separatedBy: CharacterSet(charactersIn: "-+")) - .first ?? "" + public var rawValue: String { + return raw + } - let parsed = base - .split(separator: ".") - .compactMap { Int($0.trimmingCharacters(in: .whitespaces)) } + public init(rawValue: String) { + self.init(rawValue) + } - // Trim trailing zeros for normalization: [1, 2, 0, 0] -> [1, 2] - var normalized = parsed - while let last = normalized.last, last == 0 { - normalized.removeLast() - } - self.components = normalized + public init(_ raw: String) { + self.raw = raw + let withoutPrerelease = raw.split(separator: "-").first.map(String.init) ?? "" + let clean = withoutPrerelease.split(separator: "+").first.map(String.init) ?? "" + self.components = clean + .split(separator: ".") + .compactMap { Int($0) } } public init(stringLiteral value: String) { @@ -29,26 +27,50 @@ public struct AppVersion: Comparable, Sendable, Equatable, Hashable, CustomStrin } public var description: String { - rawValue + return raw } - public func hash(into hasher: inout Hasher) { - hasher.combine(components) + public static func < (lhs: AppVersion, rhs: AppVersion) -> Bool { + let count = max(lhs.components.count, rhs.components.count) + for i in 0.. Bool { - lhs.components == rhs.components + let count = max(lhs.components.count, rhs.components.count) + for i in 0.. Bool { - let maxCount = max(lhs.components.count, rhs.components.count) - for index in 0.. AppUpdateAction { + // If maintenance, ignore and force optional update for VIP test + return .optionalUpdate( + title: "VIP Update", + message: "Exclusive build", + storeURL: config.storeURL ?? defaultStoreURL! + ) + } } - """.data(using: .utf8)! - let config = try JSONDecoder().decode(AppUpdateConfig.self, from: json) - XCTAssertEqual(config.releaseNotes?.count, 2) - XCTAssertEqual(config.releaseNotes?[0], "Added dark mode") - XCTAssertEqual(config.releaseNotes?[1], "Performance improvements") + let config = AppUpdateConfig(storeURL: testURL, isMaintenance: true) + let action = AppUpdateChecker.evaluate( + currentVersion: "1.0.0", + config: config, + evaluator: GracePeriodEvaluator() + ) + + XCTAssertEqual(action.title, "VIP Update") } } diff --git a/Tests/AppUpdateKitTests/AppUpdateManagerTests.swift b/Tests/AppUpdateKitTests/AppUpdateManagerTests.swift index 997d79e..5ad32cf 100644 --- a/Tests/AppUpdateKitTests/AppUpdateManagerTests.swift +++ b/Tests/AppUpdateKitTests/AppUpdateManagerTests.swift @@ -36,9 +36,11 @@ final class AppUpdateManagerTests: XCTestCase { XCTAssertEqual(action, .optionalUpdate( title: "Update Available", message: "A new version of the app is available. Would you like to update now?", - storeURL: testURL + storeURL: testURL, + version: AppVersion("2.0.0") )) XCTAssertEqual(manager.currentAction, action) + XCTAssertEqual(manager.latestConfig, config) XCTAssertFalse(manager.isChecking) XCTAssertNotNil(manager.lastCheckDate) @@ -61,20 +63,24 @@ final class AppUpdateManagerTests: XCTestCase { let defaults = UserDefaults(suiteName: suiteName)! let manager = AppUpdateManager(userDefaults: defaults) + final class CounterBox: @unchecked Sendable { + var count = 0 + } + let box = CounterBox() + let config = AppUpdateConfig(minimumVersion: "2.0.0", storeURL: testURL) - var fetchCount = 0 _ = await manager.check(policy: .oncePerSession, currentVersion: "1.0.0") { - fetchCount += 1 + box.count += 1 return config } - XCTAssertEqual(fetchCount, 1) + XCTAssertEqual(box.count, 1) // Second check with oncePerSession policy should not invoke fetcher _ = await manager.check(policy: .oncePerSession, currentVersion: "1.0.0") { - fetchCount += 1 + box.count += 1 return config } - XCTAssertEqual(fetchCount, 1) + XCTAssertEqual(box.count, 1) } } diff --git a/art/banner.svg b/art/banner.svg new file mode 100644 index 0000000..b77f9e9 --- /dev/null +++ b/art/banner.svg @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AppUpdateKit + + + Zero-Dependency, Fail-Safe App Update & Maintenance Engine for Swift + + + + + + + + + 0 Dependencies + + + + + + Swift 6 Ready + + + + + + Headless & UI Optional + + + + + + microCMS / JSON + + + +